<?php

namespace Modules\Role\Controllers;

use App\Controllers\BaseController;
use Modules\Role\Models\RoleModel;
use App\Libraries\Rolepermission;
use Modules\Role\Models\MenuModel;
use Modules\Role\Models\PermissionModel;
use Modules\Company\Models\CompanyModel;


class Role extends BaseController
{
    protected $Viewpath;
    protected $roleModel;
    protected $menuModel;
    protected $db;
    protected $permissionModel;
    protected $companyModel;

    public function __construct()
    {

        $this->Viewpath = "Modules\Role\Views";
        $this->roleModel = new RoleModel();
        $this->menuModel = new MenuModel();
        $this->permissionModel = new PermissionModel();
        $this->companyModel = new CompanyModel();
        $this->db = \Config\Database::connect();
    }

    public function new()
    {
        $company_id = 0;
        if(!in_array(session()->get('role_id'),[1,2])){
            $company_id = session()->get('company_id') ?? 0;
        }
        
        $data['module'] =    lang("Localize.role");
        $data['title']  =    lang("Localize.add_role");

        $data['pageheading'] = lang("Localize.add_role");

        $data['company_id'] = 0;
        $data['companies'] = $this->companyModel->findAll();

        $data['logged_company_id'] = $company_id;
        $data['logged_role'] = session()->get('role_id');

        echo view($this->Viewpath . '\role/new', $data);
    }

    public function validateCompanyId($companyId, string $roleTypeField)
    {
        $roleType = $this->request->getPost($roleTypeField);

        if ($roleType === 'custom' && empty($companyId)) {
            return false; // Validation fails
        }

        return true; // Validation passes
    }

    public function create()
    {
        // Determine if we're updating or creating
        $isUpdating = isset($id);
        
        $role_type  = $this->request->getVar('role_type');
        $company_id = $this->request->getVar('company_id');
        $name       = $this->request->getVar('name');

        // Build validation rules dynamically
        $validationRules = [
            'role_type' => [
                'rules' => 'required|in_list[custome,global]', // Adjust the allowed values as per your use case
                'errors' => [
                    'required' => 'The Role Type is required.',
                    'in_list' => 'Invalid Role Type selected.',
                ],
            ],
            'name' => [
                'rules' => 'required',
                'errors' => [
                    'required' => 'The Name is required.'
                ],
            ]
        ];

        $role_type = $this->request->getVar('role_type');
        
        if($role_type == "custome"){
            
            $validationRules['company_id'] = [
                'rules' => 'required',
                'errors' => [
                    'validateCompanyId' => 'The Company field is required when Role Type is custome.',
                ],
            ];
        }

        if (!$this->validate($validationRules)) {
            return redirect()->back()->withInput()->with('fail', $this->validation->listErrors());
        }
        
        $builder = $this->roleModel->builder();
        $builder->where('name', $name);
    
        if ($role_type === 'custome') {
            $builder->where('company_id', $company_id);
        } else {
            $builder->where('role_type', 'global');
        }
    
        if ($builder->get()->getRow()) {
            return redirect()->back()
                ->withInput()
                ->with('fail', $role_type === 'custome'
                    ? 'The Name already exists in this company.'
                    : 'The Name must be unique.');
        }
        
        $data = array(
            "name" => $this->request->getVar('name'),
            "role_type" => $this->request->getVar('role_type'),
            "company_id" => $this->request->getVar('company_id'),
            "status" => $this->request->getVar('status'),
        );

        $userRole =  $this->roleModel->insert($data);
        $matchArray = [1, 2, 3, 4];

        $insertArray = array(
            "create" => 1,
            "read" => 1,
            "edit" => 1,
            "delete" => 1,
        );

        $userId = $this->session->get('user_id');
        //_________________________//
        //    1 = create
        //    2 = read
        //    3 = edit
        //    4 = delete
        //_________________________//
        $valueArray = array();

        $menuTitle = $this->menuModel->findAll();
        foreach ($menuTitle as $key => $menuvalue) {

            $permissionvalue = $this->request->getVar($menuvalue->menu_title);

            if (!empty($permissionvalue)) {

                $result = array_diff($matchArray, $permissionvalue);

                if (!empty($result)) {

                    foreach ($result as $resultvalue) {

                        if ($resultvalue == 1) {
                            $insertArray['create'] = 0;
                        }
                        if ($resultvalue == 2) {
                            $insertArray['read'] = 0;
                        }
                        if ($resultvalue == 3) {
                            $insertArray['edit'] = 0;
                        }
                        if ($resultvalue == 4) {
                            $insertArray['delete'] = 0;
                        }
                    }
                } else {

                    $insertArray = array(
                        "create" => 1,
                        "read" => 1,
                        "edit" => 1,
                        "delete" => 1,
                    );
                }
            } else {
                $insertArray = array(
                    "create" => 0,
                    "read" => 0,
                    "edit" => 0,
                    "delete" => 0,
                );
            }

            $insertArray['role_id'] = $userRole;
            $insertArray['user_id'] = $userId;
            $insertArray['menu_id'] = $menuvalue->id;
            $insertArray['menu_title'] = $menuvalue->menu_title;

            $valueArray[$key] = $insertArray;

            $insertArray = array();

            $insertArray = array(
                "create" => 1,
                "read" => 1,
                "edit" => 1,
                "delete" => 1,
            );
        }

        $checkData =  $this->permissionModel->where('role_id', $userRole)->findAll();
        if (!empty($checkData)) {
            foreach ($checkData as $key => $delvalue) {
                $this->permissionModel->delete($delvalue->id, true);
            }
        }
        $this->permissionModel->insertBatch($valueArray);

        return redirect()->route('index-role')->with("success", "Data Save");
    }

