<?php

namespace Modules\Cancellation\Controllers;

use App\Controllers\BaseController;
use Modules\Company\Models\CompanyModel;
use Modules\User\Models\UserModel;
use Modules\User\Models\UserDetailModel;
use Modules\Role\Models\RoleModel;
use Modules\Trip\Models\TripModel;
use Modules\Location\Models\LocationModel;
use App\Libraries\Rolepermission;
use Modules\Cancellation\Models\CancellationModel;

class Cancellation extends BaseController
{
    protected $Viewpath;
    protected $db;
    protected $userModel;
    protected $userDetailModel;
    protected $companyModel;
    protected $roleModel;
    protected $locationModel;
    protected $tripModel;
    protected $cancellationModel;


    public function __construct()
    {
        $this->Viewpath = "Modules\Cancellation\Views";
        $this->companyModel = new CompanyModel();
        $this->userModel = new UserModel();
        $this->userDetailModel = new UserDetailModel();
        $this->roleModel = new RoleModel();
        $this->tripModel = new TripModel();
        $this->locationModel = new LocationModel();
        $this->db = \Config\Database::connect();
        $this->cancellationModel = new CancellationModel();
    }

    public function index(bool $showTrashOnly = false)
    {
        // build layout data
        $data['pageheading'] = lang("Localize.cancellation_policy_list");
        $data['module'] = lang("Localize.cancellation_policy");
        $data['title']  = lang("Localize.cancellation_policy_list");

        // build perission dat
        $rolepermissionLibrary = new Rolepermission();
        $data['add_cancellation'] = $rolepermissionLibrary->create("add_cancellation");
        $data['edit_cancellation'] = $rolepermissionLibrary->edit("add_cancellation");
        $data['delete_cancellation'] = $rolepermissionLibrary->delete("delete_cancellation");

        // $data['companydetail'] = $this->companyModel->findAll();

        $data['cancellationlist'] = $this->cancellationModel->select('cancellation_policies.*, companies.name AS company_name, users.login_email, users.login_mobile')
            ->join('users', 'users.id = cancellation_policies.user_id')
            ->join('companies', 'companies.id = cancellation_policies.company_id')
            ->GroupBy('cancellation_policies.company_id')
            ->findAll();

        $userRole = $this->session->get('role_id');
        $data['validation'] = $this->validator;
        $data['role_id'] = $userRole;

        return view($this->Viewpath . '\cancellation\index', $data);

    }

    public function new()
    {
        // build layout data
        $data['pageheading'] = lang("Localize.add_cancellation_policy");
        $data['module'] = lang("Localize.cancellation_policy");
        $data['title']  = lang("Localize.add_cancellation_policy");
        $data['companies'] = $this->companyModel->findAll();
        return view($this->Viewpath . '\cancellation\new', $data);
    }

    /* public function create()
    {
        
        // dd($this->request->getVar());
        // build agent login credintial
        $company_id = $this->request->getVar('company_id');
        $hours = $this->request->getVar('hours');
        $charges = $this->request->getVar('charges');
        $userId = $this->session->get('user_id');
        
        
        $model = new CancellationModel();
        

        $existData = $this->cancellationModel->select('cancellation_policies.*')
            ->where('company_id', $company_id)
            ->find();
        if(!$existData){

            $cancellationData = array(
                "company_id"            => $company_id,
                "user_id"               => $userId,
                "hours"                 => $hours,
                "charges"               => $charges,
            );

            if (!$validation->setRules(config('Validation')->cancellation)->run($data)) {
                // Validation failed, return to the form with errors
                return view('your_view', ['validation' => $validation]);
            }
    
            if ($this->validation->run($cancellationData, 'cancellation')) {
                
                $this->db->transStart();
                
                $CanId = $this->cancellationModel->insert($cancellationData);
                
                $this->db->transComplete();
    
                return redirect()->route('index-cancellation')->with("success", "Data Save");
            } else {
                return redirect()->back()->withInput()->with('fail', $this->validation->listErrors());
            }

        } else {
            return redirect()->back()->withInput()->with('fail', 'A cancellation policy for this company has already been added.');
        }
        
    } */


