<?php

namespace App\DataTables\Warehouses;

use App\Models\LocalizationManagement\City;
use App\Models\SecurityManagement\Role;
use App\Models\StockManagement\Stock;
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 Illuminate\Support\Facades\DB;
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 WarehouseDataTableFieldDatatable extends DataTable{


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

    public function getWarehouseType(){
        return $this->request()->get("warehouseType");
    }

    /**Build DataTable class.
     * @param QueryBuilder $query Results from query() method.
     * @return EloquentDataTable
     */
    public function dataTable(QueryBuilder $query){
        return (new EloquentDataTable($query))
                ->editColumn('actions', function ($row){
                     return view('backend.stocks.warehouses.blocs.datatable-actions',compact("row"));
                })
                ->editColumn('managers', function ($row){
                   // return view('backend.stocks.warehouses.blocs.datatable-list-managers',compact("row"));
                    return count($row->managers);
                })
                ->editColumn('cities', function ($row){
                    // return view('backend.stocks.warehouses.blocs.datatable-list-managers',compact("row"));
                    return 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) ? __("Oui") : __("Non");
                })
                ->addColumn('type', function ($row){
                    return $row->type->name ?? "";
                })
                ->addColumn('city', function ($row){
                    return $row->city->name ?? "";
                })
                ->setRowId('id')
            ;
    }

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

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

        if ($this->request->filled("warehouseType")){
            $this->warehouseType = $this->request()->get("warehouseType");
        }
        return $warehouse->newQuery()
                    ->with(["type","managers"])
                    //->where(WareHouseType::FK_ID,$this->warehouseType)
                    ->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->getTableId())
            ->columns($this->getColumns())
            ->select(['enable' => true,'style' => 'os' ,"selector" => 'td:first-child',"multi" => false])
            ->addTableClass('table-striped')
            ->setTableAttribute("style", "width:100%;")
            ->minifiedAjax(route("admin.stocks.warehouses.index"))
            ->dom('Bfrtipl')
            // ->orderBy(1)
            ->buttons($this->getButtons())
            ->editor(
                Editor::make($this->getEditor())
                    ->idSrc("id")
                    ->fields($this->getFields())
                    ->ajax([
                        "url" => route('admin.stocks.warehouses.dt-edit'),
                        "type" => "post"
                    ])
            )
            ;
    }

    protected function getFields(){

        $cities = City::skip(100)->take(100)->get()->pluck("id","name");
        $warehouseType = blank($this->warehouseType) ? WareHouseType::STORE : $this->warehouseType;
        $fields = [
            Fields\Hidden::make('warehouse_type_code',__("Type"))
                         ->data('warehouse_type_code'),
            Fields\Text::make('name',__("Name"))->data('name'),

            Fields\Select::make('city',__('Ville de Localisation'))
                        ->options($cities)
                        ->attr("data-plugin-multiselect","")
                        ->data('city_id'),
            Fields\Select::make('managers[]',__('Gérants'))
                ->options(Admin::stockManagers()->get()->pluck("id","fullName"))
                ->attr("data-plugin-multiselect","")
                ->attr("multiple",true)
                ->data('managers_ids')
        ];

        if ($warehouseType == WareHouseType::POINT_OF_SALE){
            $fields[] = Fields\Select::make('store_id',__('Magasin Principal'))
                                        ->options($cities)->attr("data-plugin-multiselect","")
                                        ->data('store_id');

            $q = DB::table("cities")->limit(100);
            $cities = Options::table($q, "name", "id");
            $fields[] = Fields\Field::make('cities[]',__('Villes Approvisionnées'))
                            ->type('datatable')
                            ->config([
                                    "ajax" => [
                                    "url" => route("admin.cities.dt-list"),
                                    "type" => "get",
                                    "contentType" => "application/json",
                                ],
                                "serverSide" => true,
                                "columns" => [
                                    [ "title" => "<input type='checkbox' class='dt-checkbox-all' onclick='select_all_td()'/>", "data" => null,],
                                    [ "title" => __('Id'), "data" => "id",],
                                    [ "title" => __('Name'), "data" => "name",],
                                ],
                                "select" => [
                                    "enable" => true,
                                    "style" => 'multi',
                                ],
                                "buttons" => [
                                    "reload",
                                    "export"
                                ]])
                            ->optionsPair(["label" => "name", "value" => "id",])
                           // ->options($cities)
                           // ->options($cities)
                            ->attr("data-plugin-multiselects","")
                            ->attr("multiple",true)
                            ->attr("name","cities[]")
                            ->data('cities_id');

        }else{
            $fields[] = Fields\Radio::make('is_bad_goods',__('Deffectueux ?'))
                            ->options(Options::yesNo())
                            ->attr("data-plugin-multiselect","")
                            ->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')
                ->title(__("Ville"))
                ->data('city')
                ->searchable(true)
                ->orderable(true)
                ->footer(__("Ville")),

            Column::make("managers")
                ->title(__('Gérants'))
                ->data("managers")
                ->addClass("right")
                ->searchable(false)
                ->orderable(false)
                ->footer(__("Gérants"))
        ];

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

        $columns[] =  Column::make(__('Créée Le'),"created_at")
                        ->data("created_at")
                        ->footer(__('Créée Le'));

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

        $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->getEditor();

        if ($user->can('role-create')){
            $buttons[] = Button::make('create')->editor($editor);
        }
//        if ($user->can('role-update')){
//            $icon_edit = '<i class="fa fa-edit"></i> ';
//            $buttons[] = Button::make('edit')
//                                    ->formTitle(__("Modifier un enregistrement"))
//                                    ->text($icon_edit)
//                                    ->className("btn-info")
//                                    ->formButtons([
//                                        "className" => "btn-info",
//                                        "text" => $icon_edit.__('Modifier'),
//                                        "action" => 'function() { this.submit(); }',
//                                    ])
//                                    ->editor($editor);
//        }

        if ($user->can('role-delete')){
            $icon_remove = '<i class="fa fa-trash"></i> ';
            $removing_message = __("Supprimer les lignes sélectionnés?");
            $buttons[] =  Button::make('remove')
                ->formTitle(__("Suppression"))
                ->text($icon_remove)
                ->className("btn-danger")
                ->formButtons([
                    "className" => "btn-danger",
                    "text" => $icon_remove.__('Supprimer'),
                    "action" => 'function() { this.submit(); }',
                ])
                ->formMessage("function (e,dt){
                                    let rows = dt.rows(e.modifier()).data();
                                    let count = rows.length;
                                   // console.log(rows.length,'count = '+count);
                                    return '$removing_message';
                                }")
                ->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(){

    }
}