    public function create_old()
    {
        $data = array(
            "name" => $this->request->getVar('name'),
            "status" => $this->request->getVar('status'),
        );

        if ($this->validation->run($data, 'role')) {
            $userRole =  $this->roleModel->insert($data);
            $matchArray = [1, 2, 3, 4];

            $insertArray = array(
                "create" => 1,
                "read" => 1,
                "edit" => 1,
                "delete" => 1,
            );

            $userId = $this->session->get('user_id');
            //_________________________//
            //    1 = create
            //    2 = read
            //    3 = edit
            //    4 = delete
            //_________________________//
            $valueArray = array();

            $valueArray = array();

            $menuTitle = $this->menuModel->findAll();
            foreach ($menuTitle as $key => $menuvalue) {

                $permissionvalue = $this->request->getVar($menuvalue->menu_title);

                if (!empty($permissionvalue)) {

                    $result = array_diff($matchArray, $permissionvalue);

                    if (!empty($result)) {

                        foreach ($result as $resultvalue) {

                            if ($resultvalue == 1) {
                                $insertArray['create'] = 0;
                            }
                            if ($resultvalue == 2) {
                                $insertArray['read'] = 0;
                            }
                            if ($resultvalue == 3) {
                                $insertArray['edit'] = 0;
                            }
                            if ($resultvalue == 4) {
                                $insertArray['delete'] = 0;
                            }
                        }
                    } else {

                        $insertArray = array(
                            "create" => 1,
                            "read" => 1,
                            "edit" => 1,
                            "delete" => 1,
                        );
                    }
                } else {
                    $insertArray = array(
                        "create" => 0,
                        "read" => 0,
                        "edit" => 0,
                        "delete" => 0,
                    );
                }

                $insertArray['role_id'] = $userRole;
                $insertArray['user_id'] = $userId;
                $insertArray['menu_id'] = $menuvalue->id;
                $insertArray['menu_title'] = $menuvalue->menu_title;

                $valueArray[$key] = $insertArray;

                $insertArray = array();

                $insertArray = array(
                    "create" => 1,
                    "read" => 1,
                    "edit" => 1,
                    "delete" => 1,
                );
            }

            $checkData =  $this->permissionModel->where('role_id', $userRole)->findAll();
            if (!empty($checkData)) {
                foreach ($checkData as $key => $delvalue) {
                    $this->permissionModel->delete($delvalue->id, true);
                }
            }
            $this->permissionModel->insertBatch($valueArray);

            return redirect()->route('index-role')->with("success", "Data Save");
        }
        
        return redirect()->back()->with('fail', $this->validation->listErrors());
    }