    public function create()
    {
        // Get form data
        $company_id = $this->request->getVar('company_id');
        $hours = $this->request->getVar('hours');
        $charges = $this->request->getVar('charges');
        $userId = $this->session->get('user_id');
        
        // Prepare the model
        $model = new CancellationModel();
        
        // Custom validation
        $validation = \Config\Services::validation();
        
        // Check if data already exists for the company
        $existData = $model->where('company_id', $company_id)->findAll();
        if ($existData) {
            return redirect()->back()->withInput()->with('fail', 'A cancellation policy for this company has already been added.');
        }

        if (!is_array($hours) || !is_array($charges)) {
            return redirect()->back()->withInput()->with('fail', 'Hours and charges must be arrays.');
        }

        // Validate the hours and charges arrays
        if (count($hours) !== count($charges)) {
            return redirect()->back()->withInput()->with('fail', 'The number of hours and charges should be the same.');
        }

        if ($hours[0]  == null || $charges[0] == null) {
            return redirect()->back()->withInput()->with('fail', 'Please add atleast 1 policy.');
        }
        
        // Validation rules for each item in the arrays
        $validationRules = [
            'company_id' => 'required',
        ];
        
        // Validation logic for dynamic fields
        $isValid = true;
        $dynamicValidationRules = [];
        $dynamicValidationMessages = [];


        foreach ($hours as $index => $hour) {
            
            $charge = $charges[$index];
            if($hour != "" && $charge != ""){
                // Validate hours (must be integer)
                if (!is_numeric($hour) || (int)$hour != $hour) {
                    $isValid = false;
                    $dynamicValidationMessages["hours[{$index}]"] = 'Each hour value must be an integer.';
                }
            
                // Validate charges (must be between 0 and 100)
                
                if (!is_numeric($charge) || $charge < 0 || $charge > 100) {
                    $isValid = false;
                    $dynamicValidationMessages["charges[{$index}]"] = 'Each charge must be a percentage (0-100).';
                }

                // Check if hours are unique for the company
                $existingHour = $model->where('company_id', $company_id)->where('hours', $hour)->first();
                if ($existingHour) {
                    $isValid = false;
                    $dynamicValidationMessages["hours[{$index}]"] = "Hour value {$hour} already exists for this company.";
                }
            }
        }

        // Apply dynamic validation rules
        $validation->setRules($validationRules);
        if (!$isValid) {
            $errorMessages = implode('<br>', $dynamicValidationMessages);
            return redirect()->back()->withInput()->with('fail', $errorMessages);
        }

        // If everything is valid, proceed with inserting the data
        $cancellationData = [];
        foreach ($hours as $index => $hour) {
            if($hour != "" ||  $charges[$index] != ""){
                $cancellationData[] = [
                    "company_id" => $company_id,
                    "user_id" => $userId,
                    "hours" => $hour,
                    "charges" => $charges[$index],
                ];
            }

        }

        // Start a database transaction to insert all records
        $this->db->transStart();

        // Insert the data
        foreach ($cancellationData as $data) {
            $model->insert($data);
        }

        $this->db->transComplete();

        // Check transaction status and redirect accordingly
        if ($this->db->transStatus() === false) {
            return redirect()->back()->with('fail', 'Something went wrong while saving the data.');
        } else {
            return redirect()->route('index-cancellation')->with('success', 'Data saved successfully.');
        }
    }

    public function edit($company_id)
    {
        // build layout data
        $data['module'] = lang("Localize.cancellation_policy");
        $data['title']  = lang("Localize.cancellation_policy_list");
        $data['pageheading'] = lang("Localize.cancellation_policy") . ' ' . lang("Localize.edit");
        
        
        $data['cancellationlist'] = $this->cancellationModel->where('company_id', $company_id)->findAll();
        $data['list_available'] = 0;
        if(!empty($data['cancellationlist'])){
            $data['list_available'] = 1;
        }
        $data['company_id'] = $company_id;
        $data['logged_user_id'] = $this->session->get('user_id');

        $data['companies'] = $this->companyModel->findAll();
        $userRole = $this->session->get('role_id');
        $data['role_id'] = $userRole;

        return view($this->Viewpath . '/cancellation/edit', $data);
    }

