<?php
error_reporting(1); // Suppress all errors
ini_set('display_errors', 1); // Do not display errors

defined('BASEPATH') or exit('No direct script access allowed');
require(APPPATH . '/libraries/REST_Controller.php');

use Restserver\Libraries\REST_Controller;

class UserController extends REST_Controller
{

    /**
     * __construct function.
     * 
     * @access public
     * @return void
     */

    public function __construct()
    {
        parent::__construct();
        $this->load->library('Authorization_Token');
        $this->load->library('form_validation');
        $this->load->library('encryption');
        $this->load->helper('encryption_helper'); //For MasterEncrypt,Master Decrypt (transport enc func) 
        $this->load->model('restAppApi/UserModel');
        $this->load->database();
        date_default_timezone_set('Asia/Kolkata');

        $this->apiKey = 'c510cd9a-4dc9-42e9-81d7-65192e7647d8'; //Quick KYC API_KEY
    }


    public function regUserTemp_post()
    {
        $name   = $this->input->post('name');
        $email  = $this->input->post('email');
        $phone  = $this->input->post('phone');
        $state  = $this->input->post('state');
        $source = $this->input->post('source');
        $landing_url = $this->input->post('landing_url');
        $service = $this->input->post('service');
        $loan_ammount = $this->input->post('loan_ammount');

        $curdatetime = date('Y-m-d H:i:s');

        $proton = '';

        // Form Specific Data----
        if ($this->input->post('loan_type') != "") {
            $loan_type = $this->input->post('loan_type');

            if ($loan_type == "business") {
                $business_registration_proof = $this->input->post('business_registration_proof');
                $business_proof = $this->input->post('business_proof');
                $business_age = $this->input->post('business_age');
                $cibil_score = $this->input->post('cibil_score');
                $employment_status = $this->input->post('employment_status');
                $in_hand_salary = $this->input->post('in_hand_salary');
                $salary_in_bank = $this->input->post('salary_in_bank');
                $salary_slips = $this->input->post('salary_slips');
                $monthly_income = $this->input->post('monthly_income');
                $income_in_bank = $this->input->post('income_in_bank');
            } else {
                $business_registration_proof = '';
                $business_proof = '';
                $business_age = '';
                $cibil_score = $this->input->post('cibil_score');
                $employment_status = $this->input->post('employment_status');
                $in_hand_salary = $this->input->post('in_hand_salary');
                $salary_in_bank = $this->input->post('salary_in_bank');
                $salary_slips = $this->input->post('salary_slips');
                $monthly_income = $this->input->post('monthly_income');
                $income_in_bank = $this->input->post('income_in_bank');
            }


            $is_sal = null;
            $is_self_emp = null;
            if ($employment_status == 'salaried') {
                $is_sal = 1;
            } else if ($employment_status == 'self_employed') {
                $is_self_emp = 1;
            }

            $proton = '1';
        }

        // Set validation rules
        $this->form_validation->set_rules(
            'name',
            'Name',
            'required|max_length[100]',
            array('required' => 'The Name field is required.', 'alpha_space' => 'The Name field may only contain alphabetical characters and spaces.')
        );
        $this->form_validation->set_rules(
            'email',
            'Email',
            'required|valid_email|max_length[100]',
            array('required' => 'The Email field is required.', 'valid_email' => 'The Email field must contain a valid email address.')
        );
        $this->form_validation->set_rules(
            'phone',
            'Phone',
            'required|numeric|exact_length[10]',
            array('required' => 'The Phone field is required.', 'numeric' => 'The Phone field must be a valid number.', 'exact_length' => 'The Phone field must be exactly 10 digits.')
        );

        // Run validation
        if ($this->form_validation->run() == FALSE) {
            $response = [
                'status' => false
            ];
            $this->response($response, REST_Controller::HTTP_BAD_REQUEST);
            return;
        }

        // Prepare data for insertion
        if ($source != "") {
            $insertData = array(
                'name' => $name,
                'email' => $email,
                'phone' => $phone,
                'state' => $state,
                'source' => $source,
                'act_date_time' => $curdatetime,
                'landing_url' => $landing_url,
                'service' => $service,
                'loan_amount' => $loan_ammount
            );
        } else {
            $insertData = array(
                'name' => $name,
                'email' => $email,
                'phone' => $phone,
                'state' => $state,
                'act_date_time' => $curdatetime,
                'landing_url' => $landing_url,
                'service' => $service,
                'loan_amount' => $loan_ammount
            );
        }

        // Call the model function
        $res = $this->UserModel->regUserTemp($insertData, 'user_raw_leads');
        if ($res) {
            if ($proton == '1') {
                $user_loan_inquery_data = array(
                    "user_id" => $res,
                    "loan_type" => $loan_type,
                    "bussiness_reg_proof_present" => $business_registration_proof == "yes" ? 1 : 0,
                    "type_of_business_proof" => $business_proof,
                    "age_business_proof" => $business_age,
                    "is_cibil_high" => $cibil_score == "yes" ? 1 : 0,
                    "in_hand_lpa" => $in_hand_salary,
                    "rcv_salary_in_bank" => $salary_in_bank == "yes" ? 1 : 0,
                    "salary_slip_avaiable" => $salary_slips  == "yes" ? 1 : 0,
                    "is_salaried" => $is_sal,
                    "is_self_employed" => $is_self_emp,
                    "income_lpa" => $monthly_income,
                    "rcv_income_in_bank" => $income_in_bank == "yes" ? 1 : 0
                );
                @$this->UserModel->commonInsert('user_loan_inquery', $user_loan_inquery_data);
            }

            $response = [
                'status' => true,
                'message' => "Information Submitted Successfully" . $res
            ];
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        } else {
            $response = [
                'status' => false,
                'message' => "Failed to submit information."
            ];
            $this->response($response, REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
            return;
        }
    }


    public function registrationStart_post()
    {
        // Decrypt the fstep parameter
        $fstep = MasterDecrypt($this->input->post('fstep'));

        // Validate the step
        if (!in_array($fstep, [1, 2])) {
            $response = [
                'status' => false,
                'message' => 'Invalid step provided.'
            ];
            $encrypted_response = MasterEncrypt(json_encode($response));
            $this->response($encrypted_response, REST_Controller::HTTP_BAD_REQUEST);
            return;
        }

        // Handle validation based on the step
        if ($fstep == 1) {
            // Validate phone number
            $phoneNumber = MasterDecrypt($this->input->post('phone_number'));
            $phnvalidres = $this->validatePhoneNumber($phoneNumber);

            if ($phnvalidres['status'] === false) {
                // Validation failed 
                $response = [
                    'status' => false,
                    'message' => $phnvalidres['message']
                ];
                $encrypted_response = MasterEncrypt(json_encode($response));
                $this->response($encrypted_response, REST_Controller::HTTP_BAD_REQUEST);
                return;
            }

            // Decrypt the phone number

            $encrypted_phone_number = $this->encryption->encrypt($phoneNumber);

            // Validate phone number in the model
            $mdl_response = $this->UserModel->phoneMailNumValidation($phoneNumber, $encrypted_phone_number, $fstep);

            if ($mdl_response['status'] == true) {
                // Successful response
                $token_data['uid'] = $mdl_response['u_id'];
                $token_data['username'] = $mdl_response['phone'];
                $tokenData = $this->authorization_token->generateToken($token_data);
                $response = [
                    'status' => true,
                    'message' => 'OTP Sent Successfully!',
                    'access-token' => $tokenData,
                    'u_id' => $mdl_response['u_id']
                ];
                $encrypted_response = MasterEncrypt(json_encode($response));
                $this->response($encrypted_response, REST_Controller::HTTP_OK);
            } else {
                // Failed to send OTP
                $response = [
                    'status' => false,
                    'message' => 'Failed to send OTP.'
                ];
                $encrypted_response = MasterEncrypt(json_encode($response));
                $this->response($encrypted_response, REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
            }
        } else if ($fstep == 2) {
            $normal_email = MasterDecrypt($this->input->post('email'));
            $u_idnormal = MasterDecrypt($this->input->post('u_id'));
            $fullname = MasterDecrypt($this->input->post('full_name'));

            if (!$this->validateToken()) {
                return;
            }
            $decryptedUID = $this->validateAndDecryptUID($this->input->post('u_id'));
            if (!$decryptedUID) {
                return;
            }
            /* -------------------------------------| DRIVER CODE |------------------  */


            $mailvalidres = $this->validateEmail($normal_email);
            if ($mailvalidres['status'] === false) {
                $response = [
                    'status' => false,
                    'message' => $mailvalidres['message']
                ];
                $encrypted_response = MasterEncrypt(json_encode($response));
                $this->response($encrypted_response, REST_Controller::HTTP_BAD_REQUEST);
                return;
            }

            // Inserting Mail
            $insertstatus = $this->UserModel->InsertEmail($normal_email, $u_idnormal, $fullname);

            if ($insertstatus) {
                $response = [
                    'status' => true,
                    'message' => 'Email Validated Successfully'
                ];
                $encrypted_response = MasterEncrypt(json_encode($response));
                $this->response($encrypted_response, REST_Controller::HTTP_OK);
            }
        }
    }

    public function validateOtp_post()
    {
        $normal_phone = MasterDecrypt($this->input->post('phone_number'));
        $u_idnormal = MasterDecrypt($this->input->post('u_id'));
        $otp_code = MasterDecrypt($this->input->post('otp_code'));

        $uid_validres = $this->validateUID($u_idnormal);

        if ($uid_validres === false) {
            // Validation failed 
            $response = [
                'status' => false,
                'message' => "Invalid User"
            ];
            $encrypted_response = MasterEncrypt(json_encode($response));
            $this->response($encrypted_response, REST_Controller::HTTP_BAD_REQUEST);
            return;
        }

        $phn_validity_response = $this->validatePhoneNumber($normal_phone);

        if ($phn_validity_response['status'] === false) {
            // Validation failed 
            $response = [
                'status' => false,
                'message' => $phn_validity_response['message']
            ];
            // Encrypt the response
            $encrypted_response = MasterEncrypt(json_encode($response));
            $this->response($encrypted_response, REST_Controller::HTTP_BAD_REQUEST);
            return;
        }

        $otpvalidationresponse = $this->validationOtpNumber($otp_code);
        if ($otpvalidationresponse['status'] === false) {
            // Validation failed 
            $response = [
                'status' => false,
                'message' => $otpvalidationresponse['message']
            ];
            // Encrypt the response
            $encrypted_response = MasterEncrypt(json_encode($response));
            $this->response($encrypted_response, REST_Controller::HTTP_BAD_REQUEST);
            return;
        }

        // Retrieve validated input
        $mdl_res = $this->UserModel->validateOtp($normal_phone, $otp_code);

        if ($mdl_res['status'] === true) {
            // OTP is valid
            $token_data['uid'] = $mdl_res['u_id'];
            $token_data['username'] = $normal_phone;
            $access_token = $this->authorization_token->generateToken($token_data);
            $response = [
                'status' => true,
                'message' => 'OTP Validated Successfully!',
                'u_id' => $mdl_res['u_id'],
                'access-token' => $access_token,
            ];
            $status_code = REST_Controller::HTTP_OK;
        } else {
            // OTP validation failed
            $response = [
                'status' => false,
                'message' => 'Invalid OTP or phone number.'
            ];
            $status_code = REST_Controller::HTTP_UNAUTHORIZED;
        }

        // Encrypt the response 
        $encrypted_response = MasterEncrypt(json_encode($response));
        // Send the encrypted response
        $this->response($encrypted_response, $status_code);
    }

    private function validatePhoneNumber($phoneNumber)
    {
        // Check if the phone number is numeric and exactly 10 digits long
        if (!is_numeric($phoneNumber) || strlen($phoneNumber) !== 10) {
            return [
                'status' => false,
                'message' => 'Phone number must be exactly 10 digits and numeric.'
            ];
        }

        // Check if the phone number starts with a valid digit (e.g., 6-9 for Indian numbers)
        if (!preg_match('/^[6-9]\d{9}$/', $phoneNumber)) {
            return [
                'status' => false,
                'message' => 'Phone number must start with a digit between 6 and 9.'
            ];
        }

        // Further validation can be added here (e.g., checking against a database of existing phone numbers)

        return [
            'status' => true,
            'message' => 'Phone number is valid.'
        ];
    }

    private function validateEmail($email)
    {
        // Basic email format validation
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return [
                'status' => false,
                'message' => 'Invalid email format.'
            ];
        }

        // Check if the email already exists in the database
        $this->db->where('email', $email);
        $query = $this->db->get('user_applicant'); // Assuming 'users' is your table name

        if ($query->num_rows() > 0) {
            return [
                'status' => false,
                'message' => 'Email is already registered.'
            ];
        }

        return [
            'status' => true,
            'message' => 'Email is valid.'
        ];
    }

    private function validationOtpNumber($otp)
    {
        // Check if the OTP is numeric and exactly 6 digits long
        if (!is_numeric($otp) || strlen($otp) !== 6) {
            return [
                'status' => false,
                'message' => 'OTP must be a 6-digit numeric value.'
            ];
        }

        // If validation passes
        return [
            'status' => true,
            'message' => 'OTP is valid.'
        ];
    }

    /*---------------------------------------------| Registration Controller End |--------------------------------------------------------- */

    public function ValidateAdhaarNumber_post()
    {
        $adhaar_num_normal = MasterDecrypt($this->input->post('adhaar_no'));
        $u_id = MasterDecrypt($this->input->post('u_id'));

        if (!$this->validateToken()) {
            return;
        }
        $decryptedUID = $this->validateAndDecryptUID($this->input->post('u_id'));
        if (!$decryptedUID) {
            return;
        }
        /* -------------------------------------| DRIVER CODE |------------------  */

        $isExistsAdhaar = $this->previewAdhaardetailsIfExists($adhaar_num_normal, $u_id);
        if ($isExistsAdhaar['status'] == true) {
            $encrypted_response = MasterEncrypt(json_encode($isExistsAdhaar));
            $this->response($encrypted_response, REST_Controller::HTTP_OK);
            return;
        } else {
            $encrypted_response = MasterEncrypt($this->generateAdhaarOtp($adhaar_num_normal));
            $this->response($encrypted_response, REST_Controller::HTTP_OK);
            return;
        }
    }

    public function validateAdhaarOTP_post()
    {
        $adhaarOTP = MasterDecrypt($this->input->post('adhaar_otp'));
        $adhaarRequestId = MasterDecrypt($this->input->post('adhaar_req_id'));
        $u_id = MasterDecrypt($this->input->post('u_id'));

        if (!$this->validateToken()) {
            return;
        }
        $decryptedUID = $this->validateAndDecryptUID($this->input->post('u_id'));
        if (!$decryptedUID) {
            return;
        }
        /* -------------------------------------| DRIVER CODE |------------------  */

        //$gtDetailsresponse = json_decode($this->getAdhaarDetailsByOTP($adhaarRequestId, $adhaarOTP));
        // print_r($gtDetailsresponse);
        // return;
        if ($gtDetailsresponse->status == 'success') {
            $rowdata = $gtDetailsresponse->data;
            $curdate = date('Y-m-d H:i:s');
            $insertdata = array(
                "u_id" => $u_id,
                "adhaar_no" => $this->encryption->encrypt($rowdata->aadhaar_number),
                "full_name" => $this->encryption->encrypt($rowdata->full_name),
                "dob" => $this->encryption->encrypt($rowdata->dob),
                "gender" => $this->encryption->encrypt($rowdata->gender),
                "care_of" => $this->encryption->encrypt($rowdata->care_of),
                "country" => $this->encryption->encrypt($rowdata->address->country),
                "dist" => $this->encryption->encrypt($rowdata->address->dist),
                "state" => $this->encryption->encrypt($rowdata->address->state),
                "post_office" => $this->encryption->encrypt($rowdata->address->po),
                "vlc" => $this->encryption->encrypt($rowdata->address->vtc),
                "sub_dist" => $this->encryption->encrypt($rowdata->address->subdist),
                "street" => $this->encryption->encrypt($rowdata->address->street),
                "house" => $this->encryption->encrypt($rowdata->address->house),
                "landmark" => $this->encryption->encrypt($rowdata->address->landmark),
                "zip_code" => $this->encryption->encrypt($rowdata->zip),
                "adhaar_image" => $rowdata->profile_image,
                "mobile" => $rowdata->mobile_hash,
                "email" => "",
                "act_date" => $curdate,
                "share_code" => $rowdata->share_code,
                "zip_data" => $rowdata->zip_data
            );

            $insertres = $this->UserModel->insertAdhaarData('user_adhaar_info', $insertdata);
            if ($insertres == true) {
                $previewresponse = $this->previewAdhaardetailsIfExists("", $u_id);
                if ($previewresponse['status'] == true) {
                    $encrypted_response = MasterEncrypt(json_encode($previewresponse));
                    $this->response($encrypted_response, REST_Controller::HTTP_OK);
                    return;
                }
            } else {
                $response = array(
                    "status" => false,
                    "message" => 'Something Went Wrong'
                );
                $encrypted_response = MasterEncrypt(json_encode($response));
                $this->response($encrypted_response, REST_Controller::HTTP_OK);
                return;
            }
        }
    }

    public function panValidtion_post()
    {
        $u_id = MasterDecrypt($this->input->post('u_id'));
        $pan_no = MasterDecrypt($this->input->post('pan_no'));

        if (!$this->validateToken()) {
            return;
        }
        $decryptedUID = $this->validateAndDecryptUID($this->input->post('u_id'));
        if (!$decryptedUID) {
            return;
        }
        /* -------------------------------------| DRIVER CODE |------------------  */

        $panvalidresponse = json_decode($this->getPanDetails($pan_no));
        $curDate = date('Y-m-d H:i:s');

        if ($panvalidresponse->status == "success") {

            $isMatched = $this->UserModel->matchUserInfo($panvalidresponse->data->full_name, $u_id);
            if ($isMatched == false) {
                $response = [
                    'status' => false,
                    'message' => 'Pan Details Mismatched'
                ];
                $encrypted_response = MasterEncrypt(json_encode($response));
                $this->response($encrypted_response, REST_Controller::HTTP_OK);
                return;
            }

            $tabledta = array(
                'u_id' => $u_id,
                'pan_no' => $this->encryption->encrypt($panvalidresponse->data->pan_number),
                'category' => $panvalidresponse->data->category,
                'pan_status' => $panvalidresponse->status,
                'act_date' => $curDate
            );
            $updatePanData = $this->UserModel->updatePanData('user_pan_info', $tabledta);
            if ($updatePanData) {
                $response = [
                    'status' => true,
                    'message' => 'Pan Card Validated Successfully'
                ];
                $encrypted_response = MasterEncrypt(json_encode($response));
                $this->response($encrypted_response, REST_Controller::HTTP_OK);
                return;
            }
        } else {
            $response = [
                'status' => false,
                'message' => 'Pan Validation Failed'
            ];
            $encrypted_response = MasterEncrypt(json_encode($response));
            $this->response($encrypted_response, REST_Controller::HTTP_OK);
            return;
        }
    }


    private function previewAdhaardetailsIfExists($adhaarNo, $uId)
    {
        $adharModelresponse = $this->UserModel->previewAdhaardetailsIfExists($adhaarNo, $uId);
        return $adharModelresponse;
    }

    private function generateAdhaarOtp($aadhaar_number)
    {
        // Set the URL and API key

        // return json_encode(
        //     [
        //         "data" => [
        //             "otp_sent" => true,
        //             "if_number" => true,
        //             "valid_aadhaar" => true,
        //             "status" => "generate_otp_success"
        //         ],
        //         "status_code" => 200,
        //         "message" => "OTP Sent.",
        //         "status" => "success",
        //         "request_id" => 1438701
        //     ]
        // );

        $url = 'https://api.quickekyc.com/api/v1/aadhaar-v2/generate-otp';
        $apiKey = 'c510cd9a-4dc9-42e9-81d7-65192e7647d8';
        $idNumber = $aadhaar_number; // Replace with dynamic input if needed

        // Prepare the data array
        $data = array(
            'key' => $apiKey,
            'id_number' => $idNumber
        );

        // Initialize cURL
        $ch = curl_init($url);

        // Set cURL options
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        // Execute the cURL request
        $response = curl_exec($ch);

        // Check for errors
        if ($response === false) {
            $error = curl_error($ch);
            curl_close($ch);
            // Log the error or handle it as needed
            echo 'Curl error: ' . $error;
            return;
        }

        // Close cURL session
        curl_close($ch);

        // Return the response
        return $response;
    }

    private function CheckAadhaarNumber($aadhaar_number, $u_id)
    {
        // Check if Aadhaar number is provided and is numeric
        if (empty($aadhaar_number) || !is_numeric($aadhaar_number) || strlen($aadhaar_number) != 12) {
            return [
                'status' => false,
                'message' => 'Invalid Aadhaar number format. It must be a 12-digit numeric value.'
            ];
        } else {
            return [
                'status' => true,
                'message' => 'Adhaar Number is valid'
            ];
        }
    }

    private function getPanDetails($pan_no)
    {

        // return json_encode(
        //     [
        //         "data" => [
        //             "pan_number" => "EKWPB6334L",
        //             "full_name" => "SUSHMITA BHOWMIK",
        //             "category" => "person"
        //         ],
        //         "status_code" => 200,
        //         "message" => null,
        //         "status" => "success",
        //         "request_id" => 1439050
        //     ]
        // );



        $url = 'https://api.quickekyc.com/api/v1/pan/pan';

        // Data to be sent via POST
        $postData = array(
            "key" => $this->apiKey,
            "id_number" => $pan_no
        );

        // Initialize cURL session
        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));