    public function index()
    {
        //$data['role'] = $this->roleModel->findAll();
        
        $company_id = 0;
        if(!in_array(session()->get('role_id'),[1,2])){
            $company_id = session()->get('company_id') ?? 0;
        }

        $this->roleModel
        ->select('roles.*, companies.name AS company_name')
        ->join('companies', 'companies.id = roles.company_id', 'left');
        if($company_id){
            $this->roleModel->where('company_id', $company_id);
        }
        

        $data['role'] = $this->roleModel->findAll();

        $data['module'] =    lang("Localize.role");
        $data['title']  =    lang("Localize.role_list");
        $data['pageheading'] = lang("Localize.role_list");

        $rolepermissionLibrary = new Rolepermission();
        $add_data = "add_role";
        $list_data = "role_list";

        

        $data['logged_company_id'] = $company_id;
        $data['logged_role'] = session()->get('role_id');

        $data['add_data'] = $rolepermissionLibrary->create($add_data);
        $data['edit_data'] = $rolepermissionLibrary->edit($list_data);
        $data['delete_data'] = $rolepermissionLibrary->delete($list_data);
        echo view($this->Viewpath . '\role/index', $data);
    }


    public function edit($id)
    {
        $company_id = 0;
        if(session()->get('role_id') == "7"){
            $company_id = session()->get('company_id') ?? 0;
        }
        $data['role'] = $this->roleModel->find($id);

        $data['module'] =    lang("Localize.role");
        $data['title']  =    lang("Localize.role_list");

        $data['company_id'] = 0;
        if(!empty($data['role'])){
            if($data['role']->company_id){
                $data['company_id'] = $data['role']->company_id;
            }
        }
        $data['companies'] = $this->companyModel->findAll();

        $data['logged_company_id'] = $company_id;
        $data['logged_role'] = session()->get('role_id');

        $heading = lang("Localize.edit") . ' ' . lang("Localize.role");
        $data['pageheading'] = $heading;

        echo view($this->Viewpath . '\role\edit', $data);
    }

    public function update($id)
    {
        // Determine if we're updating or creating
        $isUpdating = isset($id);

        // Build validation rules dynamically
        $validationRules = [
            'role_type' => [
                'rules' => 'required|in_list[custome,global]', // Adjust the allowed values as per your use case
                'errors' => [
                    'required' => 'The Role Type is required.',
                    'in_list' => 'Invalid Role Type selected.',
                ],
            ],
            'name' => [
                'rules' => 'required',
                'errors' => [
                    'required' => 'The Name is required.'
                ],
            ]
        ];

        $role_type = $this->request->getVar('role_type');
        $company_id = $this->request->getVar('company_id');
        $name       = $this->request->getVar('name');
        
        
        if($role_type == "custome"){
            
            $validationRules['company_id'] = [
                'rules' => 'required',
                'errors' => [
                    'validateCompanyId' => 'The Company field is required when Role Type is custome.',
                ],
            ];
        }

        if (!$this->validate($validationRules)) {
            return redirect()->back()->withInput()->with('fail', $this->validation->listErrors());
        }
        
        $builder = $this->roleModel->builder();
        $builder->where('name', $name);
        $builder->where('id !=', $id);
    
        if ($role_type === 'custome') {
            $builder->where('company_id', $company_id);
        } else {
            $builder->where('role_type', 'global');
        }
    
        if ($builder->get()->getRow()) {
            return redirect()->back()
                ->withInput()
                ->with('fail', $role_type === 'custome'
                    ? 'The Name already exists in this company.'
                    : 'The Name must be unique.');
        }
        
        $data = array(
            "id" => $id,
            "name" => $this->request->getVar('name'),
            "role_type" => $this->request->getVar('role_type'),
            "company_id" => $this->request->getVar('company_id'),
            "status" => $this->request->getVar('status'),
        );
        $this->roleModel->save($data);
        return redirect()->route('index-role')->with("success", "Data Update");
    }

    public function update_old($id)
    {
        $data = array(
            "id" => $id,
            "name" => $this->request->getVar('name'),
            "status" => $this->request->getVar('status'),
        );

        if ($this->validation->run($data, 'role')) {
            $this->roleModel->save($data);
            return redirect()->route('index-role')->with("success", "Data Update");
        }

        return redirect()->back()->with('fail', $this->validation->listErrors());
    }

    public function delete($id)
    {
        $this->roleModel->delete($id);
        return redirect()->route('index-role')->with("fail", "Data Deleted");
    }
}
