<?php

namespace Modules\Term\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\Term\Models\TermModel;

class Term extends BaseController
{
    protected $Viewpath;
    protected $db;
    protected $userModel;
    protected $userDetailModel;
    protected $companyModel;
    protected $roleModel;
    protected $locationModel;
    protected $tripModel;
    protected $termModel;


    public function __construct()
    {
        $this->Viewpath = "Modules\Term\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->termModel = new TermModel();
    }

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

        // build perission dat
        $rolepermissionLibrary = new Rolepermission();
        $data['add_term'] = $rolepermissionLibrary->create("add_terms");
        $data['edit_term'] = $rolepermissionLibrary->edit("add_terms");
        $data['delete_term'] = $rolepermissionLibrary->delete("add_terms");

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

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

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

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

    }

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

    public function create()
    {
        // Get form data
        $company_id = $this->request->getVar('company_id');
        $title = $this->request->getVar('title');
        $sub_title = $this->request->getVar('sub_title');
        $description = $this->request->getVar('description');
        $userId = $this->session->get('user_id');
        // Prepare the model
        $model = new TermModel();
        
        // 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 Terms & Conditions for this company has already been added.');
        }
        
        // Validation rules for each item in the arrays
        $validationRules = [
            'company_id' => 'required',
        ];

        $termData = [ 
            "company_id"    => $company_id,
            "user_id"       => $userId,
            "title"         => $title,
            "sub_title"     => $sub_title,
            "description"   => $description
        ];

        $this->db->transStart();
        
        $model->insert($termData);
        $lastInsertId = $this->db->insertID();
        $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-company-term')->with('success', 'Data saved successfully.');
        }
    }

    public function edit($company_id)
    {
        // build layout data
        $data['module'] = lang("Localize.terms_conditions");
        $data['title']  = lang("Localize.terms_conditions_list");
        $data['pageheading'] = lang("Localize.terms_conditions") . ' ' . lang("Localize.edit");
        
        
        $data['termlist'] = $this->termModel->where('company_id', $company_id)->findAll();
        $data['list_available'] = 0;
        if(!empty($data['termlist'])){
            $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 . '/term/edit', $data);
    }

    public function edit_company_term($company_id)
    {
        // build layout data
        $data['module'] = lang("Localize.terms_conditions");
        $data['title']  = lang("Localize.terms_conditions_list");
        $data['pageheading'] = lang("Localize.terms_conditions") . ' ' . lang("Localize.edit");
        
        
        $data['termlist'] = $this->termModel->where('company_id', $company_id)->findAll();
        $data['list_available'] = 0;
        if(!empty($data['termlist'])){
            $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 . '/term/edit', $data);
    }

    public function update($userId, $company_id)
    {
        $userRole = $this->session->get('role_id');
        $title = $this->request->getVar('title');
        $sub_title = $this->request->getVar('sub_title');
        $description = $this->request->getVar('description');
        $userId = $this->session->get('user_id');
        
        // Prepare the model
        $model = new TermModel();
        
        // Custom validation
        $validation = \Config\Services::validation();

        $termData = [ 
            "company_id"    => $company_id,
            "user_id"       => $userId,
            "title"         => $title,
            "sub_title"     => $sub_title,
            "description"   => $description
        ];
        
        
        $db = \Config\Database::connect();
        $deletebuilder = $db->table('company_terms');
        $deletebuilder->where('company_id', $company_id);
        $deletebuilder->delete();
        // Start a database transaction to insert all records
        $this->db->transStart();
        $model->insert($termData);

        $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 {
            if($userRole == 1){
                return redirect()->route('index-company-term')->with('success', 'Data saved successfully.');    
            }else{
                return redirect()->route('admin-home')->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 status($usercompanyId)
    {
        $userStatus = $this->termModel->find($usercompanyId);

        if ($userStatus->status == 1) {
            $upData = array(
                "id" => $usercompanyId,
                "status" => 0
            );
            $this->termModel->save($upData);
        }
        if ($userStatus->status == 0) {
            $upData = array(
                "id" => $usercompanyId,
                "status" => 1
            );
            $this->termModel->save($upData);
        }
        return redirect()->route('index-company-term')->with("success", "Data Update");
    }
}
