<?php

namespace App\DataTables\Roles;

use App\Models\SecurityManagement\Permission;
use App\Models\SecurityManagement\Role;
use App\Models\StockManagement\Stock;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Yajra\DataTables\EloquentDataTable;
use Yajra\DataTables\Exceptions\Exception;
use Yajra\DataTables\Html\Builder as HtmlBuilder;
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 RoleDataTable 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 = [];
                   $notEditables = [
                       Role::SUPER_ADMIN,
                       Role::CUSTOMER,
                   ];

                   if (!in_array($row->name,$notEditables)){
                       $permissions['edit'] =  "role-update";
                       $permissions['remove'] =  "role-delete";
                   }
                   return view('shared.datatable-column-actions',compact("permissions"));
               })
                ->editColumn('permissions', function ($row){
                    return view('backend.roles.blocs.datatable-list-permissions',compact("row"));
                })
                ->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 ?? "";
                })
                ->setRowId('id')
                ->setRowData([
                    "data-id" => function ($row){
                       return $row->id;
                    },
                ])
            ;
    }

    /**Get query source of dataTable.
     * @param Role $model
     * @return QueryBuilder
     */
    public function query(Role $model){
        return $model->newQuery()
                    ->with("permissions")
                    ->where("editable",true)
                    ->latest("updated_at");
    }


    public function html(){

        return $this->builder()
            ->setTableId('roles-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.roles.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\Select::make('permissions',__('Permissions'))
                            ->options(Permission::admin()->get()->pluck("id","description"))
                            ->multiple(true)
                            ->attr("data-plugin-multiselect","")
                            ->data('permissions_ids') ,

                        Fields\TextArea::make('description',__("Description"))
                               ->attr("rows","3")
                               ->attr("cols","3")
                               ->data('description'),

                    ])
                    ->ajax([
                        "url" => route('admin.roles.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('description')
                ->title(__("Description"))
                ->data('description')
                ->searchable(false)
                ->orderable(false)
                ->footer(__("Description")),

            Column::make("permissions")
                ->title(__('Permissions'))
                ->data("permissions")
                ->addClass("right")
                ->searchable(false)
                ->orderable(false)
                ->footer(__("Permissions"))

            ,
            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('role-create')){
            $buttons[] = Button::make('create')->editor("editor");
        }
        if ($user->can('role-update')){
           // $buttons[] = Button::make('edit')->editor("editor");
        }

        if ($user->can('role-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(){

    }
}