    public function update($userId, $company_id)
    {
        $userRole = $this->session->get('role_id');
        $hours = $this->request->getVar('hours');
        $charges = $this->request->getVar('charges');
        $userId = $this->session->get('user_id');
        
        // Prepare the model
        $model = new CancellationModel();
        
        // Custom validation
        $validation = \Config\Services::validation();
        
        if (!is_array($hours) || !is_array($charges)) {
            return redirect()->back()->withInput()->with('fail', 'Hours and charges must be arrays.');
        }

        // Validate the hours and charges arrays
        if (count($hours) !== count($charges)) {
            return redirect()->back()->withInput()->with('fail', 'The number of hours and charges should be the same.');
        }

        if ($hours[0]  == null || $charges[0] == null) {
            return redirect()->back()->withInput()->with('fail', 'Please add atleast 1 policy.');
        }
        
        // Validation rules for each item in the arrays
        $validationRules = [
            'user_id' => 'required',
        ];
        
        // Validation logic for dynamic fields
        $isValid = true;
        $dynamicValidationRules = [];
        $dynamicValidationMessages = [];

        foreach ($hours as $index => $hour) {
            
            $charge = $charges[$index];
            if($hour != "" && $charge != ""){
                // Validate hours (must be integer)
                if (!is_numeric($hour) || (int)$hour != $hour) {
                    $isValid = false;
                    $dynamicValidationMessages["hours[{$index}]"] = 'Each hour value must be an integer.';
                }
            
                // Validate charges (must be between 0 and 100)
                
                if (!is_numeric($charge) || $charge < 0 || $charge > 100) {
                    $isValid = false;
                    $dynamicValidationMessages["charges[{$index}]"] = 'Each charge must be a percentage (0-100).';
                }

                // Check if hours are unique for the company
                /* $existingHour = $model->where('company_id', $company_id)->where('hours', $hour)->first();
                if ($existingHour) {
                    $isValid = false;
                    $dynamicValidationMessages["hours[{$index}]"] = "Hour value {$hour} already exists for this company.";
                } */
            }
        }

        // Apply dynamic validation rules
        $validation->setRules($validationRules);
        if (!$isValid) {
            $errorMessages = implode('<br>', $dynamicValidationMessages);
            return redirect()->back()->withInput()->with('fail', $errorMessages);
        }

        $db = \Config\Database::connect();

        // Delete from the table with a where condition
        $deletebuilder = $db->table('cancellation_policies');
        $deletebuilder->where('company_id', $company_id);
        $deletebuilder->delete();

        // If everything is valid, proceed with inserting the data
        $cancellationData = [];
        foreach ($hours as $index => $hour) {
            if($hour != "" ||  $charges[$index] != ""){
                $cancellationData[] = [
                    "company_id" => $company_id,
                    "user_id" => $userId,
                    "hours" => $hour,
                    "charges" => $charges[$index],
                ];
            }

        }

        // Start a database transaction to insert all records
        $this->db->transStart();

        // Insert the data
        foreach ($cancellationData as $data) {
            $model->insert($data);
        }

        $this->db->transComplete();

        // Check transaction status and redirect accordingly
        if ($this->db->transStatus() === false) {
            return redirect()->back()->with('fail', 'Something went wrong while saving the data.');
        } else {
            return redirect()->route('index-cancellation')->with('success', 'Data saved successfully.');
        }
        
    }

    public function edit_company_cancellation($company_id)
    {
        // build layout data
        $data['module'] = lang("Localize.update_cancellation_policy");
        $data['title']  = lang("Localize.update_cancellation_policy");
        $data['pageheading'] = lang("Localize.update_cancellation_policy");
        
        $data['cancellationlist'] = $this->cancellationModel->where('company_id', $company_id)->findAll();

        $data['list_available'] = 0;
        if(!empty($data['cancellationlist'])){
            $data['list_available'] = 1;
        }

        $userRole = $this->session->get('role_id');

        $data['logged_user_id'] = $this->session->get('user_id');
        $data['logged_company_id'] = $this->session->get('company_id');
        $data['role_id'] = $userRole;

        return view($this->Viewpath . '/cancellation/edit_company_cancellation', $data);
    }