        // Execute cURL request and get response
        $response = curl_exec($ch);

        // Check for cURL errors
        if (curl_errno($ch)) {
            $error_msg = curl_error($ch);
            curl_close($ch);
            return json_encode(array('error' => $error_msg));
        }
        curl_close($ch);

        return $response;
    }


    /*---------------------------------------------| Adhaar/Pan Controller End |--------------------------------------------------------- */

    public function getCibilScore_post()
    {
        $u_id = MasterDecrypt($this->input->post('u_id'));
        if (!$this->validateToken()) {
            return;
        }
        $decryptedUID = $this->validateAndDecryptUID($this->input->post('u_id'));
        if (!$decryptedUID) {
            return;
        }
        /* -------------------------------------| DRIVER CODE |------------------  */
        $pan_no = $this->UserModel->getPanNoByUid($u_id);
        if ($pan_no != "") {
            $cibilScore = json_decode($this->getCiBiLScoreAPI($pan_no));
            if ($cibilScore->status == true) {
                $response = [
                    'status' => true,
                    'cibil_score' => $cibilScore->cibilScore,
                    'eligible_amount' => '10000',
                    'message' => 'Cibil Score Found'
                ];
                $encrypted_response = MasterEncrypt(json_encode($response));
                $this->response($encrypted_response, REST_Controller::HTTP_OK);
                return;
            } else {
                $response = [
                    'status' => false,
                    'cibil_score' => $cibilScore->cibilScore,
                    'eligible_amount' => '',
                    'message' => 'Sorry You Are Not Eligible For The Loan'
                ];
                $encrypted_response = MasterEncrypt(json_encode($response));
                $this->response($encrypted_response, REST_Controller::HTTP_OK);
                return;
            }
        }
    }

    function getCiBiLScoreAPI($pan_no)
    {
        return json_encode(array(
            'status' => true,
            'cibilScore' => 765
        ));
    }

    /*---------------------------------------------| CIBIL Score Controller End |--------------------------------------------------------- */


    public function getUserStatus_post()
    {
        $u_id_normal = MasterDecrypt($this->input->post('u_id'));

        if (!$this->validateToken()) {
            return;
        }
        $decryptedUID = $this->validateAndDecryptUID($this->input->post('u_id'));
        if (!$decryptedUID) {
            return;
        }

        $currentStatus = $this->UserModel->getUserStatus($u_id_normal);
        if ($currentStatus['status'] == true) {
            $response = [
                'status' => true,
                'status_code' => $currentStatus['status_code'],
                'message' => $currentStatus['message']
            ];
            $encrypted_response = MasterEncrypt(json_encode($response));
            $this->response($encrypted_response, REST_Controller::HTTP_OK);
            return;
        }
    }

    public function internldecrypt_post()
    {
        $enc = $this->input->post('enc');
        echo $this->encryption->encrypt($enc);
    }

    public function viewEncryptedValue_post()
    {
        $enc = $this->input->post('enc');
        echo MasterEncrypt($enc);
    }

    public function viewdecryptedValue_post()
    {
        $enc = $this->input->post('enc');
        echo MasterDecrypt($enc);
    }

    protected function validateToken()
    {
        $headers = $this->input->request_headers();
        if (isset($headers['authorization'])) {
            $decodedToken = $this->authorization_token->validateToken($headers['authorization']);
            if (!$decodedToken['status']) {
                // Token expired or invalid
                $this->sendErrorResponse('Token Expired!', REST_Controller::HTTP_OK);
                return false;
            }
            return true;
        } else {
            $this->sendErrorResponse('Authentication failed', REST_Controller::HTTP_OK);
            return false;
        }
    }

    protected function validateAndDecryptUID($uid)
    {
        $decryptedUID = MasterDecrypt($uid);
        if (!$this->validateUID($decryptedUID)) {
            $this->sendErrorResponse('Invalid User', REST_Controller::HTTP_BAD_REQUEST);
            return false;
        }
        return $decryptedUID;
    }

    protected function sendErrorResponse($message, $httpCode)
    {
        $response = [
            'status' => false,
            'message' => $message
        ];
        $encrypted_response = MasterEncrypt(json_encode($response));
        $this->response($encrypted_response, $httpCode);
    }

    private function validateUID($u_id)
    {
        $mdl_response = $this->UserModel->validateUID($u_id);
        // Check if the length is 10 characters
        if ($mdl_response) {
            return true;
        } else {
            return false;
        }
    }

    /*---------------------------------------------| Internal Functions End |--------------------------------------------------------- */
}
