<?php

namespace App\DataTables\Invoices;

use App\Models\Customer;
use App\Models\Farmer;
use App\Models\Sale;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Services\DataTable;

class SaleDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        return datatables($query)
            ->addIndexColumn()
            ->editColumn('created_at', static function ($data) {
                return $data->created_at->format('d M Y');
            })
            ->editColumn('customer_id', static function ($data) {
                $customer = Customer::find($data->customer_id);
                if (!$customer) {
                    $customer = Farmer::find($data->customer_id);
                }
                return $customer ? $customer->name : 'Unknown';
            })
            ->editColumn('payment_type', static function ($data) {
                return sprintf(
                    "<span class='label label-sm label-%s'>%s</span>",
                    $data->payment_type == 'partial' ? 'warning' : 'success', 
                    ucfirst($data->payment_type)
                );
            })
            ->editColumn('sub_total',static function($data){
                return number_format($data->sub_total,2);
            })
            ->editColumn('discount',static function($data){
                return number_format( $data->discount,2 );
            })
            ->editColumn('grand_total', static function($data){
                return number_format($data->grand_total,2);
            })
            ->editColumn('due', static function($data){
                return number_format($data->due,2);
            })
            ->addColumn('action',function ($data){
                return $this->getActionColumn($data);
            })
            ->rawColumns(['grand_total','action','payment_type','due'])
            ->setRowClass('gradeX');
    }

    /**
     * @param $data
     * @return string
     */
    protected function getActionColumn($data): string
    {
        $showUrl = route('admin.sales.show', $data->id);
        $showFarmer = route('admin.farmerinvoice.show',$data->id);
        $show = !empty($data->customer_id) ? $showUrl : $showFarmer;
        
        $buttons = "";
        
        if (auth()->user()->can('view_sale') || auth()->user()->hasRole('superadmin')) {
             $buttons .= "<a class='btn dark btn-outline btn-circle' data-value='$data->id' href='$show'><i class='material-icons'>visibility</i></a> ";
        }

        if (auth()->user()->can('edit_sale') || auth()->user()->hasRole('superadmin')) {
             $editUrl = route('admin.sales.edit', $data->id);
             $buttons .= "<a class='btn blue btn-outline btn-circle' href='$editUrl'><i class='material-icons'>edit</i></a> ";
        }

        if (auth()->user()->can('delete_sale') || auth()->user()->hasRole('superadmin')) {
             $buttons .= "<button class='btn red btn-outline btn-circle delete' data-value='$data->id' ><i class='material-icons'>delete</i></button>";
        }
        
        return $buttons;
    }

    /**
     * @param $data
     * @return string
     */
    protected function getViewColumn($data): string
    {
        $showUrl    = route('admin.sales.show', $data->id);
        $showFarmer = route('admin.farmerinvoice.show',$data->id);
        $show       = ! empty($data->customer_id) ? $showUrl : $showFarmer;
        return "<a class='btn dark btn-outline btn-circle' data-value='$data->id' href='$show'><i class='material-icons'>visibility</i></a>";
    }

    /**
     * Get query source of dataTable.
     *
     * @param \App\Models\User $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query()
    {
        $query = Sale::when(request()->from && request()->to,function( $query ){
            $startDate = Carbon::createFromFormat('Y-m-d', request()->from);
            $endDate = Carbon::createFromFormat('Y-m-d', request()->to);
            $query->whereBetween('created_at', [$startDate, $endDate]);
        })->latest();
        
        if ( ( $type = request('type') ) && $type == 'due' ) {
            $query->where('due', '>', 0);
        } 

        if (!auth()->user()->hasRole('superadmin')) {
            $query->whereIn('branch_id', auth()->user()->getAccessibleBranchIds());
        }
        
        return $query;
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->addAction([
                        'width' => '12%',
                        'printable' => false,
                        'exportable' => false,
                        'searchable' => false
                    ])
                    ->paging(true)
                    ->lengthMenu([[50, 100,500, -1], [50, 100,500, 'All']])
                    ->scrollX(true)
                    ->parameters($this->getBuilderParameters());
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            [
                'defaultContent' => '',
                'data'           => 'DT_RowIndex',
                'name'           => 'DT_RowIndex',
                'title'          => 'S. No',
                'render'         => null,
                'orderable'      => false,
                'searchable'     => false,
                'exportable'     => false,
                'printable'      => true,
                'width'          => '8%',

            ],
            [
                'data'              => 'id',
                'name'              => 'id',
                'title'             => 'ID No.',
                'orderable'         => false,
                'searchable'        => false,
                'exportable'        => false,
                'printable'         => false,
                'visible'           => false
            ],
            [
                'data'           => 'created_at',
                'name'           => 'created_at',
                'title'          => 'Date',
                'orderable'      => true,
                'searchable'     => false,
                'exportable'     => true,
                'printable'      => true,
                'visible'        => true
            ],
            [
                'data'           => 'branch_id',
                'name'           => 'branch_id',
                'title'          => 'Branch',
                'orderable'      => false,
                'searchable'     => false,
                'exportable'     => false,
                'printable'      => false,
                'visible'        => false
            ],
            [
                'data'           => 'sale_no',
                'name'           => 'sale_no',
                'title'          => 'Inv-No.',
                'orderable'      => true,
                'searchable'     => true,
                'exportable'     => true,
                'printable'      => true,
                'visible'        => true,
                'width'          => '10%'
            ],
            [
                'data'           => 'customer_id',
                'name'           => 'customer_id',
                'title'          => 'Name',
                'orderable'      => true,
                'searchable'     => false,
                'exportable'     => true,
                'printable'      => true,
                'visible'        => true,
            ],
            [
                'data'           => 'payment_type',
                'name'           => 'payment_type',
                'title'          => 'Paid Type',
                'orderable'      => true,
                'searchable'     => true,
                'exportable'     => true,
                'printable'      => true,
                'visible'        => true
            ],
            [
                'data'           => 'sub_total',
                'name'           => 'sub_total',
                'title'          => 'Sub Total',
                'orderable'      => true,
                'searchable'     => true,
                'exportable'     => true,
                'printable'      => true,
                'visible'        => true
            ],
            [
                'data'           => 'discount',
                'name'           => 'discount',
                'title'          => 'Discount',
                'orderable'      => true,
                'searchable'     => true,
                'exportable'     => true,
                'printable'      => true,
                'visible'        => true
            ],
            [
                'data'           => 'grand_total',
                'name'           => 'grand_total',
                'title'          => 'Grand Total',
                'orderable'      => true,
                'searchable'     => true,
                'exportable'     => true,
                'printable'      => true,
                'visible'        => true
            ],
            [
                'data'           => 'due',
                'name'           => 'due',
                'title'          => 'Due',
                'orderable'      => true,
                'searchable'     => true,
                'exportable'     => true,
                'printable'      => true,
                'visible'        => true
            ],
            [
                'data'           => 'user_id',
                'name'           => 'user_id',
                'title'          => 'ID No.',
                'orderable'      => false,
                'searchable'     => false,
                'exportable'     => false,
                'printable'      => false,
                'visible'        => false
            ],
        ];
    }

    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename()
    {
        return 'InvoicesSale_' . date('YmdHis');
    }
}