    public function update_company_cancellation($user_id, $company_id)
    {
        $userRole = $this->session->get('role_id');
        $userId = $this->session->get('user_id');

        $hours = $this->request->getVar('hours');
        $charges = $this->request->getVar('charges');
        
        // Prepare the model
        $model = new CancellationModel();
        
        // Custom validation
        $validation = \Config\Services::validation();
        
        if (!is_array($hours) || !is_array($charges)) {
            return redirect()->back()->withInput()->with('fail', 'Hours and charges must be arrays.');
        }

        // Validate the hours and charges arrays
        if (count($hours) !== count($charges)) {
            return redirect()->back()->withInput()->with('fail', 'The number of hours and charges should be the same.');
        }

        if ($hours[0]  == null || $charges[0] == null) {
            return redirect()->back()->withInput()->with('fail', 'Please add atleast 1 policy.');
        }
        
        // Validation rules for each item in the arrays
        $validationRules = [
            'user_id' => 'required',
        ];
        
        // Validation logic for dynamic fields
        $isValid = true;
        $dynamicValidationRules = [];
        $dynamicValidationMessages = [];

        foreach ($hours as $index => $hour) {
            
            $charge = $charges[$index];
            if($hour != "" && $charge != ""){
                // Validate hours (must be integer)
                if (!is_numeric($hour) || (int)$hour != $hour) {
                    $isValid = false;
                    $dynamicValidationMessages["hours[{$index}]"] = 'Each hour value must be an integer.';
                }
            
                // Validate charges (must be between 0 and 100)
                
                if (!is_numeric($charge) || $charge < 0 || $charge > 100) {
                    $isValid = false;
                    $dynamicValidationMessages["charges[{$index}]"] = 'Each charge must be a percentage (0-100).';
                }
            }
        }

        /* foreach ($hours as $index => $hour) {
            
            $charge = $charges[$index];
            // Check if hours are unique for the company
            $existingHour = $model->where('company_id', $company_id)->where('hours', $hour)->first();
            if ($existingHour) {
                $isValid = false;
                $dynamicValidationMessages["hours[{$index}]"] = "Hour value {$hour} already exists for this company.";
            }
        } */

        // Apply dynamic validation rules
        $validation->setRules($validationRules);
        if (!$isValid) {
            $errorMessages = implode('<br>', $dynamicValidationMessages);
            return redirect()->back()->withInput()->with('fail', $errorMessages);
        }

        $db = \Config\Database::connect();

        // Delete from the table with a where condition
        $deletebuilder = $db->table('cancellation_policies');
        $deletebuilder->where('company_id', $company_id);
        $deletebuilder->delete();

        // If everything is valid, proceed with inserting the data
        $cancellationData = [];
        foreach ($hours as $index => $hour) {
            if($hour != "" ||  $charges[$index] != ""){
                $cancellationData[] = [
                    "company_id" => $company_id,
                    "user_id" => $userId,
                    "hours" => $hour,
                    "charges" => $charges[$index],
                ];
            }

        }

        // Start a database transaction to insert all records
        $this->db->transStart();

        // Insert the data
        foreach ($cancellationData as $data) {
            $model->insert($data);
        }

        $this->db->transComplete();

        // Check transaction status and redirect accordingly
        if ($this->db->transStatus() === false) {
            return redirect()->back()->with('fail', 'Something went wrong while saving the data.');
        } else {
            return redirect()->back()->with('success', 'Data saved successfully.');

        }
    }

    public function clear_company_cancellation($company_id)
    {
        $db = \Config\Database::connect();

        // Delete from the table with a where condition
        $builder = $db->table('cancellation_policies');
        $builder->where('company_id', $company_id);
        $builder->delete();


        return redirect()->back()->with('success', 'Clear all policy.');

    }

    public function delete(int $companyId)
    {
        $companyInfo = $this->companyModel->find($companyId);
        $companyUserId = $companyInfo->user_id;
        $companyId = $companyInfo->id;
        $companyName = $companyInfo->name;
        try {
            $this->db->transStart();
            $this->companyModel->delete($companyId);
            $this->userModel->delete($companyUserId);
            $this->db->transComplete();
        } catch (\Throwable $e) {
            return redirect()->back()->with('fail', $e->getMessage());
        }

        return redirect()->back()->with('fail', "Company: {$companyName} deleted");
    }

    public function restore(int $companyId)
    {
        $companyInfo = $this->companyModel->withDeleted()->find($companyId);
        $companyUserId = $companyInfo->user_id;
        $companyId = $companyInfo->id;
        $companyName = $companyInfo->name;

        try {
            $this->db->transStart();
            $this->companyModel->set('deleted_at', null)->update($$companyId);
            $this->userModel->set('deleted_at', null)->update($companyUserId);
            $this->db->transComplete();
        } catch (\Throwable $e) {
            return redirect()->back()->with('fail', $e->getMessage());
        }

        return redirect()->route('trash-index-company')->with('success', "Company: {$companyName} restored");
    }

    public function status($usercompanyId)
    {
        $userStatus = $this->companyModel->find($usercompanyId);

        if ($userStatus->status == 1) {
            $upData = array(
                "id" => $usercompanyId,
                "status" => 0
            );
            $this->companyModel->save($upData);

            $trips = $this->tripModel->where('company_id', $usercompanyId)->findAll();

            if (!empty($trips)) {
                $this->tripModel->where('company_id', $usercompanyId)
                            ->set(['status' => 0])
                            ->update();
            }


        }
        if ($userStatus->status == 0) {
            $upData = array(
                "id" => $usercompanyId,
                "status" => 1
            );
            $this->companyModel->save($upData);
            
            // $trips = $this->tripModel->where('company_id', $companyId)->findAll();

            // if (!empty($trips)) {
            //     $this->tripModel->where('company_id', $companyId)
            //                 ->set(['status' => 1])
            //                 ->update();
            // }
        }
        return redirect()->route('index-company')->with("success", "Data Update");
    }
}
