<?php

namespace App\DataTables\ProductManagement\Categories;

use App\Models\ProductManagement\Category;
use App\Models\SecurityManagement\Permission;
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 CategoryDataTable 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'] =  "category-update";
                   //$permissions['remove'] =  "category-delete";
                   return view('shared.datatable-column-actions',compact("permissions"));
               })
                ->editColumn('products_count_formated', function ($row){
                    return format_amount(count($row->products));
                })
                ->editColumn('children_formated', function ($row){
                    return format_amount(count($row->children));
                })
                ->editColumn('created_at', function ($row){
                    return format_date( $row->created_at,__("d-m-Y H:i:i"));
                })
                ->editColumn('created_by', function ($row){
                    return $row->createdBy->fullName ?? "---";
                })
                ->editColumn('parent_name', function ($row){
                    return $row->parent->name ?? "---";
                })
                ->setRowId('id')
//                ->setRowData([
//                    "data-id" => function ($row){
//                       return $row->id;
//                    },
//                ])
            ;
    }

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


    public function html(){
        $categories = Category::active()->get();
        $categories = $categories->prepend(['id'=>null, "name" => "Nothing"])->pluck("id","name")->toArray();

        return $this->builder()
            ->setTableId('categories-table')
            ->columns($this->getColumns())
            ->select(['enable' => false,'style' => 'os' ,"selector" => 'td:first-child',"multi" => false])
            ->addTableClass('table-striped')
            ->setTableAttribute("style", "width:100%;")
            ->minifiedAjax(route("admin.categories.index"))
            ->dom('Bfrtipl')
            // ->orderBy(1)
            ->buttons($this->getButtons())

            ->editor(
                Editor::make("editor")
                    ->idSrc("id")
                    ->fields([
                        Fields\Text::make('name',__("Name"))->data('name'),

                        Fields\Select::make('parent_id',__('Parent'))
                            ->options($categories)
                            ->attr("data-plugin-multiselect","")
                            ->data('parent_id') ,

                        Fields\Radio::make('active',__('Status'))
                                    ->options([
                                        ['label' => __('Active'), 'value' => 1],
                                        ['label' => __('Inactive'), 'value' => 0],
                                    ])
                                    ->data('active') ,

                    ])
                    ->ajax([
                        "url" => route('admin.categories.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("products_count")
                ->title(__('Products'))
                ->data("products_count_formated")
                ->addClass("right")
                ->searchable(false)
                ->orderable(false)
                ->footer(__("Products")) ,

            Column::make('parent_name')
                ->title(__("Parent"))
                ->data('parent_name')
                ->searchable(false)
                ->orderable(false)
                ->footer(__("Parent")),

            Column::make('children',__("Children"))
               // ->title(__("Children"))
                ->data('children_formated')
                ->searchable(false)
                ->orderable(false)
                ->footer(__("Children"))

            ,
            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()->user();
        $buttons = [];

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

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

    }
}
