<?php

namespace App\DataTables\Warehouses;


use App\Models\StockManagement\Warehouse;
use App\Models\StockManagement\WareHouseType;
use App\Models\UserManagement\Admin;
use App\Models\UserManagement\User;
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\Html\Editor\Fields\Options;
use Yajra\DataTables\Services\DataTable;

class WarehouseDataTable extends DataTable{


    protected $warehouseType ;
    public function __construct($warehouseType = WareHouseType::STORE){
          parent::__construct();
      //  $this->warehouseType = $this->request()->get("warehouseType");
        $this->warehouseType = $warehouseType;
        if (request()->filled("warehouseType")){
            $this->warehouseType = request()->get("warehouseType");
        }
    }

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

    protected function getEditorName(){
        return "editor_$this->warehouseType";
    }
    protected function getIdTable(){
        return "table_$this->warehouseType";
    }

    /**Get query source of dataTable.
     * @param Warehouse $model
     * @return QueryBuilder
     */
    public function query(Warehouse $model){

        return $model->newQuery()
                    ->with(["type","managers","city","cities"])
                    ->when(!blank($this->warehouseType),function ($query){
                        return $query->where(WareHouseType::FK_ID,$this->warehouseType);
                    })
                    ->latest("updated_at");
    }


    public function html(){

        return $this->builder()
            ->setTableId($this->getIdTable())
            ->columns($this->getColumns())
            ->select(['enable' => true,'style' => 'os' ,"selector" => 'td:first-child',"multi" => true])
            ->addTableClass('table-striped')
            ->setTableAttribute("style", "width:100%;")
            ->minifiedAjax(route("admin.stocks.warehouses.index",["warehouseType"=>$this->warehouseType]))
            ->dom('Bfrtipl')
            // ->orderBy(1)
            ->buttons($this->getButtons())
            ->editor(
                Editor::make($this->getEditorName())
                    ->idSrc("id")
                    ->fields($this->getFields())
                    ->ajax([
                        "url" => route('admin.stocks.warehouses.dt-edit'),
                        "type" => "post"
                    ])
            )
            ;
    }

    protected function getFields(){

        $country = selected_country();
      //  $countryName = user_location();
        $cities = $country->cities->pluck("id","name");
        //$cities = City::skip(100)->take(100)->get()->pluck("id","name");
       // $cities = City::active()->get()->pluck("id","name");
        $warehouseType = blank($this->warehouseType) ? WareHouseType::STORE : $this->warehouseType;

        $managers = Admin::get()->pluck("id","fullName");
        $fields = [
            Fields\Hidden::make(WareHouseType::FK_ID,__("Type"))->default($warehouseType),
            Fields\Text::make('name',__("Name"))->data('name'),

            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')
        ];

        if ($warehouseType == WareHouseType::POINT_OF_SALE){
            $stores = Warehouse::stores()->get()->pluck("id","name");
            $fields[] = Fields\Select::make('store_id',__('Main Store'))
                                        ->options($stores)
                                        ->attr("data-plugin-multiselect","")
                                        ->data('store_id');

            //$q = DB::table("cities")->limit(100);
            //$cities = Options::table($q, "name", "id");
            $fields[] = Fields\Field::make('cities',__('Cities Supplied'))
                            ->type('select')
                            ->options($cities)
                            ->multiple(true)
                            ->attr("data-plugin-multiselect","")
                            ->data('cities_id');

        }else{
            $fields[] = Fields\Radio::make('is_bad_goods',__('Deffect ?'))
                            ->options(Options::yesNo())
                             ->fieldInfo(__("Determine if it is a warehouse intended for obsolete products, damaged, in poor condition ..."))
                            ->data('is_bad_goods');
        }
        return $fields;
    }

    protected function getColumns() :array {
        $warehouseType = blank($this->warehouseType) ? WareHouseType::STORE : $this->warehouseType;
        $columns = [
            Column::computed("")
                ->title("<input type='checkbox' class='dt-checkbox-all' onclick='select_all_td()'/>")
                ->exportable(false)
                ->printable(false)
                ->className("select-checkbox")
                ->content("")
                ->data(""),

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

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

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

        if ($warehouseType == WareHouseType::POINT_OF_SALE){
            $columns[] =   Column::make("cities")
                                    ->title(__('Cities Supplied'))
                                    ->data("cities")
                                    ->addClass("right")
                                    ->searchable(false)
                                    ->orderable(false)
                                    ->footer(__('Cities Supplied'));
        }else{
            $columns[] =  Column::make(__('Deffect ?'),"bad_goods")
                                ->data("bad_goods")
                                ->searchable(false)
                                ->footer(__('Deffect ?'));
        }

        $columns[] =  Column::make(__('Created At'),"created_at")
                        ->data("created_at")
                        ->footer(__('Created At'));

        $columns[] = Column::make(__('By'),"created_by")
                            ->data("created_by")
                            ->searchable(false)
                            ->footer(__('By'));

        $columns[] =   Column::make('actions')
                        ->title(__("Actions"))
                        ->data('actions')
                        ->searchable(false)
                        ->orderable(false)
                        ->footer(__("Actions"));
        return $columns;
    }

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

        if ($user->can('st-warehouse-create')){
            $buttons[] = Button::make('create')->editor($editor);
        }

        if ($user->can('st-warehouse-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 'Role_file' . date('d-m-Y-H-i-s');
    }

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

    }

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

    }

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

    }
}
