<?php

namespace App\DataTables\Invoices;

use App\Models\Purchase;
use App\User;
use Carbon\Carbon;
use Yajra\DataTables\Services\DataTable;
use function foo\func;

class PurchaseDataTable 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('company_id', static function ($data) {
                return $data->company->name;
            })
            ->editColumn('grand_total', static function ($data) {
                return "<b>{$data->grand_total}</b>";
            })
            ->editColumn('due', static function ($data) {
                return "<b>{$data->due}</b>";
            })
            ->editColumn('payment_type', static function ($data) {
                return sprintf(
                    '<span class="label label-sm label-%s">%s</span>',
                    $data->due > 0 ? 'warning' : 'success',
                    $data->due > 0 ? 'Partial' : 'Paid',
                );
            })
            ->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.purchases.show', $data->id);
        $deleteUrl = route('admin.purchases.destroy', $data->id);
        $csrf = csrf_token();
        
        $buttons = "";

        if (auth()->user()->can('view_purchase') || auth()->user()->hasRole('superadmin')) {
             $buttons .= "<a class='btn dark btn-outline btn-circle' data-value='$data->id' href='$showUrl'><i class='material-icons'>visibility</i></a> ";
        }

        if (auth()->user()->can('edit_purchase') || auth()->user()->hasRole('superadmin')) {
             $editUrl = route('admin.purchases.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_purchase') || auth()->user()->hasRole('superadmin')) {
            $buttons .= "<button class='btn red btn-outline btn-circle delete' type='submit' data-value='$data->id' onclick='deleteInvoice($data->id)' ><i class='material-icons'>delete</i></button>
                        <form id='delete-form-{$data->id}' action='{$deleteUrl}' method='post' style='display:none;'>
                                            <input type='hidden' name='_token' value='{$csrf}'>
                                            <input type='hidden' name='_method' value='DELETE'>
                                        </form>";
        }

        return $buttons;
    }

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

    }

    /**
     * Get query source of dataTable.
     *
     * @param Purchase $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
   public function query()
    {
        $query = Purchase::with(['company', 'branch', 'user']);

        if (request()->filled('from') && request()->filled('to')) {
            $startDate = Carbon::parse(request()->from)->startOfDay();
            $endDate = Carbon::parse(request()->to)->endOfDay();
            $query->whereBetween('purchase_date', [$startDate, $endDate]);
        }
        
        if (request('type') == 'due') {
            $query->where('due', '>', 0);
        } 

        if (request()->filled('company_id')) {
            $query->where('company_id', request('company_id'));
        }
        
        if (!auth()->user()->hasRole('superadmin')) {
             $query->whereIn('branch_id', auth()->user()->getAccessibleBranchIds());
        }
        
        return $query->latest('purchase_date');
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
                    ->columns($this->getColumns())
                    ->minifiedAjax(url()->full())
                    ->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'    => 'purchase_date',
                'name'    => 'purchase_date',
                'title'   => 'Date',
                'orderable'      => true,
                'searchable'     => true,
                'exportable'     => true,
                'printable'      => true,
                'visible' => true
            ],
            [
                'data'    => 'purchase_no',
                'name'    => 'purchase_no',
                'title'   => 'Inv-No.',
                'orderable'      => true,
                'searchable'     => true,
                'exportable'     => true,
                'printable'      => true,
                'visible' => true
            ],
            [
                'data'    => 'company_id',
                'name'    => 'company_id',
                'title'   => 'Company',
                'orderable'      => true,
                'searchable'     => true,
                'exportable'     => true,
                'printable'      => true,
                'visible' => true
            ],
            [
                'data'    => 'payment_type',
                'name'    => 'payment_type',
                'title'   => 'Payment 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 'InvoicesPurchase_' . date('YmdHis');
    }
}
