<?php

namespace App\DataTables\BillingDesks;

use App\Models\OrderManagement\BillingDesk;
use App\Models\UserManagement\Admin;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Yajra\DataTables\EloquentDataTable;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;

class BillingDeskDataTable extends DataTable{

    //Export Columns with Custom Title
//    protected array|string $exportColumns = [
//        ['data' => 'name', 'title' => 'Name'],
//        ['data' => 'email', 'title' => 'Registered Email'],
//    ];
//
//    protected array $excludeFromPrint = [
//        "action"
//    ];

    /**Build DataTable class.
     * @param QueryBuilder $query Results from query() method.
     * @return EloquentDataTable
     */
    public function dataTable(QueryBuilder $query){
        return (new EloquentDataTable($query))
               // ->addColumn('action', '')
               ->addColumn('actions', function ($row){
                   $permissions = [];
                   $permissions['edit'] =  "pos-update";
                   $permissions['remove'] =  "pos-delete";
                   return view('shared.datatable-column-actions',compact("permissions"));
               })
                ->editColumn('managers_count', function ($row){
                    // return view('backend.stocks.warehouses.blocs.datatable-list-managers',compact("row"));
                    return format_amount(count($row->managers));
                })
                ->editColumn('created_at', function ($row){
                    return format_date( $row->created_at,__("d-m-Y H:i:s"));
                })
                ->editColumn('created_by', function ($row){
                    return $row->createdBy->fullName ?? "--";
                })
                ->addColumn('type', function ($row){
                    return $row->type->name ?? "";
                })
                ->addColumn('city', function ($row){
                    return $row?->city?->only("id",'name') ?? [];
                })
                ->addColumn('managers_ids', function ($row){
                    return $row?->managers?->pluck("id")->toArray();
                })
                ->editColumn('managers', function ($row){
                     return $row?->managers?->only("id","fullName")->toArray();
                })
                ->setRowId('id')
            ;
    }

    /**Get query source of dataTable.
     * @param BillingDesk $model
     * @return QueryBuilder
     */
    public function query(BillingDesk $model){
        return $model->newQuery()
                    ->with("managers","city")
                    ->latest("updated_at");
    }


    public function html(){

        $managers = Admin::get()->pluck("id","fullName");

        $country = selected_country();
        $cities = $country->cities->pluck("id","name");

        return $this->builder()
            ->setTableId('billing-desks-table')
            ->columns($this->getColumns())
            ->select(['enable' => true,'style' => 'os' ,"selector" => 'td:first-child',"multi" => false])
            ->addTableClass('table-striped')
            ->setTableAttribute("style", "width:100%;")
            ->minifiedAjax(route("admin.billing-desks.index"))
            ->dom('Bfrtipl')
            // ->orderBy(1)
            ->buttons($this->getButtons())
//            ->parameters([
//               "searchPane" => ['controls' => false]
//            ])
            ->editor(
                Editor::make("editor")
                    ->idSrc("id")
                    ->fields([
                        Fields\Text::make('name',__("Name"))->data('name'),
                        Fields\Text::make('code',__("Code"))->data('code'),
                        Fields\Select::make('city_id',__('City of Localisation'))
                                    ->options($cities)
                                    ->attr("data-plugin-multiselect","")
                                    ->data('city_id'),

                        Fields\Select::make('managers',__('Managers'))
                            ->options($managers)
                            ->multiple(true)
                            ->attr("data-plugin-multiselect","")
                            ->data('managers_ids')

                    ])
                    ->ajax([
                        "url" => route('admin.billing-desks.dt-edit'),
                        "type" => "post"
                    ])
            );
    }

    protected function getColumns() :array {
        return [
//            Column::computed("")
//                ->title("<input type='checkbox' class='dt-checkbox-all' onclick='select_all_td()'/>")
//                ->exportable(false)
//                ->printable(false)
//                ->className("select-checkbox")
//                ->content("")
//                ->width(10)
//                ->data(""),

            Column::make('name')
                ->title(__("Name"))
                ->data('name')
                ->searchable(true)
                ->orderable(true)
                ->footer(__("Name")),

            Column::make('code')
                ->title(__("Code"))
                ->data('code')
                ->searchable(true)
                ->orderable(true)
                ->footer(__("Code")),


            Column::make('city.name')
                ->title(__("City"))
                ->data('city.name')
                ->searchable(true)
                ->orderable(true)
                ->footer(__("City")),

            Column::make("managers.fullName")
                ->title(__('Managers'))
                ->data("managers_count")
                ->addClass("right")
                ->searchable(false)
                ->orderable(false)
                ->footer(__("Managers"))

            ,
            Column::make(__('Created At'),"created_at")
                   ->data("created_at")
                   ->footer(__('Created At')),
            Column::make(__('By'),"created_by")
                   ->data("created_by")
                   ->footer(__('By')),

            Column::computed('actions')
                ->exportable(false)
                ->printable(false)
                ->width(60)
                ->addClass('text-center'),

//            [
//                'defaultContent' => '',
//                'data'           => 'action',
//                'name'           => 'action',
//                'title'          => __("Action"),
//                'render'         => null,
//                'orderable'      => false,
//                'searchable'     => false,
//                'exportable'     => false,
//                'printable'      => false,
//                'footer'         => __("Action"),
//            ]
        ];
    }

    protected function getButtons(){
        $user = auth(activeGuard())->user();
        $buttons = [];

        if ($user->can('pos-create')){
            $buttons[] = Button::make('create')->editor("editor");
        }
        if ($user->can('pos-update')){
           // $buttons[] = Button::make('edit')->editor("editor");
        }

        if ($user->can('pos-delete')){
            $buttons[] =  Button::make('remove')->editor("editor");
        }
        $buttons[] = Button::make('reload');
        $buttons[] = Button::make('export');

        return $buttons;
    }
    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename() : string{
        return 'POS_file' . date('d-m-Y-H-i-s');
    }

    /**
     * @inheritDoc
     */
    public function excel(){

    }

    /**
     * @inheritDoc
     */
    public function csv(){

    }

    /**
     * @inheritDoc
     */
    public function pdf(){

    }
}
