<?php

namespace App\DataTables\Users;

use App\Models\SecurityManagement\Role;
use App\Models\UserManagement\Admin;
use App\Models\UserManagement\Customer;
use App\Models\UserManagement\User;
use App\Models\UserManagement\UserType;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Illuminate\Database\Eloquent\Model;
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\Html\Editor\Fields\Options;
use Yajra\DataTables\Services\DataTable;
use function Money\mod;

class UserDataTable extends DataTable{


    protected $userType ;
    public function __construct($userType = UserType::CUSTOMER){
        parent::__construct();

        $this->userType = $userType;
        if (request()->filled("userType")){
            $this->userType = request()->get("userType");
        }
    }


    /**Build DataTable class.
     * @param QueryBuilder $query Results from query() method.
     * @return EloquentDataTable
     */
    public function dataTable(QueryBuilder $query){
        $userType =   $this->userType;
        return (new EloquentDataTable($query))
               // ->addColumn('action', '')
                ->addColumn('actions', function ($row) use ($userType){
                    $permissions = [];
                    $permissions['edit'] = ($userType == UserType::CUSTOMER) ? "customer-update" : "user-update";
                    $permissions['remove'] = ($userType == UserType::CUSTOMER) ? "customer-delete" : "user-delete";
                    return view('shared.datatable-column-actions',compact("permissions"));
                })
                ->addColumn('image', function ($row){
                    return view('backend.users.blocs.dt-image',compact("row"));
                })
                ->addColumn('balance_formated', fn ($row) => format_amount($row->balance ?? 0,true))
                ->addColumn('order_count_formated', fn ($row) => format_amount(count($row->orders)))
                ->addColumn('username_fullname', function ($row){
                    return view('backend.users.blocs.dt-fullname-username',compact("row"));
                })
                ->addColumn('email_phone', function ($row){
                    return view('backend.users.blocs.dt-email-phone',compact("row"));
                })
//               ->addColumn('roles_names', function ($row){
//                   $roles = $row->roles->pluck('name')->toArray() ?? [];
//                    return ($roles) ? implode(",",$roles) : "--";
//                })
                ->addColumn('roles_names', function ($row){
                    return view('backend.users.blocs.dt-list-roles',compact("row"));
                })

//                ->editColumn('orders', function ($row){
//                    return format_amount($row->orders,true);
//                })
                ->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 ?? "";
//                })
                ->setRowId('id')
            ;
    }

    /**Get query source of dataTable.
     * @param Customer|Admin $model
     * @return QueryBuilder
     */
    public function query(User $model){

        $model = $this->userType == UserType::CUSTOMER ? Customer::class : Admin::class;

        //dd((new $model)->newQuery()->latest()->get());
        return (new $model)->newQuery()
                  //  ->with(["orders"])
                    //->when(filled($this->userType),fn($query) => $query->where(UserType::FK_ID,(int) $this->userType))
                   ->when(request()->has("search"),function ($query){
                       $search = request()->get("search")['value'];
                        return $query->whereLike(['first_name','last_name',"username","email","phone"],$search);
                    })
                   ->when(($this->userType == UserType::CUSTOMER),fn ($query) => $query->with(['payments']))
                   ->latest() ;
    }


    public function html(){

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


    protected function getFields(){

        $userType = blank($this->userType) ? UserType::CUSTOMER : $this->userType;

        $fields = [
            Fields\Hidden::make(UserType::FK_ID,__("Type"))->default($this->userType),
            Fields\Text::make('first_name',__("First Name"))->data('first_name'),
            Fields\Text::make('last_name',__("Last Name"))->data('last_name'),
            Fields\Text::make('username',__("Username"))->data('username'),
            Fields\Text::make('email',__("Email"))->data('email'),
            Fields\Text::make('phone',__("Phone"))->data('phone'),
            Fields\Radio::make('active',__('Status'))
                        ->options([
                            ['label' => __('Active'), 'value' => 1],
                            ['label' => __('Inactive'), 'value' => 0],
                        ])
                        ->data('active') ,

            Fields\Radio::make('receive_email',__('Receive Email')." ?")
                            ->options(Options::yesNo())
                            ->data('receive_email') ,


        ];

        if ($userType == UserType::ADMIN){
            $roles = Role::where("name","<>",Role::CUSTOMER)->get()->pluck("id","name");
            $fields[] = Fields\Select::make('roles',__('Roles'))
                        ->options($roles)
                        ->multiple(true)
                        ->attr("data-plugin-multiselect","")
                        ->data('roles_ids');


        }
        $fields[] = Fields\Password::make('password',__("New Password"))
                        ->attr("class","text-danger")
                        ->fieldInfo(__("If not set, the password will be the email"))
                        ->data('');

        $fields[] = Fields\Password::make('password_confirmation',__("Confirm Password"))
                            ->attr("class","text-danger")
                            ->data('');

        return $fields;
    }

    protected function getColumns() :array {
        $userType = blank($this->userType) ? UserType::CUSTOMER : $this->userType;


        $columns = [
            Column::computed("")
                ->title("<input type='checkbox' class='dt-checkbox-all' onclick='select_all_td()'/>")
                ->searchable(false)
                ->exportable(false)
                ->printable(false)
                ->className("select-checkbox")
                ->content("")
                ->width(10)
                ->data(""),

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

            Column::make("first_name")
                ->title(__("Name & Username"))
                ->data('username_fullname')
                ->searchable(true)
                ->orderable(true)
                ->footer(__("Name & Username")),

            Column::make(["email",'phone'])
                ->title(__("Email & Phone"))
                ->data('email_phone')
                ->searchable(true)
                ->orderable(true)
                ->footer(__("Email & Phone")),

        ];
        $columns[] =   Column::make('status')
                        ->title(__("Status"))
                        ->data('status_label')
                        ->searchable(false)
                        ->orderable(true)
                        ->footer(__("Status"));

        if ($userType == UserType::ADMIN){
            $columns[] =   Column::make('roles')
                            ->title(__("Roles"))
                            ->data('roles_names')
                            ->searchable(false)
                            ->orderable(true)
                            ->footer(__("Roles"));

        }else{
            $columns[] =   Column::make('balance')
                                ->title(__("Balance"))
                                ->data('balance_formated')
                                ->searchable(false)
                                ->orderable(true)
                                ->footer(__("Balance"));

            $columns[] =   Column::make('order_count')
                                ->title(__("Orders"))
                                ->data('order_count_formated')
                                ->searchable(false)
                                ->orderable(false)
                                ->footer(__("Orders"));
        }

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

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


        return $columns;
    }

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

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

        if ($user->can('customer-delete')  or $user->can('user-delete')){
            $buttons[] =  Button::make('remove')->editor("editor");
        }
        $buttons[] = Button::make('reload');
//        $buttons[] = Button::make('searchPanes');
        $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(){

    }
}
