<?php

namespace App\DataTables\Users;

use App\Models\SecurityManagement\Role;
use App\Models\PaymentManagement\Payment;
use App\Models\PaymentManagement\PaymentMethod;
use App\Models\UserManagement\Admin;
use App\Models\UserManagement\Customer;
use App\Models\UserManagement\User;
use App\Models\UserManagement\UserType;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Validation\Rule;
use Yajra\DataTables\DataTablesEditor;

class UserDataTableEditor extends DataTablesEditor{
    protected $model = Admin::class;

    private $type = "ADMIN";

    public function __construct() {
        $data = Arr::first(request()->all()['data']);
        $this->type = $data[UserType::FK_ID];
        $this->model = ($this->type == UserType::CUSTOMER) ? Customer::class : Admin::class;
    }

    /**Get create action validation rules.
     * @return array
     */
    public function createRules(){
        $data = Arr::first(request()->all()['data']);
        $type = $this->type;
        $users_table = $this->resolveModel()->getTable();
        $roles_table = (new Role)->getTable();


        $provided_by_create_order_page = $data['provided_by_create_order_page'] ?? false;

        $rules =  [
            'first_name' => ['required', "min:2",'max:255'],
            'last_name' => ['nullable', 'max:255'],

            UserType::FK_ID => ['required',Rule::in(UserType::all()->pluck("id")->toArray())],

            'username' => [ 'required', 'min:4','max:10',
                Rule::unique($users_table,"username")
            ],

            'email' => [ 'required', 'email', 'max:255',
                Rule::unique($users_table,"email")
            ],

            'phone' => ['nullable', 'string', 'max:255',
                Rule::unique($users_table,"phone")
            ],

            'password' => ['required', 'min:6', 'confirmed'],
            'active' => ['required'],
            'receive_email' => ['required'],
            // 'user_image' => ['mimes:jpg,jpeg,png,gif', 'max:20000'],
        ];


        if (filled($data['password'])){
            $rules['password_confirmation']  = ['required','string', 'min:6'];
        }

        if ($type == UserType::CUSTOMER){
           $rules['password'][] = "nullable";
        }else{
            $rules['roles'] = ['required','array','min:1'];
           // $rules['roles.*'] = ['required',"int","exists:$roles_table,id,guard_name,web,deleted_at,NULL"];
        }


        if ($provided_by_create_order_page){
            unset($rules['password']['required'],$rules['active']['required']);
            unset($rules['phone']['required'],$rules['username']['required']);
            unset($rules['receive_email']['required'],$rules['email']['required']);
        }
        return $rules;
    }

    /**Get edit action validation rules.
     * @param Model $model
     * @return array
     */
    public function editRules(Model $model){
        $users_table = $this->resolveModel()->getTable();

        $data =  Arr::first(request()->all()['data']);
        $roles_table = (new Role)->getTable();
        $type = $this->type;

        $rules =  [
            UserType::FK_ID => ['required',Rule::in(UserType::all()->pluck("id")->toArray())],
            'first_name' =>   ['required', 'max:255'],

            'last_name' =>    ['nullable', 'max:255'],

            'username' => [
                'required', 'min:4','max:10',
                Rule::unique($users_table,"username")
                    ->ignore($model->getKey())
            ],

            'email' => [
                'required', 'email', 'max:255',
                Rule::unique($users_table,"email")
                    ->ignore($model->getKey())

            ],

            'phone' => [
                'nullable', 'string', 'max:255',
                Rule::unique($users_table,"phone")
                    ->ignore($model->getKey())

            ],

            'active' => ['nullable'],
            'receive_email' => ['nullable'],
        ];

        if (!blank($data['password'])){
            $rules['password_confirmation']  = ['required','string', 'min:6'];
        }

        if ($type == UserType::CUSTOMER){
            $rules['password'][] = "nullable";
        }else{
            $rules['roles'] = ['required','array','min:1'];
           // $rules['roles.*'] = ['required',"int","exists:$roles_table,id,guard_name,web,deleted_at,NULL"];
        }

        return $rules;
    }

    /**
     * Get remove action validation rules.
     *
     * @param Model $model
     * @return array
     */
    public function removeRules(Model $model){
       // $role_table_name = $this->resolveModel()->getTable();
        return [
//            "ids" => ['required',"array","min:1"],
//            "ids.*" => ['required',"int","exists:$role_table_name,id,deleted_at,NULL"],
        ];
    }

    public function attributes(){
        return [
            "first_name" => __("First Name"),
            "last_name" => __("Last Name"),
        ];
    }


    public function created(User $user, $data){

        if (isset($data['roles'])){
            $user->assignRole($data['roles']);
        }
        return $user;
    }

    public function updated(User $user, $data){

        if (!$user->isCustomer()){
            $roles = $data['roles'] ?? [];
           // $user->assignRole($roles);
            $user->roles()->sync($roles);
        }

        return $user;
    }

    public function updating(User $user, $data){
        $password = $data['password'] ?? "";
        if (!empty($password)){
            $data["password"] = bcrypt($password);
        }else{
            unset($data['password']);
        }
        return $data;
    }

    public function creating(User $user, $data){
        $password = $data['password'] ?? "";
        if (!empty($password)){
            $data["password"] = bcrypt($password);
        }

        return $data;
    }


}
