myLogger = \Config\Services::mylogger(); $this->clientModel = new ClientModel(); $this->clientBranchModel = new ClientBranchModel(); $this->policyTypeModel = new PolicyTypeModel(); $this->clientDepositModel = new ClientDepositModel(); $this->clientPolicyModel = new ClientPolicyModel(); $this->insurerBranchModel = new InsurerBranchModel(); $this->insurerModel = new InsurerModel(); $this->policyTransactionModel = new PolicyTransactionModel(); $this->policyTransactionStatusModel = new PolicyTransactionStatusModel(); $this->kycEntityTypeModel = new KYCEntityTypeModel(); $this->clientKYCDocsModel = new ClientKYCDocsModel(); $this->tpaBranchModel = new TPABranchModel(); $this->tpaModel = new TPAModel(); $this->PTFileModel = new PTFileModel(); $this->PTCOShareDetailsModel = new PTCOShareDetailsModel(); $this->employeeModel = new EmployeeModel(); $this->userTeamsModel = new UserTeamsModel(); $this->userModel = new UserModel(); $this->employeePolicyModel = new EmployeePolicyModel(); $this->insurerStatements = new InsurerStatements(); $this->invPaymentDetailsModel = new InvPaymentDetailsModel(); $this->batchFileModel = new BatchFileModel(); $this->filesModel = new FileModel(); $this->coShareStmtDetailsModel = new COShareStmtDetailsModel(); $this->invoiceStatus = [ 'pending' => 'Pending', 'generated' => 'Generated', 'sent' => 'Sent', 'payment_received' => 'Payment
Received', ]; } // Policy Transaction Inception public function viewInception() { $data['page_name'] = 'Policy'; // Static arrays for dropdowns $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance']; $data['client_type'] = [1 => 'Group', 2 => 'Individual']; $data['issuing_type'] = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over']; $data['policy_status'] = [ 'under_process' => 'Under Process', 'client_pending' => 'Client Pending', 'insurer_pending' => 'Insurer Pending', 'co_insurer_pending' => 'Co-Insurer Pending', 'tpa_pending' => 'TPA Pending', 'validated' => 'Validated', 'cancelled' => 'Cancelled', 'instalment_pending' => 'Instalment Pending', 'completed' => 'Completed', 'lost' => 'Lost', ]; $data['invoice_status_array'] = [ 'yet_to_generate' => 'Pending', 'generated' => 'Generated', 'send' => 'Sent', 'recived' => 'Payment Received', ]; $data['vehicle_type'] = [ 'two_wheeler' => 'Two Wheeler', 'four_wheeler' => 'Four Wheeler', 'truck' => 'Truck', 'bus' => 'Bus', 'van' => 'Van', 'suv' => 'SUV', 'motorcycle' => 'Motorcycle', 'bicycle' => 'Bicycle' ]; $data['vehicle_des'] = [ 'commercial' => 'Commercial', 'private' => 'Private', ]; $data['date_type'] = [ 'policy_issue_date' => 'Policy Issue Date', 'policy_start_date' => 'Policy Start Date', 'policy_end_date' => 'Policy End Date', ]; // Filter data $start_date = $this->request->getGet('start_date'); $end_date = $this->request->getGet('end_date'); $client_id = $this->request->getGet('client_id'); $insurer_id = $this->request->getGet('insurer_id'); $policy_type_id = $this->request->getGet('policy_type_id'); $date_type = $this->request->getGet('date_type'); $issuer = $this->request->getGet('issuer'); $status = $this->request->getGet('status'); // Handle null or empty values $start_date = empty($start_date) ? 0 : $start_date; $end_date = empty($end_date) ? 0 : $end_date; $client_id = empty($client_id) ? 0 : $client_id; $insurer_id = empty($insurer_id) ? 0 : $insurer_id; $policy_type_id = empty($policy_type_id) ? 0 : $policy_type_id; $date_type = empty($date_type) ? 0 : $date_type; $issuer = empty($issuer) ? 0 : $issuer; $status = empty($status) ? 0 : $status; // Corrected from `$issuer` if ($this->request->is('get')) { // Fetch inception data list $data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData( $start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status ); }else{ $ids = $this->request->getPost('ids'); $ids = array_filter(explode(',', $ids)); $data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData( $start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0, $ids ); } // Fetch additional data $data['client'] = $this->clientModel->where('is_active', 1)->findAll(); $data['client_branch'] = $this->clientBranchModel->where('is_active', 1)->findAll(); $data['policy_type'] = $this->policyTypeModel->where('is_active', 1)->findAll(); $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll(); $data['entity'] = $this->kycEntityTypeModel->where('is_active', 1)->findAll(); $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll(); $data['insurer_branch'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(); $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); // Fetch PP Teams Data $data['ppTeamsData'] = $this->userModel ->where('is_active', 1) ->findAll(); // Fetch Sales Team $data['salse_team'] = $this->userModel ->select('user_profiles.*') ->join('user_teams', 'user_profiles.id = user_teams.user_id') ->where('user_teams.team_id', 5) ->where('user_teams.is_active', 1) ->where('user_profiles.is_active', 1) ->findAll(); // Fetch ACM $data['ACM'] = $this->userModel ->where('role', 3) // Assuming `role` is in `user_profiles` ->where('is_active', 1) ->findAll(); // echo '
';
        // print_r($data['ppTeamsData']); die;

        // dd($data);

        // Load view
        $this->loadLayout('policy_transaction_inception_list', $data);
    }

    // policy Transaction Create function start
    public function createInceptionPolicy()
    {
        // print_r($this->request->getPost()); die;
        $id = $this->request->getPost('id');
        $data = $this->preparePolicyData();
        $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no');
        // print_r($this->request->getPost()); die;


        if (!$id) {
            return $this->insertInceptionPolicy($data);
        } else {
            return $this->updateInceptionPolicy($id, $data);
        }
    }

    private function preparePolicyData()
    {
        $data = $this->request->getPost();

        // print_r($data); die;
        // var_dump($data); die;

        if (empty($data['policy_issue_date'])) {
            $data['policy_issue_date'] = null;
        }

        if (empty($data['policy_start_date'])) {
            $data['policy_start_date'] = null;
        }

        if (empty($data['policy_end_date'])) {
            $data['policy_end_date'] = null;
        }

        if (empty($data['renewal_date'])) {
            $data['renewal_date'] = null;
        }

        if (empty($data['rollover_date'])) {
            $data['rollover_date'] = null;
        }

        if (empty($data['last_action_date'])) {
            $data['last_action_date'] = null;
        } else {
            $data['last_action_date'] = change_date_format($data['last_action_date']);
        }


        // Separate Insurer and TPA Branch IDs and IDs
        if (isset($data['insurer_id']) && !empty($data['insurer_id'])) {
            list($data['insurer_branch_id'], $data['insurer_id']) = explode('-', $data['insurer_id']);
            if (isset($data['tpa']) && !empty($data['tpa'])) {
                list($data['tpa_branch_id'], $data['tpa_id']) = explode('-', $data['tpa']);
            }
        }

        $data['tsi'] = generate_tsi_code($data['issue_type']);
        $data['action_type'] = 'inception';

        if (!isset($data['co_share'])) {
            $data['co_share'] = 0;
        } elseif ($data['co_share']) {
            $data['co_share'] = 1;
        }

        if (!isset($data['bro_payable_by'])) {
            $data['bro_payable_by'] = 0;
        } elseif ($data['bro_payable_by']) {
            $data['bro_payable_by'] = 1;
        }

        if (!isset($data['same_as_proposer'])) {
            $data['same_as_proposer'] = 0;
        } elseif ($data['same_as_proposer']) {
            $data['same_as_proposer'] = 1;
        }

        if (!isset($data['policy_with_corr'])) {
            $data['policy_with_corr'] = 0;
        } elseif ($data['policy_with_corr']) {
            $data['policy_with_corr'] = 1;
        }

        if (!isset($data['is_cd_reduce_from_bds'])) {
            $data['is_cd_reduce_from_bds'] = 0;
        } elseif ($data['is_cd_reduce_from_bds']) {
            $data['is_cd_reduce_from_bds'] = 1;
        }

        if ($data['ct_type'] == "") {
            $data['ct_type'] = 1;
        }

        // $month = '01-'.(string)$this->request->getPost('month');
        // $data['month'] = empty($data['month']) ? null : date('Y-m-d', strtotime($month));    

        // Determine $is_addon value
        $data['is_addon'] = in_array($data['policy_type_id'], [1, 2, 6, 7]) ? 1 : (in_array($data['policy_type_id'], [4, 5]) ? 2 : ($data['policy_type_id'] == 3 && isset($data['base_policy']) ? 3 : 1));

        // print_r($data); die;

        return $data;
    }

    private function insertInceptionPolicy($data)
    {
        // print_r($data); die;

        $insert = $this->policyTransactionModel->insert($data);
        if ($insert) {
            $this->insertTransactionStatus($insert, $data, 1);
            $emp_data = $this->processInsertIndividualMemberInEmpTable($data);

            if (isset($data['follow_insurer_id']) && !empty($data['follow_insurer_id'][0])) {

                $pt_co_share_details = $this->insertOrUpdateCoShareDetails($data, $insert);

                if ($data['ct_type'] == 2) {

                    $client_policy_insert_data = $this->prepareClientPolicyInsertData($data);
                    $client_policy_id = $this->clientPolicyModel->insert($client_policy_insert_data);
                    $this->policyTransactionModel->update($insert, ['client_policy_id' => $client_policy_id]);
                    $emp_policy_insert = $this->InsertIndividualEmpPolicyTable($emp_data, $client_policy_id);

                    if ($data['client_type'] == 1 && $data['status'] == 'completed' && $data['is_cd_reduce_from_bds'] == 1) {
                        $this->processCompletedStatus($data, $client_policy_id, $data['insurer_id']);
                    }
                }


                $data['pt_co_share_details'] = $this->PTCOShareDetailsModel->where('pt_id', $insert)->where('is_active', 1)->findAll();
            }

            $client_data = $this->clientModel->where('id', $data['client_id'])->first();
            $data['client_kyc']       = $this->clientKYCDocsModel->where('client_id',  $data['client_id'])->findAll();
            $data['entity_type_id'] =  $client_data['entity_type_id'];

            return $this->respondSuccess($insert, "Policy transaction created successfully", $data);
        }
        return $this->respondError("Failed to create policy transaction");
    }

    private function updateInceptionPolicy($id, $data)
    {
        // print_r($data); die;
        if ($this->policyTransactionModel->update($id, $data)) {

            $this->insertTransactionStatus($id, $data, 1);
            $emp_data = $this->processInsertIndividualMemberInEmpTable($data);

            if (isset($data['follow_insurer_id']) && !empty($data['follow_insurer_id'][0])) {

                $this->insertOrUpdateCoShareDetails($data, $id);

                if ($data['ct_type'] == 1) {
                    $this->policyTransactionModel->update($id, ['client_policy_id' => $data['client_policy_id']]);
                }

                if (empty($data['client_policy_id']) || $data['client_policy_id'] == 0) {

                    if ($data['ct_type'] == 2) {
                        $client_policy_insert_data = $this->prepareClientPolicyInsertData($data);
                        $client_policy_id = $this->clientPolicyModel->insert($client_policy_insert_data);
                        $this->policyTransactionModel->update($id, ['client_policy_id' => $client_policy_id]);
                        $this->InsertIndividualEmpPolicyTable($emp_data, $client_policy_id);
                    }
                } else {
                    if (isset($data['emp_policy_id']) && !empty($data['emp_policy_id'][0])) {
                        $this->InsertIndividualEmpPolicyTable($emp_data, $data['client_policy_id']);
                    }
                }

                if ($data['status'] == 'completed' && $data['ct_type'] == 2) {
                    if ($data['client_type'] == 1 && $data['is_cd_reduce_from_bds'] == 1) {
                        $this->processCompletedStatus($data, $data['client_policy_id'], $data['insurer_id']);
                    }
                }

                $data['pt_co_share_details'] = $this->PTCOShareDetailsModel->where('pt_id', $id)->where('is_active', 1)->findAll();
            }

            $client_data = $this->clientModel->where('id', $data['client_id'])->first();
            $data['client_kyc']       = $this->clientKYCDocsModel->where('client_id',  $data['client_id'])->findAll();
            $data['entity_type_id'] =  $client_data['entity_type_id'];

            return $this->respondSuccess($id, "Policy transaction updated successfully", $data);
        }

        return $this->respondError("Failed to update policy transaction");
    }

    private function insertOrUpdateCoShareDetails($data, $pt_id)
    {
        // Prepare data for insertion and updating
        $coShareDetails = [];

        // print_r($data); die;
        // die;

        if (isset($data['co_share_id']) && !empty($data['co_share_id'])) {
            $this->removePtCoShareRecords($data['co_share_id'], $pt_id);
        }

        if (isset($data['follow_insurer_id'])) {

            foreach ($data['follow_insurer_id'] as $index => $insurer) {

                // Separate the insurer and insurer branch
                if (isset($insurer) && !empty($insurer)) {
                    list($insurer_branch_id, $insurer_id) = explode('-', $insurer);
                } else {
                    $insurer_branch_id = null;
                    $insurer_id = null;
                }

                // Prepare each co-share detail entry
                $coShareDetails[] = [
                    'pt_id' => $pt_id,
                    'insurer_id' => $insurer_id ?? 0,
                    'insurer_branch_id' => $insurer_branch_id ?? 0,
                    'co_share_type' => $data['co_share_type'][$index] ?? 1,
                    'co_share_per' => $data['co_share_per'][$index] ?? 0,
                    'bp_amt' => $data['base_premium'][$index] ?? 0,
                    'bp_gst_amt' => $data['gst_amount'][$index] ?? 0,
                    'bp_igst' => $data['igst'][$index] ?? 0,
                    'bp_sgst' => $data['sgst'][$index] ?? 0,
                    'bp_cgst' => $data['cgst'][$index] ?? 0,
                    'tp_amt' => $data['tp_premium'][$index] ?? 0,
                    'tep_amt' => $data['ter_premium'][$index] ?? 0,
                    'cotp_amt' => $data['co_tp_premium'][$index] ?? 0,
                    'cotep_amt' => $data['co_ter_premium'][$index] ?? 0,
                    'agreed_amt' => $data['agreed_amount'][$index] ?? 0,
                    'agreed_bp_per' => $data['agreed_bp'][$index] ?? 0,
                    'agreed_tp_per' => $data['agreed_tp'][$index] ?? 0,
                    'agreed_tep_per' => $data['agreed_ter'][$index] ?? 0,
                    'standerd_bp_per' => $data['standard_bp'][$index] ?? 0,
                    'standerd_tp_per' => $data['standard_tp'][$index] ?? 0,
                    'standerd_tep_per' => $data['standard_ter'][$index] ?? 0,
                    'actual_bp_amt' => $data['actual_bp_amt'][$index] ?? 0,
                    'actual_tp_amt' => $data['actual_tp_amt'][$index] ?? 0,
                    'actual_tep_amt' => $data['actual_tep_amt'][$index] ?? 0,
                    'actual_bp_per' => $data['actual_bp_per'][$index] ?? 0,
                    'actual_tp_per' => $data['actual_tp_per'][$index] ?? 0,
                    'actual_tep_per' => $data['actual_tep_per'][$index] ?? 0,
                    'actual_bp_brokerage_amt' => $data['actual_bp_brokerage_amt'][$index] ?? 0,
                    'actual_tp_brokerage_amt' => $data['actual_tp_brokerage_amt'][$index] ?? 0,
                    'actual_tep_brokerage_amt' => $data['actual_tep_brokerage_amt'][$index] ?? 0,
                    'exp_amt' => $data['exp_amt'][$index] ?? 0,
                    'amount' => $data['total'][$index] ?? 0,
                    'stamp_duty' => $data['stamp_duty'][$index] ?? 0,
                    'cop_amt' => $data['co_premium'][$index] ?? 0,
                    'variance' => $data['variance'][$index] ?? 0,
                    'reward' => $data['reward'][$index] ?? null,
                    'created_by' => get_session_userid() ?? null,
                    'updated_by' => get_session_userid() ?? null,
                    'id' => $data['co_share_id'][$index] ?? null, // Assuming this is the ID to identify existing records
                    'follower_policy_no' => $data['follower_policy_no'][$index] ?? null,
                    'non_comm_per_amt' => $data['non_comm_per_amt'][$index] ?? null,
                ];
            }

            // print_r($pt_id); 
            // print_r($coShareDetails); 
            // die;

            // Separate data into insert and update batches
            $insertData = array_filter($coShareDetails, function ($detail) {
                return empty($detail['id']); // Only insert new records
            });

            $updateData = array_filter($coShareDetails, function ($detail) {
                return !empty($detail['id']); // Only update existing records
            });

            // Insert new records
            if (!empty($insertData)) {
                $this->PTCOShareDetailsModel->insertBatch($insertData);
            }

            // Update existing records
            if (!empty($updateData)) {
                $this->PTCOShareDetailsModel->updateBatch($updateData, 'id'); // Assuming 'id' is the unique identifier
            }

            // print_r($this->PTCOShareDetailsModel->getLastQuery()); die;

            // print_r($coShareDetails); 
            // die;

            return true;
        }

        // print_r($data); 
        // die;
    }

    private function prepareClientPolicyInsertData($data)
    {
        return [
            'client_id' => $data['client_id'] ?? null,
            'insurer_id' => $data['insurer_id'] ?? null,
            'insurer_branch_id' => $data['insurer_branch_id'] ?? null,
            'tpa_id' => $data['tpa_id'] ?? null,
            'tpa_branch_id' => $data['tpa_branch_id'] ?? null,
            'policy_type_id' => $data['policy_type_id'] ?? null,
            'policy_start_date' => $data['policy_start_date'] ?? null,
            'policy_end_date' => $data['policy_end_date'] ?? null,
            'policy_status' => 1,
            'is_addon' => $data['is_addon'] ?? null,
            'base_policy' => $data['base_policy'] ?? 0,
            'created_by' => get_session_userid(),
            'policy_no' => $data['policy_no'] ?? null,
            'client_branch_id' => $data['client_branch_id'] ?? 0,
            'cd_ac_pk' => $data['cd_ac_no'] ?? null,
            'gst' => 18,
        ];
    }

    private function insertTransactionStatus($policyTranId, $data, $statusType)
    {
        $statusData = [
            'policy_tran_id' => $policyTranId,
            'status' => $data['status'],
            'last_action_date' => $data['last_action_date'],
            'status_type' => $statusType,
            'created_by' => get_session_userid(),
        ];
        $this->policyTransactionStatusModel->insert($statusData);
    }

    private function processCompletedStatus($data, $client_policy_id, $insurer_id)
    {
        $totalAmount = (int)$data['total'][0] ?? 0;
        $description = 'The following amount of Rs. ' . $totalAmount . '/- has been debited for the ' . $data['emp_count'] . ' employees at Inception (BDS).';

        $cdTransactionData = [
            'amount' => $totalAmount,
            'sub_type_id' => 4,
            'client_id' => $data['client_id'],
            'client_policy_id' => $client_policy_id ?? 0,
            'endorsement_no' => null,
            'cd_ac_no' => $data['cd_ac_no'] ?? null,
            'insurer_id' => $insurer_id,
            'description' => $description,
            'transaction_type' => 'Debit',
            'updated_by' => get_session_userid(),
            'event_name' => 'inception',
            'is_active' => 1,
            'cd_ac_pk'  => $data['cd_ac_pk']
        ];

        DepositHelper::saveDeposit($cdTransactionData, get_session_userid());
    }

    private function processInsertIndividualMemberInEmpTable($data)
    {
        // print_r($data);
        if (isset($data['family_name']) && !empty($data['family_name'])) {

            $emp_data = [];
            $emp_ids = [];
            $random_code = generateRandomCode(); // Generate random code once

            foreach ($data['family_name'] as $index => $val) {

                // Determine the gender based on the relationship
                $relationship = $data['relationship'][$index] ?? '';
                $gender = 'M'; // Default to Male

                // Set gender based on relationship
                if (in_array($relationship, ['Mother', 'Daughter', 'Mother in law', 'Spouse'])) {
                    $gender = 'F';
                }

                $emp_data[] = [
                    'client_id' => $data['client_id'] ?? 0,
                    'client_branch_id' => $data['client_branch_id'] ?? 0,
                    'name' => $val,
                    'relationship' => $relationship,
                    'gender' => $gender,
                    'emp_status' => 'active',
                    'created_by' => get_session_userid(),
                    'emp_code' => $random_code, // Use the same random code for all
                    'id' => $data['emp_id'][$index] ?? null
                ];

                $emp_ids[] = $data['emp_id'][$index] ?? 0;
            }


            // print_r($emp_data); die;

            // Separate data into insert and update batches
            $insertData = array_filter($emp_data, function ($detail) {
                return empty($detail['id']); // Only insert new records
            });

            $updateData = array_filter($emp_data, function ($detail) {
                return !empty($detail['id']); // Only update existing records
            });

            // Insert new records
            if (!empty($insertData)) {
                $this->employeeModel->insertBatch($insertData);
            }

            // Update existing records
            if (!empty($updateData)) {
                $this->employeeModel->updateBatch($updateData, 'id'); // Assuming 'id' is the unique identifier
            }

            return $emp_ids;
        }
    }

    private function InsertIndividualEmpPolicyTable($emp_ids, $client_policy_id)
    {
        if (!empty($emp_ids)) {

            $emp_policy_data = [];

            foreach ($emp_ids as $index => $emp_id) {

                $emp_policy_data[] = [
                    'employee_id' => $emp_id ?? 0,
                    'client_policy_id' => $client_policy_id ?? 0,
                    'created_by' => get_session_userid(),
                    'status' => 'active',
                ];
            }

            // print_r($emp_policy_data); die;

            // Insert new records
            if (!empty($emp_policy_data)) {
                $this->employeePolicyModel->insertBatch($emp_policy_data);
            }


            return true;
        }
    }

    private function respondSuccess($id, $message, $data)
    {
        return $this->respond(['status' => true, 'pt_id' => $id, 'message' => $message, 'data' => $data], 200);
    }

    private function respondError($message)
    {
        return $this->respond(['status' => false, 'message' => $message], 200);
    }
    // policy Transaction Create function End

    // Get the Single Inception Tranction data for edit
    public function getInceptionDataForEdit($id)
    {
        $data = $this->policyTransactionModel
            ->select('
                        policy_transaction.*, 
                        clients.short_name as client_short_name, 
                        clients.client_type, 
                        clients.entity_type_id, 
                        policy_type.policy_type,
                        client_policy.tpa_id as master_tpa_id,
                        client_policy.tpa_branch_id as master_tpa_branch_id,
                        client_policy.policy_type_id as master_policy_type_id,
                        client_policy.is_addon,
                        client_policy.base_policy,
                        ( 
                            select last_action_date
                            from policy_transaction_status
                            where policy_tran_id = policy_transaction.id
                            and status = policy_transaction.status
                            order by id desc
                            limit 1

                        ) as last_action_date
                    ')
            ->join('clients', 'clients.id = policy_transaction.client_id')
            ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
            ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
            ->where('policy_transaction.id', $id)
            ->where('policy_transaction.is_active', 1)
            ->first();

        // $data['policy_issue_date'] = (isset($data['policy_issue_date']) && $data['policy_issue_date'] !== null && $data['policy_issue_date'] !== '') 
        //     ? date('d/m/Y', strtotime($data['policy_issue_date'])) 
        //     : null;

        // $data['policy_start_date'] = (isset($data['policy_start_date']) && $data['policy_start_date'] !== null && $data['policy_start_date'] !== '') 
        //     ? date('d/m/Y', strtotime($data['policy_start_date'])) 
        //     : null;

        // $data['policy_end_date'] = (isset($data['policy_end_date']) && $data['policy_end_date'] !== null && $data['policy_end_date'] !== '') 
        //     ? date('d/m/Y', strtotime($data['policy_end_date'])) 
        //     : null;

        // $data['renewal_date'] = (isset($data['renewal_date']) && $data['renewal_date'] !== null && $data['renewal_date'] !== '') 
        //     ? date('d/m/Y', strtotime($data['renewal_date'])) 
        //     : null;

        // $data['rollover_date'] = (isset($data['rollover_date']) && $data['rollover_date'] !== null && $data['rollover_date'] !== '') 
        //     ? date('d/m/Y', strtotime($data['rollover_date'])) 
        //     : null;

        // $data['month'] = (isset($data['month']) && $data['month'] !== null && $data['month'] !== '') 
        //     ? date('M/Y', strtotime($data['month'])) 
        //     : null;


        $data['created_at'] = (isset($data['created_at']) && $data['created_at'] !== null && $data['created_at'] !== '')
            ? date('d/m/Y h:i:s A', strtotime($data['created_at']))
            : null;

        $data['updated_at'] = (isset($data['updated_at']) && $data['updated_at'] !== null && $data['updated_at'] !== '')
            ? date('d/m/Y h:i:s A', strtotime($data['updated_at']))
            : null;


        if (!empty($data['policy_issue_date'])) {
            $data['policy_issue_date'] =  change_date_format($data['policy_issue_date'], 'Y-m-d', 'd/m/Y');
        }

        if (!empty($data['policy_start_date'])) {
            $data['policy_start_date'] =  change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
        }

        if (!empty($data['policy_end_date'])) {
            $data['policy_end_date'] =  change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y');
        }

        if (!empty($data['renewal_date'])) {
            $data['renewal_date'] =  change_date_format($data['renewal_date'], 'Y-m-d', 'd/m/Y');
        }

        if (!empty($data['rollover_date'])) {
            $data['rollover_date'] =  change_date_format($data['rollover_date'], 'Y-m-d', 'd/m/Y');
        }

        if (!empty($data['endorse_eff_date'])) {
            $data['endorse_eff_date'] =  change_date_format($data['endorse_eff_date'], 'Y-m-d', 'd/m/Y');
        }

        if (!empty($data['last_action_date'])) {
            $data['last_action_date'] =  change_date_format($data['last_action_date'], 'Y-m-d', 'd/m/Y');
        }

        if (!empty($data['month'])) {
            $data['month'] =  change_date_format($data['month'], 'Y-m-d', 'M/Y');
        } else {
            $data['month'] = null;
        }



        // print_r($data); die;

        $data['renewal_policy'] = $this->clientPolicyModel
            ->select('client_policy.*, policy_type.policy_type')
            ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
            ->where('client_policy.client_id', $data['client_id'])
            ->where('client_policy.client_branch_id', $data['client_branch_id'])
            ->where('client_policy.is_active', 1)
            ->findAll();


        $data['base_policy_data'] = $this->clientPolicyModel
            ->select('client_policy.*, policy_type.policy_type')
            ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
            ->where('client_policy.client_id', $data['client_id'])
            ->where('client_policy.client_branch_id', $data['client_branch_id'])
            ->whereIn('client_policy.policy_type_id', [2, 3])
            ->where('client_policy.is_active', 1)
            ->findAll();


        $ptFileQuery = $this->PTFileModel
            ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
            ->where('pt_files.pt_id', $id)
            ->where('pt_files.is_active', 1);

        if (!in_array(get_role_id(), [1, 5]) && empty(array_intersect(user_team(), [MANAGEMENT_TEAM_ID, FINANCE_TEAM_ID, BUSINESS_TEAM_ID]))) {

            if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
                $ptFileQuery->where('pt_files.created_by', get_session_userid());
            }
        }

        $data['pt_files'] = $ptFileQuery->findAll();



        $data['pt_co_share_details'] = $this->PTCOShareDetailsModel
            ->select("
                    pt_co_share_details.*,
            
                    (
                        SELECT
                            COUNT(*)
                        FROM
                            co_share_stmt_details
                        WHERE
                            co_share_stmt_details.co_share_id = pt_co_share_details.id
                            AND co_share_stmt_details.is_active = 1
                    ) AS record_count,

                        (
                            SELECT 
                                SUM(actual_bp_amt) 
                            FROM 
                                co_share_stmt_details 
                            WHERE 
                                co_share_id = pt_co_share_details.id 
                                AND is_active = 1
                                
                        ) AS actual_bp_amount,
                        
                        (
                            SELECT 
                                SUM(actual_tp_amt) 
                            FROM 
                                co_share_stmt_details 
                            WHERE 
                                co_share_id = pt_co_share_details.id 
                                AND is_active = 1
                                
                        ) AS actual_tp_amount,
                        
                        (
                            SELECT 
                                SUM(actual_tep_amt) 
                            FROM 
                                co_share_stmt_details 
                            WHERE 
                                co_share_id = pt_co_share_details.id 
                                AND is_active = 1
                                
                        ) AS actual_tep_amount,
                        
                        (
                            SELECT 
                                SUM(actual_bp_per) 
                            FROM 
                                co_share_stmt_details 
                            WHERE 
                                co_share_id = pt_co_share_details.id 
                                AND is_active = 1
                                
                        ) AS actual_bp_percentage,
                        
                        (
                            SELECT 
                                SUM(actual_tp_per) 
                            FROM 
                                co_share_stmt_details 
                            WHERE 
                                co_share_id = pt_co_share_details.id 
                                AND is_active = 1
                                
                        ) AS actual_tp_percentage,
                        
                        (
                            SELECT 
                                SUM(actual_tep_per) 
                            FROM 
                                co_share_stmt_details 
                            WHERE 
                                co_share_id = pt_co_share_details.id 
                                AND is_active = 1
                                
                        ) AS actual_tep_percentage,
                        
                        
                        (
                            SELECT 
                                SUM(actual_bp_brokerage_amt) 
                            FROM 
                                co_share_stmt_details 
                            WHERE 
                                co_share_id = pt_co_share_details.id 
                                AND is_active = 1
                                
                        ) AS actual_bp_brokerage_amount,
                        
                        
                        (
                            SELECT 
                                SUM(actual_tp_brokerage_amt) 
                            FROM 
                                co_share_stmt_details 
                            WHERE 
                                co_share_id = pt_co_share_details.id 
                                AND is_active = 1
                                
                        ) AS actual_tp_brokerage_amount,
                        
                        
                        (
                            SELECT 
                                SUM(actual_tep_brokerage_amt) 
                            FROM 
                                co_share_stmt_details 
                            WHERE 
                                co_share_id = pt_co_share_details.id 
                                AND is_active = 1
                                
                        ) AS actual_tep_brokerage_amount

                ")
            ->where('pt_id', $id)
            ->where('is_active', 1)
            ->orderBy('id', 'asc')
            ->findAll();

        $data['emp_data'] = $this->employeeModel
            ->select('employees.*, employee_polices.id as emp_policy_id')
            ->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left')
            ->where('employees.client_id', $data['client_id'])
            ->where('employees.is_active', 1)->findAll();
        $data['client_kyc']   = $this->clientKYCDocsModel->where('client_id',  $data['client_id'])->findAll();
        $data['vehicle_docs'] = $this->clientKYCDocsModel
            ->where('client_id',  $data['client_id'])
            ->where('vehicle_id', $data['vehicle_id'])
            ->findAll();

        // print_r( $data['pt_co_share_details']); die;

        if ($data) {
            return $this->respond(['status' => true, 'data' => $data], 200);
        } else {
            return $this->respond(['status' => false], 200);
        }
    }

    public function removePolicyTransaction($id)
    {
        if ($id) {

            $data['is_active']  = 0;
            $this->policyTransactionModel->where('id', $id)->set($data)->update();
            $this->PTCOShareDetailsModel->where('pt_id', $id)->set($data)->update();
            return $this->respond(['status' => true, 'code' => 200, 'message' => 'Policy Transaction removed successfully'], 200);
        } else {

            return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove policy transaction'], 200);
        }
    }

    //function for soft delete for pt_co_share_details records
    public function removePtCoShareRecords($primaryKeys, $pt_id)
    {
        if (empty($primaryKeys)) {
            return false;
        }

        // Convert array to a comma-separated string of placeholders for query binding
        $placeholders = implode(',', array_fill(0, count($primaryKeys), '?'));

        // Prepare the query with proper binding
        $sql = "UPDATE pt_co_share_details SET is_active = 0 WHERE pt_id = ? AND id NOT IN ($placeholders)";

        // Merge pt_id with primary keys for binding
        $params = array_merge([$pt_id], $primaryKeys);

        // Execute the query with bound parameters
        return db_connect()->query($sql, $params);
    }


    //------------------------------------------------------------------------------------------------

    // Policy Transaction Endorsement
    public function viewEndorsement()
    {
        // echo '
';
        // !dd($this->getEndorsementDataForEdit(17));

        $data['page_name'] = 'Endorsement';

        $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
        $data['client_type'] = [1 => 'Group', 2 => 'Individual'];

        $data['policy_status'] = [
            'under_process' => 'Under Process',
            'client_pending' => 'Client Pending',
            'insurer_pending' => 'Insurer Pending',
            'co_insurer_pending' => 'Co-Insurer Pending',
            'tpa_pending' => 'TPA Pending',
            'validated' => 'Validated',
            'cancelled' => 'Cancelled',
            'instalment_pending' => 'Instalment Pending',
            'completed' => 'Completed',
        ];

        $data['invoice_status'] = [
            'yet_to_generate' => 'Pending',
            'generated' => 'Generated',
            'send' => 'Sent',
            'recived' => 'Payment Received',
        ];

        $data['action_type'] = [
            'addition' => 'Addition',
            'deletion' => 'Deletion',
            'addition_deletion' => 'Addition & Deletion',
            'si_enhancement' => 'SI Enhancement',
            'combo_a_d_si' => 'Combo A, D & SI',
            'correction' => 'Correction',
            'baby_addition' => 'Baby Addition',
            'policy_instalment' => 'Policy Instalment',
            'addition_inception' => 'Addition-Inception',
            'bds_correction' => 'BDS Correction',
            'policy_correction' => 'Policy Correction',
            'policy_cancellation' => 'Policy Cancellation',
        ];

        $data['date_type'] = [
            'policy_issue_date' => 'Policy Issue Date',
            'policy_start_date' => 'Policy Start Date',
            'policy_end_date' => 'Policy End Date',
        ];

        //filter datas
        $start_date = $this->request->getGet('start_date');
        $end_date = $this->request->getGet('end_date');
        $client_id = $this->request->getGet('client_id');
        $insurer_id = $this->request->getGet('insurer_id');
        $policy_type_id = $this->request->getGet('policy_type_id');
        $date_type = $this->request->getGet('date_type');
        $issuer = $this->request->getGet('issuer');
        $status = $this->request->getGet('status');

        $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
        $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;

        $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
        $status = (!isset($issuer) || $status === '' || $status === null) ? 0 : $status;


        $data['endorsement_data_list'] = $this->policyTransactionModel->getEndorsementTranctionListData($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status);
        $data['client'] = $this->clientModel->where('is_active', 1)->findAll();
        $data['policy_type'] = $this->policyTypeModel->where('is_active', 1)->findAll();

        $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
        // $data['tpa']           = $this->tpaModel->where('is_active', 1)->findAll();
        $data['insurer_branch']      = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
        $data['tpa']           = $this->tpaBranchModel->getTpaBranchesWithTpaNames();


        $this->loadLayout('policy_transaction_endorsement_list', $data);
    }

    public function createEndorsementPolicy()
    {
        $id = $this->request->getPost('id');
        $data = $this->preparePolicyTransactionData();
        // print_r($data); die;

        if (!$id) {
            return $this->insertEndorsementTransaction($data);
        } else {
            return $this->updateEndorsementTransaction($id, $data);
        }
    }

    private function preparePolicyTransactionData()
    {
        $data = $this->request->getPost();

        // echo '
';
        // print_r($data); 
        // die;

        if (!isset($data['policy_with_corr'])) {
            $data['policy_with_corr'] = 0;
        } elseif ($data['policy_with_corr']) {
            $data['policy_with_corr'] = 1;
        }

        if (!isset($data['is_cd_reduce_from_bds'])) {
            $data['is_cd_reduce_from_bds'] = 0;
        } elseif ($data['is_cd_reduce_from_bds']) {
            $data['is_cd_reduce_from_bds'] = 1;
        }

        if (empty($data['data_received_date'])) {
            $data['data_received_date'] = null;
        } else {
            $data['data_received_date'] =  change_date_format($data['data_received_date'], 'd/m/Y', 'Y-m-d');
        }

        if (empty($data['policy_issue_date'])) {
            $data['policy_issue_date'] = null;
        } else {
            $data['policy_issue_date'] =  change_date_format($data['policy_issue_date'], 'd/m/Y', 'Y-m-d');
        }

        if (empty($data['endorse_eff_date'])) {
            $data['endorse_eff_date'] = null;
        } else {
            $data['endorse_eff_date'] =  change_date_format($data['endorse_eff_date'], 'd/m/Y', 'Y-m-d');
        }

        if (empty($data['install_due_date'])) {
            $data['install_due_date'] = null;
        } else {
            $data['install_due_date'] =  change_date_format($data['install_due_date'], 'd/m/Y', 'Y-m-d');
        }

        if (!empty($data['month'])) {
            $month = '01/' . $data['month'];
            $data['month'] =  change_date_format($month, 'd/M/Y', 'Y-m-d');
        }

        if (empty($data['last_action_date'])) {
            $data['last_action_date'] = null;
        } else {
            $data['last_action_date'] = change_date_format($data['last_action_date']);
        }

        // print_r($data); die;   

        // Separate Insurer and TPA Branch IDs and IDs
        if (isset($data['insurer_id']) && !empty($data['insurer_id'])) {
            list($data['insurer_branch_id'], $data['insurer_id']) = explode('-', $data['insurer_id']);
            if (isset($data['tpa']) && !empty($data['tpa'])) {
                list($data['tpa_branch_id'], $data['tpa_id']) = explode('-', $data['tpa']);
            }
        }

        $issue_type = $this->policyTransactionModel
            ->where('action_type', 'inception')
            ->where('client_id', $this->request->getPost('client_id'))
            ->where('client_policy_id', $this->request->getPost('client_policy_id'))
            ->where('policy_transaction.is_active', 1)
            ->first();

        $data['tsi'] = generate_tsi_code($issue_type['issue_type'] ?? 1);

        $client_branch_id = $data['client_branch_id'];
        if ($data['client_branch_id'] == "") {
            $client_branch_id = $issue_type['client_branch_id'];
        }

        if (!$data['id']) {

            $data += [
                'issuer' => $issue_type['issuer'] ?? null,
                'client_type' => $data['client_type'] ?? $issue_type['client_type'] ?? null,
                'policy_type_id' => $issue_type['policy_type_id'] ?? null,
                'issue_type' => $issue_type['issue_type'] ?? null,
                'source_client_policy_id' => $issue_type['source_client_policy_id'] ?? null,
                'cd_ac_no' => isset($data['cd_ac_no']) && !empty($data['cd_ac_no']) ? $data['cd_ac_no'] : $issue_type['cd_ac_no'] ?? null,
                'cd_ac_pk' => isset($data['cd_ac_pk']) && !empty($data['cd_ac_pk']) ? $data['cd_ac_pk'] : $issue_type['cd_ac_pk'] ?? null,
                // 'policy_issue_date' => $issue_type['policy_issue_date'] ?? null,
                'policy_start_date' => $issue_type['policy_start_date'] ?? null,
                'policy_end_date' => $issue_type['policy_end_date'] ?? null,
                'revenue_type' =>  $issue_type['revenue_type'] ?? null,
                'co_share' => $issue_type['co_share'] ?? 0,
                'bro_payable_by' => $issue_type['bro_payable_by'] ?? 0,
                'installment' => $issue_type['installment'] ?? null,
                'installment_data' => $issue_type['installment_data'] ?? null,
                'location' => $issue_type['location'] ?? null,
                'links' =>  $issue_type['links'] ?? null,
                'stage' => $issue_type['stage'] ?? null,
                'etat' => $issue_type['etat'] ?? null,
                'etat_band' => $issue_type['etat_band'] ?? null,
                'edate' => $issue_type['edate'] ?? null,
                'renewal_date' => $issue_type['renewal_date'] ?? null,
                'rollover_date' => $issue_type['rollover_date'] ?? null,
                'policy_holder_name' => $issue_type['policy_holder_name'] ?? null,
                'same_as_proposer' => $issue_type['same_as_proposer'] ?? 1,
                'ref' => $issue_type['ref'] ?? null,
                'spl' => $issue_type['spl'] ?? null,
                'fund_received' => $issue_type['fund_received'] ?? null,
                'listed_insurers' => $issue_type['listed_insurers'] ?? null,
                'ppteam' => $issue_type['ppteam'] ?? null,
                'sales_generated_by' => $issue_type['sales_generated_by'] ?? null,
                'serviced_by' => $issue_type['serviced_by'] ?? null
            ];

            $data['client_branch_id'] = $client_branch_id;
        }

        // print_r($issue_type); 
        // print_r($data); 
        // die;

        return $data;
    }

    private function insertEndorsementTransaction($data)
    {
        $insert = $this->policyTransactionModel->insert($data);

        if ($insert) {

            $this->insertTransactionStatus($insert, $data, 1);
            $this->handleCompletedStatus($data, $insert);
            $this->insertOrUpdateCoShareDetails($data, $insert);

            return $this->respond(['status' => true, 'message' => 'Endorsement transaction created successfully'], 200);
        }

        return $this->respond(['status' => false, 'message' => 'Endorsement transaction creation failed'], 400);
    }

    private function updateEndorsementTransaction($id, $data)
    {
        $update = $this->policyTransactionModel->where('id', $id)->set($data)->update();

        if ($update) {

            $this->insertTransactionStatus($id, $data, 1);
            $this->handleCompletedStatus($data, $id);
            $this->insertOrUpdateCoShareDetails($data, $id);


            return $this->respond(['status' => true, 'message' => 'Endorsement transaction updated successfully'], 200);
        }

        return $this->respond(['status' => false, 'message' => 'Endorsement transaction update failed'], 400);
    }

    private function handleCompletedStatus($data, $policy_tran_id)
    {
        if ($data['client_type'] == 1 && $data['status'] == 'completed' && $data['is_cd_reduce_from_bds'] == 1) {

            $tolamt = $data['total'][0] ?? 0;

            $description = 'The following amount of Rs. ' . round($tolamt, 2) . '/- has been' .
                ($data['action_type'] == 'deletion' ? ' Credit ' : ' Debit ') . 'from the policy transaction (BDS)';

            $cd_tranction_data = [
                'amount' => $tolamt,
                'sub_type_id' => $data['action_type'] == 'deletion' ? 3 : 4,
                'client_id' => $data['client_id'],
                'client_policy_id' => $data['client_policy_id'],
                'endorsement_no' => null,
                'cd_ac_no' => $data['cd_ac_no'] ?? null,
                'insurer_id' => $data['insurer_id'],
                'description' => $description,
                'transaction_type' => $data['action_type'] == 'deletion' ? 'Credit' : 'Debit',
                'updated_by' => get_session_userid(),
                'event_name' => $data['action_type'],
                'is_active' => 1,
                'cd_ac_pk' => $data['cd_ac_pk'] ?? null,
            ];

            DepositHelper::saveDeposit($cd_tranction_data, get_session_userid());
        }
    }

    public function getEndorsementDataForEdit($id)
    {
        $data = $this->policyTransactionModel
            ->select('
                        policy_transaction.*, 
                        clients.short_name as client_short_name, 
                        clients.client_type, 
                        ( 
                            select last_action_date
                            from policy_transaction_status
                            where policy_tran_id = policy_transaction.id
                            and status = policy_transaction.status
                            order by id desc
                            limit 1

                        ) as last_action_date
                    ')
            ->join('clients', 'clients.id = policy_transaction.client_id')
            ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
            ->where('policy_transaction.id', $id)
            ->where('policy_transaction.is_active', 1)
            ->orderBy('id', 'asc')
            ->first();


        if (!empty($data['policy_start_date'])) {
            $data['policy_start_date'] =  change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
        }

        if (!empty($data['policy_end_date'])) {
            $data['policy_end_date'] =  change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y');
        }

        if (!empty($data['data_received_date'])) {
            $data['data_received_date'] =  change_date_format($data['data_received_date'], 'Y-m-d', 'd/m/Y');
        }

        if (!empty($data['policy_issue_date'])) {
            $data['policy_issue_date'] =  change_date_format($data['policy_issue_date'], 'Y-m-d', 'd/m/Y');
        }

        if (!empty($data['endorse_eff_date'])) {
            $data['endorse_eff_date'] =  change_date_format($data['endorse_eff_date'], 'Y-m-d', 'd/m/Y');
        }

        if (!empty($data['install_due_date'])) {
            $data['install_due_date'] =  change_date_format($data['install_due_date'], 'Y-m-d', 'd/m/Y');
        }

        if (!empty($data['last_action_date'])) {
            $data['last_action_date'] =  change_date_format($data['last_action_date'], 'Y-m-d', 'd/m/Y');
        }

        if (!empty($data['month'])) {
            $data['month'] =  change_date_format($data['month'], 'Y-m-d', 'M/Y');
        }

        // print_r($data); die;

        //get PT Co-Share Details
        $data['pt_co_share_details'] = $this->PTCOShareDetailsModel

            ->select("
                        pt_co_share_details.*,
                
                        (
                            SELECT
                                COUNT(*)
                            FROM
                                co_share_stmt_details
                            WHERE
                                co_share_stmt_details.co_share_id = pt_co_share_details.id
                                AND co_share_stmt_details.is_active = 1
                        ) AS record_count,
    
                            (
                                SELECT 
                                    SUM(actual_bp_amt) 
                                FROM 
                                    co_share_stmt_details 
                                WHERE 
                                    co_share_id = pt_co_share_details.id 
                                    AND is_active = 1
                                    
                            ) AS actual_bp_amount,
                            
                            (
                                SELECT 
                                    SUM(actual_tp_amt) 
                                FROM 
                                    co_share_stmt_details 
                                WHERE 
                                    co_share_id = pt_co_share_details.id 
                                    AND is_active = 1
                                    
                            ) AS actual_tp_amount,
                            
                            (
                                SELECT 
                                    SUM(actual_tep_amt) 
                                FROM 
                                    co_share_stmt_details 
                                WHERE 
                                    co_share_id = pt_co_share_details.id 
                                    AND is_active = 1
                                    
                            ) AS actual_tep_amount,
                            
                            (
                                SELECT 
                                    SUM(actual_bp_per) 
                                FROM 
                                    co_share_stmt_details 
                                WHERE 
                                    co_share_id = pt_co_share_details.id 
                                    AND is_active = 1
                                    
                            ) AS actual_bp_percentage,
                            
                            (
                                SELECT 
                                    SUM(actual_tp_per) 
                                FROM 
                                    co_share_stmt_details 
                                WHERE 
                                    co_share_id = pt_co_share_details.id 
                                    AND is_active = 1
                                    
                            ) AS actual_tp_percentage,
                            
                            (
                                SELECT 
                                    SUM(actual_tep_per) 
                                FROM 
                                    co_share_stmt_details 
                                WHERE 
                                    co_share_id = pt_co_share_details.id 
                                    AND is_active = 1
                                    
                            ) AS actual_tep_percentage,
                            
                            
                            (
                                SELECT 
                                    SUM(actual_bp_brokerage_amt) 
                                FROM 
                                    co_share_stmt_details 
                                WHERE 
                                    co_share_id = pt_co_share_details.id 
                                    AND is_active = 1
                                    
                            ) AS actual_bp_brokerage_amount,
                            
                            
                            (
                                SELECT 
                                    SUM(actual_tp_brokerage_amt) 
                                FROM 
                                    co_share_stmt_details 
                                WHERE 
                                    co_share_id = pt_co_share_details.id 
                                    AND is_active = 1
                                    
                            ) AS actual_tp_brokerage_amount,
                            
                            
                            (
                                SELECT 
                                    SUM(actual_tep_brokerage_amt) 
                                FROM 
                                    co_share_stmt_details 
                                WHERE 
                                    co_share_id = pt_co_share_details.id 
                                    AND is_active = 1
                                    
                            ) AS actual_tep_brokerage_amount
    
                    ")
            ->where('pt_id', $id)
            ->where('is_active', 1)
            ->orderBy('id', 'asc')
            ->findAll();

        // print_r($data['endorse_eff_date']); die;

        if ($data) {
            return $this->respond(['status' => true, 'data' => $data], 200);
        } else {
            return $this->respond(['status' => false], 200);
        }
    }

    //------------------------------------------------------------------------------------------------

    //file upload function 
    public function uploadFile()
    {
        $GoogleDriveController = new GoogleDriveController();
        $files = $this->request->getFiles();
        $doc_name = $this->request->getPost('doc_name[]');
        $pt_id = $this->request->getPost('pt_id');
        $client_policy_id = $this->request->getPost('client_policy_id');
        $data = $this->request->getPost();

        $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';

        $uploadData = [];

        foreach ($data['doc_name'] as $key => $docName) {

            // Get the corresponding file for this document name
            $file = $files['file'][$key];

            if (!empty($docName) && $file->isValid() && !$file->hasMoved()) {

                // Upload the file
                $uploadedFileName = file_Upload($file, $uploadFilePath);

                if ($uploadedFileName) {
                    // Prepare data for each document upload
                    $docData = [
                        'pt_id' => $pt_id,
                        'doc_name' => $docName,
                        'file_name' => $uploadedFileName,
                        'created_by' => get_session_userid(),
                    ];

                    // $uploadFilePath = $uploadFilePath . '/' . $uploadedFileName;

                    // $GoogleDriveController->uploadFiletoGdrive(client_policy_id: $client_policy_id, doc_type: 'POLICY', file_path: $uploadFilePath, file_name: $uploadedFileName);

                    // Insert into database
                    $insert = $this->PTFileModel->insert($docData);

                    if ($insert) {
                        $uploadData[] = $docData;
                    }
                }
            }
        }

        // print_r($uploadData); die;

        // $uploadData = uploadFilesToGoogleDrive($files['file'], $doc_name, $pt_id);

        if (!empty($uploadData)) {

            $ptFileQuery = $this->PTFileModel
                ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
                ->where('pt_files.pt_id', $pt_id)
                ->where('pt_files.is_active', 1);

            if (!in_array(get_role_id(), [1, 5]) && empty(array_intersect(user_team(), [MANAGEMENT_TEAM_ID, FINANCE_TEAM_ID, BUSINESS_TEAM_ID]))) {

                if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
                    $ptFileQuery->where('pt_files.created_by', get_session_userid());
                }
            }

            $data['pt_files'] = $ptFileQuery->findAll();

            return $this->respond(['status' => true, 'message' => 'File uploaded successfully in G-Drive', 'data' => $data]);
        } else {
            return $this->respond(['status' => false, 'message' => 'Failed to upload file in G-Drive']);
        }
    }

    // update Invoice Status 
    public function updateInvoiceStatus()
    {
        $ids = $this->request->getPost('ids');
        $ids = json_decode($ids);

        // var_dump($ids); die;

        $data['invoice_status'] = $this->request->getPost('invoice_status');
        if ($this->request->getPost('invoice_status') == 'generated') {
            $data['invoice_no'] = $this->request->getPost('invoice_no');
        }


        $update = $this->policyTransactionModel
            ->whereIn('id', $ids)
            ->set($data)
            ->update();


        if ($update) {

            return $this->respond(['status' => true, 'data' => $ids, 'message' => 'Invoice status updated successfully'], 200);
        } else {
            return $this->respond(['status' => true, 'data' => $ids, 'message' => 'Failed to update invoice status'], 200);
        }
    }

    public function removeCoShareData($id)
    {
        $this->myLogger->logme('error', 'PT Co Share Detailes Remove function called');

        $data = [
            'updated_by' => get_session_userid(),
            'is_active' => 0
        ];

        $update = $this->PTCOShareDetailsModel->where('id', $id)->set($data)->update();

        if ($update) {
            return $this->respond(['status' => true, 'code' => 200, 'message' => 'Data removed successfully'], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove data'], 200);
        }
    }

    public function getPTCOShareCount($client_id, $client_policy_id)
    {
        $totalCount = $this->PTCOShareDetailsModel
            ->select("
                    pt_co_share_details.*,
                    policy_transaction.bro_payable_by,
                    policy_transaction.cd_ac_pk,
                    (
                        select cd_ac_no
                        from cd_master
                        where id = policy_transaction.cd_ac_pk
                    ) as cd_account_no,
                    (
                        select balance
                        from cash_deposit
                        where cd_ac_pk = policy_transaction.cd_ac_pk
                        and is_active = 1
                        order by id desc
                        limit 1
                    ) as cd_amount,
                ")
            ->join('policy_transaction', 'policy_transaction.id = pt_co_share_details.pt_id')
            ->where('policy_transaction.client_id', $client_id)
            ->where('policy_transaction.client_policy_id', $client_policy_id)
            ->where('policy_transaction.action_type', 'inception')
            ->findAll();

        $is_copay_yes = $this->policyTransactionModel
            ->where('client_id', $client_id)
            ->where('client_policy_id', $client_policy_id)
            ->where('action_type', 'inception')
            ->where('is_active', 1)
            ->first();

        $cd_ac_no = db_connect()->table('cd_master')->where('id', $is_copay_yes['cd_ac_pk'] ?? null)->get()->getRowArray();

        if ($totalCount) {
            return $this->respond(['status' => true, 'code' => 200, 'data' => $totalCount, 'is_copay_yes' => $is_copay_yes, "cd_master_data" => $cd_ac_no], 200);
        } else {
            $insurer_data = $this->clientPolicyModel->where('id', $client_policy_id)->where('is_active', 1)->first();
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to get data'], 200);
        }
    }

    public function checkInvoiceStatus($pt_id)
    {
        $data = $this->policyTransactionModel
            ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id')
            ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id')
            ->where('policy_transaction.id', $pt_id)
            ->where('policy_transaction.is_active', 1)
            ->where('pt_co_share_details.is_active', 1)
            ->where('pt_co_share_details.statement_id IS NOT NULL')
            ->where('insurer_statements.invoice_no IS NOT NULL')
            ->countAllResults();

        if ($data) {
            return $this->respond(['status' => true, 'count' => $data,  'code' => 200], 200);
        } else {
            return $this->respond(['status' => false, 'count' => 0, 'message' => 'No Data Found', 'code' => 404], 200);
        }
    }

    public function getBasePolicy($client_id, $client_branch_id)
    {
        $data = $this->clientPolicyModel
            ->select('client_policy.*, policy_type.policy_type')
            ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
            ->where('client_policy.client_id', $client_id)
            ->where('client_policy.client_branch_id', $client_branch_id)
            ->whereIn('client_policy.policy_type_id', [2, 3])
            ->where('client_policy.is_active', 1)
            ->findAll();

        if ($data) {
            return $this->respond(['status' => true, 'data' => $data,  'code' => 200], 200);
        } else {
            return $this->respond(['status' => false, 'count' => 0, 'message' => 'No Data Found', 'code' => 404], 200);
        }
    }

    //---------------------------------------------------------------------------------------------------

    //get BDS Reports data old function
    public function reportBDSOld()
    {

        $data['page_name'] = 'BDS Report';

        $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
        $data['client_type'] = [1 => 'Group', 2 => 'Individual'];
        $data['issuing_type'] = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over'];
        $data['policy_status'] = [
            'pending' => 'Pending',
            'exported_to_insurer' => 'Exported to Insurer',
            'imported_from_insurer' => 'Imported from Insurer',
            'exported_to_tpa' => 'Exported to TPA',
            'imported_from_tpa' => 'Imported from TPA',
            'completed' => 'Completed'
        ];
        $data['invoice_status_array'] = [
            'yet_to_generate' => 'Yet to Generate',
            'generated' => 'Generated',
            'send' => 'Send',
            'recived' => 'Recived',
        ];
        $data['date_type'] = [
            'policy_issue_date' => 'Policy Issue Date',
            'policy_start_date' => 'Policy Start Date',
            'policy_end_date' => 'Policy End Date',
            'data_received_date' => 'Data Received Date',
            'closure_date' => 'Closure Date',
        ];

        $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
        $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
        $data['clients'] = $this->clientModel->where('is_active', 1)->findAll();

        //filter datas
        $start_date = $this->request->getGet('start_date');
        $end_date = $this->request->getGet('end_date');
        $client_id = $this->request->getGet('client_id');
        $insurer_id = $this->request->getGet('insurer_id');
        $policy_type_id = $this->request->getGet('policy_type_id');
        $date_type = $this->request->getGet('date_type');
        $issuer = $this->request->getGet('issuer');

        $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
        $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;

        $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;


        //Actual data for the list
        $data['report_list'] = $this->policyTransactionModel->getBDSReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
        // dd($data);

        $this->loadLayout('report_bds_filter', $data);
    }

    //get BDS Reports data New Function
    public function reportBDS()
    {

        $data['page_name'] = 'BDS Report';

        $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
        $data['client_type'] = [1 => 'Group', 2 => 'Individual'];
        $data['issuing_type'] = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over'];
        $data['policy_status'] = [
            'pending' => 'Pending',
            'exported_to_insurer' => 'Exported to Insurer',
            'imported_from_insurer' => 'Imported from Insurer',
            'exported_to_tpa' => 'Exported to TPA',
            'imported_from_tpa' => 'Imported from TPA',
            'completed' => 'Completed'
        ];
        $data['invoice_status_array'] = [
            'yet_to_generate' => 'Yet to Generate',
            'generated' => 'Generated',
            'send' => 'Send',
            'recived' => 'Recived',
        ];
        $data['date_type'] = [
            'policy_issue_date' => 'Policy Issue Date',
            'policy_start_date' => 'Policy Start Date',
            'policy_end_date' => 'Policy End Date',
            'data_received_date' => 'Data Received Date',
            'closure_date' => 'Closure Date',
            'statement_month' => 'Statement Month',
        ];

        $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
        $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
        $data['clients'] = $this->clientModel->where('is_active', 1)->findAll();


        //filter datas
        $start_date = $this->request->getGet('start_date');
        $end_date = $this->request->getGet('end_date');
        $client_id = $this->request->getGet('client_id');
        $insurer_id = $this->request->getGet('insurer_id');
        $policy_type_id = $this->request->getGet('policy_type_id');
        $date_type = $this->request->getGet('date_type');
        $issuer = $this->request->getGet('issuer');
        $client_branch_id = $this->request->getGet('client_branch_id');
        $insurer_branch_id = $this->request->getGet('insurer_branch_id');
        $client_policy_id = $this->request->getGet('client_policy_id');

        if ($date_type == 'statement_month') {
            $start_date = (string)date('Y-m-01', strtotime($start_date));
            $end_date = (string)date('Y-m-31', strtotime($end_date));
        }

        // dd($start_date, $end_date, $date_type);

        $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
        $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;

        $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;
        $client_branch_id = (!isset($client_branch_id) || $client_branch_id === '' || $client_branch_id === null) ? 0 : $client_branch_id;
        $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id;
        $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id;
        if ($this->request->is('post')) {
            $isFromDashboard = $this->request->getPost("is_dashboard");

            if (isset($isFromDashboard) && !empty($isFromDashboard) && $isFromDashboard == 1) {
                $ids = $this->request->getPost('ids');
                
                $ids = array_filter(explode(',', $ids));

                if (!empty($ids)) {
                    $idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs to be integers
                    $where = "policy_transaction.id IN ($idsStr)";
                } else {
                    $where = []; // No valid IDs, return empty result
                }
            }
            // dd($ids);
        }
        //Actual data for the list
        $data['report_list'] = $this->policyTransactionModel->getBDSReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $client_branch_id, $insurer_branch_id, $client_policy_id, isset($where) ? $where : '');
        //!dd($data['report_list']);

        $this->loadLayout('report_bds_filter', $data);
    }

    public function reportVarience()
    {
        $data['page_name'] = 'Variance Report';

        $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
        $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
        $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
        $data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
        $data['date_type'] = [
            'policy_issue_date' => 'Policy Issue Date',
            'policy_start_date' => 'Policy Start Date',
            'policy_end_date' => 'Policy End Date',
            'data_received_date' => 'Data Received Date',
            'closure_date' => 'Closure Date',
        ];

        //filter datas
        $start_date = $this->request->getGet('start_date');
        $end_date = $this->request->getGet('end_date');
        $client_id = $this->request->getGet('client_id');
        $insurer_id = $this->request->getGet('insurer_id');
        $policy_type_id = $this->request->getGet('policy_type_id');
        $date_type = $this->request->getGet('date_type');
        $issuer = $this->request->getGet('issuer');
        $client_branch_id = $this->request->getGet('client_branch_id');
        $insurer_branch_id = $this->request->getGet('insurer_branch_id');
        $client_policy_id = $this->request->getGet('client_policy_id');


        $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
        $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;

        $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;

        $client_branch_id = (!isset($client_branch_id) || $client_branch_id === '' || $client_branch_id === null) ? 0 : $client_branch_id;
        $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id;
        $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id;


        $data['varience_list'] = $this->policyTransactionModel->getVarienceReportLIst($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $client_branch_id, $insurer_branch_id, $client_policy_id);
        // !dd($data['varience_list']);
        $this->loadLayout('variance_report_list', $data);
    }


    public function reportBusinessList()
    {
        $data['page_name'] = 'Business Report';

        $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
        $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
        $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
        $data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
        $data['date_type'] = [
            'policy_issue_date' => 'Policy Issue Date',
            'policy_start_date' => 'Policy Start Date',
            'policy_end_date' => 'Policy End Date',
            'data_received_date' => 'Data Received Date',
            'closure_date' => 'Closure Date',
        ];

        //filter datas
        $start_date = $this->request->getGet('start_date');
        $end_date = $this->request->getGet('end_date');
        $client_id = $this->request->getGet('client_id');
        $insurer_id = $this->request->getGet('insurer_id');
        $policy_type_id = $this->request->getGet('policy_type_id');
        $date_type = $this->request->getGet('date_type');
        $issuer = $this->request->getGet('issuer');

        $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
        $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;

        $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;


        $data['business_list'] = $this->policyTransactionModel->getBusinessReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
        $this->loadLayout('business_team_list', $data);
    }


    public function reportFinanceList()
    {
        $data['page_name'] = 'Finance Report';

        $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
        $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
        $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
        $data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
        $data['date_type'] = [
            'policy_issue_date' => 'Policy Issue Date',
            'policy_start_date' => 'Policy Start Date',
            'policy_end_date' => 'Policy End Date',
            'data_received_date' => 'Data Received Date',
            'closure_date' => 'Closure Date',
        ];

        //filter datas
        $start_date = $this->request->getGet('start_date');
        $end_date = $this->request->getGet('end_date');
        $client_id = $this->request->getGet('client_id');
        $insurer_id = $this->request->getGet('insurer_id');
        $policy_type_id = $this->request->getGet('policy_type_id');
        $date_type = $this->request->getGet('date_type');
        $issuer = $this->request->getGet('issuer');

        $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
        $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;

        $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;
        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;
        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;



        $data['finance_list'] = $this->policyTransactionModel->getFinanceReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
        $this->loadLayout('finance_team_list', $data);
    }

    public function reportOutstanding()
    {
        $data['page_name'] = 'Outstanding Report';

        $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
        $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
        $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
        $data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
        $data['date_type'] = [
            'policy_issue_date' => 'Policy Issue Date',
            'policy_start_date' => 'Policy Start Date',
            'policy_end_date' => 'Policy End Date',
            'data_received_date' => 'Data Received Date',
            'closure_date' => 'Closure Date',
        ];

        //filter datas
        $start_date = $this->request->getGet('start_date');
        $end_date = $this->request->getGet('end_date');
        $client_id = $this->request->getGet('client_id');
        $insurer_id = $this->request->getGet('insurer_id');
        $insurer_branch_id = $this->request->getGet('insurer_branch_id');

        $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : change_date_format($start_date, 'd-m-Y', 'Y-m-01');
        $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : change_date_format($end_date, 'd-m-Y', 'Y-m-31');
        // dd([$start_date,$end_date]);


        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
        $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id;

        $data['outstanting_list'] = $this->policyTransactionModel->getOutstandingReportLIst($start_date, $end_date, $insurer_id, $insurer_branch_id);
        // dd($this->policyTransactionModel->getLastQuery());
        // dd($data);
        $this->loadLayout('outstanding_report_list', $data);
    }

    //---------------------------------------------------------------------------------------------------

    //insurer statement list page
    public function statementList()
    {
        // dd($this->validateInsurerStatement(['file_id' => 30]));
        // $data['insurers'] = $this->insurerModel->where('is_active',1)->findAll();
        $today = date('Y-m-d');
        $fromday = $from_date = date('Y-m-d', strtotime('-180 days', strtotime($today)));
        // echo $fromday;die();
        $data['invoice_status_array'] = $this->invoiceStatus;
        $data['insurers'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();

        // dd( $data['insurers']);
        $data['insurer_statement_list'] = $this->insurerStatements
            ->select(
                'insurer_statements.*, 
                                                          insurers.name AS insurer_name, 
                                                          insurers.short_name, 
                                                          user_profiles.first_name, 
                                                          insurer_branch.branch_code,
                                                          (SELECT SUM(pt_co_share_details.exp_amt) 
                                                           FROM pt_co_share_details 
                                                           WHERE pt_co_share_details.is_active = 1 
                                                             AND pt_co_share_details.statement_id = insurer_statements.id
                                                          ) AS exp_inv_amt,
                                                          (SELECT SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds)  + SUM(inv_payment_details.gst)
                                                           FROM inv_payment_details 
                                                           WHERE inv_payment_details.is_active = 1 
                                                             AND inv_payment_details.statement_id = insurer_statements.id
                                                          ) AS received_inv_amt'
            )
            ->join('insurers', 'insurer_statements.insurer_id = insurers.id')
            ->join('insurer_branch', 'insurer_statements.branch_id = insurer_branch.id')
            ->join('user_profiles', 'insurer_statements.created_by = user_profiles.id')
            ->where('insurer_statements.is_active', 1)
            // ->where('insurer_statements.file_status','success')
            ->where('date(insurer_statements.created_at) >= ', $from_date)
            ->where('date(insurer_statements.created_at) <= ', $today)
            ->orderBy('insurer_statements.id', 'DESC')
            ->findAll();

        // dd( $this->insurerStatements->getLastQuery());
        $data['page_name'] = 'Statement Upload';

        $this->loadLayout('insurer_statement_list',  $data);
    }

    // public function failedStatementList(){
    //     $today = date('Y-m-d');
    //     $fromday = $from_date = date('Y-m-d', strtotime('-180 days', strtotime($today)));
    //     // echo $fromday;die();
    //      $data['invoice_status_array'] = $this->invoiceStatus;
    //      $data['insurers'] = $this->insurerBranchModel ->getInsurerBranchesWithInsurerNames();

    //      // dd( $data['insurers']);
    //      $data['insurer_statement_list'] = $this->insurerStatements
    //                                             ->select('insurer_statements.*, 
    //                                                       insurers.name AS insurer_name, 
    //                                                       insurers.short_name, 
    //                                                       user_profiles.first_name, 
    //                                                       insurer_branch.branch_code,
    //                                                       (SELECT SUM(pt_co_share_details.exp_amt) 
    //                                                        FROM pt_co_share_details 
    //                                                        WHERE pt_co_share_details.is_active = 1 
    //                                                          AND pt_co_share_details.statement_id = insurer_statements.id
    //                                                       ) AS exp_inv_amt,
    //                                                       (SELECT SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds)  + SUM(inv_payment_details.gst)
    //                                                        FROM inv_payment_details 
    //                                                        WHERE inv_payment_details.is_active = 1 
    //                                                          AND inv_payment_details.statement_id = insurer_statements.id
    //                                                       ) AS received_inv_amt'
    //                                             )
    //                                             ->join('insurers', 'insurer_statements.insurer_id = insurers.id')
    //                                             ->join('insurer_branch', 'insurer_statements.branch_id = insurer_branch.id')
    //                                             ->join('user_profiles', 'insurer_statements.created_by = user_profiles.id')
    //                                             ->where('insurer_statements.is_active', 1)
    //                                             ->where('insurer_statements.file_status','failed')
    //                                             ->where('date(insurer_statements.created_at) >= ', $from_date)
    //                                             ->where('date(insurer_statements.created_at) <= ', $today)
    //                                             ->orderBy('insurer_statements.id', 'DESC')
    //                                             ->findAll();
    //         if($data['insurer_statement_list']){
    //             return $this->respond(['status' => true, 'code' => 200,'data'=>$data ], 200);
    //         }else{
    //             return $this->respond(['status'=>false,'message'=>'Data Not Fount'],404);
    //         }

    // }

    public function uploadInsurerStatement()
    {

        //validate uploaded file
        $filename = '';
        $validated = $this->validate([
            'statement' => [
                'uploaded[statement]',
                'mime_in[statement,application/vnd.ms-excel,application/vnd,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.spreadsheet]',
                'max_size[statement,16384]',
            ],
        ]);
        // $this->createStatementFolder();
        if ($validated) {
            $avatar = $this->request->getFile('statement');
            if (!$avatar) {
                $this->myLogger->logme("error", 'Statement File not found');
                return $this->respond(['dataStatus' => false, 'code' => 400, 'message' => 'File not found'], 400);
            }

            $is_moved = $avatar->move(WRITEPATH . 'uploads/statements/');
            if ($is_moved) {
                $filename = $avatar->getName();
                // Handle successful upload, e.g., log success or further processing
                $this->myLogger->logme("error", 'Statement File moved successful');
            } else {
                $this->myLogger->logme("error", 'Statement File move failed');
                return $this->respond(['dataStatus' => false, 'code' => 500, 'message' => 'File move failed'], 500);
            }
        } else {
            $this->myLogger->logme("error", 'Statement Upload failed Invalid file');
            return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'Invalid file'], 404);
        }

        //process post variable entry in file table
        $loggedInUserID = get_session_userid();
        // dd($loggedInUserID);
        // $loggedInUserID = 8;

        $insurer = $this->request->getPost('insurer');

        $insurer_id = explode('-', $insurer)[0];
        $branch_id = explode('-', $insurer)[1];
        // print_r($insurer_id);
        // print_r($branch_id);
        // die();
        $month = $this->request->getPost('statement_month');
        $month = $month . '-01';
        // print_r($month);die;
        $month = change_date_format($month, 'Y-M-d', 'Y-m-d');
        $stmt_sno = $this->request->getPost('statement_no');
        // print_r($month);die;

        $file_id = $this->insurerStatements->insert(['insurer_id' => $insurer_id, 'branch_id' => $branch_id, 'file_name' => $filename, 'month' => $month, 'created_by' => $loggedInUserID, 'stmt_sno' => $stmt_sno]); //here field policy_id have client_policy_id and not policy id from policy master
        $this->myLogger->logme("error", '{file_id} statement uploaded success', ['file_id' => $file_id]);

        //validate file
        $validation_result = $this->validateInsurerStatement(['file_id' => $file_id]);
        //update file content to DB
        if ($validation_result['status']) {
            $this->updateInsurerStatement(['file_id' => $file_id]);
        }

        if (!isset($file_id) || !$validation_result['status']) {
            return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file not uploaded', 'error_data' => $validation_result['error_data'], 'error_code' =>   $validation_result['error_code']], 200);
        }

        if (isset($file_id) || $validation_result['status']) {
            $this->insurerStatements->where('id', $file_id)->set(['invoice_status' => 'pending'])->update();
        }



        return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'file upload success'], 200);
    }

    public function createStatementFolder()
    {
        $folderPath = WRITEPATH . 'uploads/statements/';

        // Check if the folder doesn't exist
        if (!file_exists($folderPath)) {
            // Create the folder
            if (mkdir($folderPath, 0777, true)) {
                $this->myLogger->logme('error', 'statement upload folder created successfully');

                // Set permissions to a+rwx (read, write, execute for all)
                chmod($folderPath, 0777);
                $this->myLogger->logme('error', 'Permissions set to a+rwx.');
            } else {
                // echo "Failed to create folder.";
                $this->myLogger->logme('error', 'Failed to create statement upload folder.');
            }
        } else {
            $this->myLogger->logme('error', 'upload folder exists.');
        }
    }

    public function validateInsurerStatement($params)
    {
        helper('excel_util_helper');
        //get file info
        $file_id = $params['file_id'];
        $file = $this->insurerStatements->find($file_id);
        // dd($file);
        $date = new \DateTime($file['month']);

        $month = $date->format('m');
        $year = $date->format('Y');

        $error_data = ['error_code' => '', 'error_data' => []];
        $status = 'success';
        $ret_status = true;
        // dd($month.'-'.$year);
        $return = [];
        if (!isset($file)) {
            //file not found in DB
            return array('status' => false, 'msg' => 'statement file not found in DB');
        }
        $file_name_with_path = WRITEPATH . "/uploads/statements/" . $file['file_name'];

        //check physical file
        if (!file_exists($file_name_with_path)) {
            //file not found  update status and reason 
            $message = "Physcial file not found";
            // echo $message;
            $this->myLogger->logme('error', ($message . ' for statement file id ' . $file_id));
            $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed', 'reason' => json_encode(['error_code' => 0, 'error_data' => $message])])->update();
            return  array('status' => false, 'error_code' => 0); //0 - Physcial file not found
        }

        //get excel data to php array
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
        $sheet = $spreadsheet->getActiveSheet();

        $highestRowAndColumn = $sheet->getHighestRowAndColumn();
        // dd($highestRowAndColumn);
        $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
        unset($excel_data[0]);
        // Kint::dump($excel_data);
        //get no of line items and update in DB
        $line_items = 0;
        // get uploaded month transactions data
        $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(insurer_id: $file['insurer_id'], insurer_branch_id: $file['branch_id']);
        // var_dump($source_data);die();
        // Kint::dump($source_data);//die();


        // check policy no,insurer and etc in DB for this month
        // if all good return true, otherwise return false with messssage 
        foreach ($excel_data as $excel_key => $excel_row) {
            $is_row_empty = check_row_is_empty_or_null($excel_row);
            if (!$is_row_empty) {
                // $excel_row = ExcelSanitizeHelper::sanitizeArrayData($excel_row);
                $is_source_found = 0;
                $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]); //policy_start_date from excel
                $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]); //policy_end_date from excel
                $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]); //policy_end_date from excel
                $policy_no = preg_replace('/[\x{200C}\x{200B}]/u', '',  $excel_row[1]); //policy_end_date from excel
                $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]); //clientname from excel
                $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]); //policy_end_date from excel
                // Kint::dump($policy_no);
                foreach ($source_data as $source_key => $source_row) {
                    $source_endorsement_no = $source_row['endorsement_no'] !== null ? $source_row['endorsement_no'] : null;
                    // Kint::dump($source_endorsement_no);
                    if (($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no  && change_date_format($policy_start_date, 'd-m-Y', 'Y-m-d') == $source_row['policy_start_date'] &&  change_date_format($policy_end_date, 'd-m-Y', 'Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name']) {
                        $is_source_found = 1;
                        $line_items = $line_items + 1;
                        unset($source_data[$source_key]);
                        continue 2;
                    }
                }

                if ($is_source_found == 0) {
                    // echo $excel_key.'-'.$excel_row[1] . '- not found
'; $error_data['error_code'] = 1; //match not found // $error_data['error_data'] = ($error_data['error_data'] ?? []); $error_data['error_data'] = array_merge($error_data['error_data'], [$excel_row[0]]); //match not found } } } // dd($error_data); if ($error_data['error_code']) { $status = 'failed'; $ret_status = false; } //update in DB $this->insurerStatements->where('id', $file_id)->set(['line_items' => $line_items, 'file_status' => $status, 'reason' => json_encode($error_data)])->update(); return array('status' => $ret_status, 'error_code' => $error_data['error_code'], 'error_data' => $error_data['error_data']); } public function updateInsurerStatement($params) { helper('excel_util_helper'); //get file info $file_id = $params['file_id']; $file = $this->insurerStatements->find($file_id); // dd($file); $date = new \DateTime($file['month']); $month = $date->format('m'); $year = $date->format('Y'); $error_data = ['error_code' => '', 'error_data' => []]; $status = 'success'; $ret_status = true; // dd($month.'-'.$year); $return = []; if (!isset($file)) { //file not found in DB return array('status' => false, 'msg' => 'statement file not found in DB'); } $file_name_with_path = WRITEPATH . "/uploads/statements/" . $file['file_name']; //check physical file if (!file_exists($file_name_with_path)) { //file not found update status and reason $message = "Physcial file not found"; // echo $message; $this->myLogger->logme('error', ($message . ' for statement file id ' . $file_id)); $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed', 'reason' => json_encode(['error_code' => 0, 'error_data' => $message])])->update(); return array('status' => false, 'error_code' => 0); //0 - Physcial file not found } //get excel data to php array $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); $sheet = $spreadsheet->getActiveSheet(); $highestRowAndColumn = $sheet->getHighestRowAndColumn(); // dd($highestRowAndColumn); $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); unset($excel_data[0]); // dd($excel_data); //get no of line items and update in DB $line_items = count($excel_data); // get uploaded month transactions data $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(insurer_id: $file['insurer_id'], insurer_branch_id: $file['branch_id']); // Kint::dump($source_data);//die; // Kint::dump($excel_data); // die; // check policy no,insurer and etc in DB for this month // if all good return true, otherwise return false with messssage $data_to_update = []; foreach ($excel_data as $excel_key => $excel_row) { $is_row_empty = check_row_is_empty_or_null($excel_row); if (!$is_row_empty) { $is_source_found = 0; $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]); //policy_start_date from excel $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]); //policy_end_date from excel $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]); //policy_end_date from excel $policy_no = preg_replace('/[\x{200C}\x{200B}]/u', '', $excel_row[1]); // $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]); //clientname from excel $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]); //policy_end_date from excel foreach ($source_data as $source_key => $source_row) { // Kint::dump(change_date_format($excel_row[3],'d-m-Y','Y-m-d')); $source_endorsement_no = $source_row['endorsement_no'] !== null ? $source_row['endorsement_no'] : null; if (($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no && change_date_format($policy_start_date, 'd-m-Y', 'Y-m-d') == $source_row['policy_start_date'] && change_date_format($policy_end_date, 'd-m-Y', 'Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name']) { $is_source_found = 1; //calculate percentage first $total_amt = 0; $actual_bp_per = trim($excel_row[9]); $actual_bp_brokerage = trim($excel_row[12]); $actual_bp_amt = trim($excel_row[6]); if (($actual_bp_brokerage && $actual_bp_brokerage != 0 && $actual_bp_brokerage != "")) { $total_amt += $actual_bp_brokerage; //percentage reverse calculation if ($actual_bp_per == 0 || $actual_bp_per == "") { $actual_bp_per = round(($actual_bp_brokerage / $actual_bp_amt) * 100, 2); } } else { $actual_bp_brokerage = $actual_bp_amt * ($actual_bp_per / 100); $total_amt += $actual_bp_brokerage; } $actual_tp_per = trim($excel_row[10]); $actual_tp_brokerage = trim($excel_row[13]); $actual_tp_amt = trim($excel_row[7]); if ($actual_tp_brokerage && $actual_tp_brokerage != 0 && $actual_tp_brokerage != "") { $total_amt += $actual_tp_brokerage; //percentage reverse calculation if ($actual_tp_per == 0 || $actual_tp_per == "") { $actual_tp_per = ($actual_tp_brokerage / $actual_tp_amt) * 100; } } else { $actual_tp_brokerage = $actual_tp_amt * ($actual_tp_per / 100); $total_amt += $actual_tp_brokerage; } $actual_tep_per = trim($excel_row[11]); $actual_tep_brokerage = trim($excel_row[14]); $actual_tep_amt = trim($excel_row[8]); if ($actual_tep_brokerage && $actual_tep_brokerage != 0 && $actual_tep_brokerage != "") { $total_amt += $actual_tep_brokerage; //percentage reverse calculation if ($actual_tep_per == 0 || $actual_tep_per == "") { $actual_tep_per = ($actual_tep_brokerage / $actual_tep_amt) * 100; } } else { $actual_tep_brokerage = $actual_tep_amt * ($actual_tep_per / 100); $total_amt += $actual_tep_brokerage; } //find variance $variance_amt = $source_row['exp_amt'] - $total_amt; $data_to_update[] = ['co_share_id' => $source_row['id'], 'actual_bp_amt' => $actual_bp_amt, 'actual_tp_amt' => $actual_tp_amt, 'actual_tep_amt' => $actual_tep_amt, 'actual_bp_per' => $actual_bp_per, 'actual_tp_per' => $actual_tp_per, 'actual_tep_per' => $actual_tep_per, 'variance' => $variance_amt, 'actual_tep_brokerage_amt' => $actual_tep_brokerage, 'actual_tp_brokerage_amt' => $actual_tp_brokerage, 'actual_bp_brokerage_amt' => $actual_bp_brokerage, 'reward' => trim($excel_row[15]), 'statement_id' => $file_id]; unset($source_data[$source_key]); continue 2; } } } } // dd($data_to_update); $this->coShareStmtDetailsModel->insertBatch($data_to_update, 'id'); // dd($data_to_update); // if($error_data['error_code']) // { // $status = 'failed'; // $ret_status = false; // } //update in DB $this->insurerStatements->where('id', $file_id)->set(['file_status' => $status, 'reason' => json_encode($error_data), 'invoice_status' => 'pending'])->update(); return array('status' => $ret_status, 'error_code' => $error_data['error_code'], 'error_data' => $error_data['error_data']); } public function getInvoicePaymentDetails() { $statement_id = $this->request->getUri()->getSegment(4); $inv_details = $this->insurerStatements->find($statement_id); $inv_payment_details = $this->invPaymentDetailsModel ->where('statement_id', $statement_id) ->where('is_active', 1) ->get() ->getResultArray(); if (!$inv_details['invoice_value']) { $stmt_level_value = $this->coShareStmtDetailsModel->select('sum(actual_tep_brokerage_amt) + sum(actual_tp_brokerage_amt) + sum(actual_bp_brokerage_amt) + sum(reward) as invoice_value') ->where('statement_id', $statement_id) ->groupBy('statement_id') ->get() ->getResultArray(); // print_r($stmt_level_value); if ($stmt_level_value && count($stmt_level_value) && isset($stmt_level_value[0])) { $inv_details['invoice_value'] = $stmt_level_value[0]['invoice_value']; } } // ~dd($inv_details); $data = [ 'invoice_status' => $inv_details['invoice_status'], 'gst_per' => isset($inv_details['gst_per']) ? $inv_details['gst_per'] : 18, 'invoice_value' => $inv_details['invoice_value'], 'gst_value' => $inv_details['gst_value'], 'invoice_no' => $inv_details['invoice_no'], 'invoice_amount' => $inv_details['invoice_amount'], 'invoice_date' => isset($inv_details['invoice_date']) ? change_date_format($inv_details['invoice_date'], 'Y-m-d', 'd/m/Y') : null ]; $data['payments'] = $inv_payment_details; return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $data], 200); } public function saveInvoicePaymentDetails() { $jsonData = $this->request->getJSON(); $jsonData = (array)$jsonData; // echo 'Hi'; // print_r($jsonData);die(); $invoiceStatus = $jsonData['invoice_status']; $hiddenStatementId = $jsonData['hidden_statement_id']; $invoiceNo = $jsonData['invoice_no']; $invoiceDate = change_date_format($jsonData['invoice_date'], 'd/m/Y', 'Y-m-d'); $invoice_amount = $jsonData['invoice_amount']; $invoice_value = $jsonData['invoice_value']; $gst_per = $jsonData['invoice_gst_per']; $gst_value = $jsonData['invoice_gst']; //Update statement table $parentData = [ 'invoice_status' => $invoiceStatus, 'invoice_no' => $invoiceNo, 'invoice_date' => $invoiceDate, 'invoice_amount' => $invoice_amount, 'gst_per' => $gst_per, 'gst_value' => $gst_value, 'invoice_value' => $invoice_value, 'updated_by' => get_session_userid() ]; $this->insurerStatements->update($hiddenStatementId, $parentData); // Process child data $receivedAmounts = $jsonData['received_amount']; $utrNos = $jsonData['utr_no']; $tdsTotal = $jsonData['tds']; $gstTotal = $jsonData['gst_amount']; $paymentDates = $jsonData['payment_date']; $pks = $jsonData['pk']; foreach ($receivedAmounts as $index => $receivedAmount) { $pk = $pks[$index]; // Get the pk for the current record $utrNo = $utrNos[$index]; $tds = $tdsTotal[$index]; $gst = $gstTotal[$index]; $paymentDate = $paymentDates[$index]; // Prepare data for insert/update $childData = [ 'inv_amt' => $receivedAmount, 'utr_no' => $utrNo, 'tds' => $tds, 'gst' => $gst, 'received_date' => change_date_format($paymentDate, 'd/m/Y', 'Y-m-d'), 'statement_id' => $hiddenStatementId ]; if ($pk) { $childData['updated_by'] = get_session_userid(); $childData['id'] = (int)$pk; } else { $childData['created_by'] = get_session_userid(); } // print_r($childData); // Insert or update $this->invPaymentDetailsModel->save($childData); // print_r($this->invPaymentDetailsModel->errors()); } return $this->respond(['dataStatus' => true, 'code' => 200], 200); //return $this->response->setJSON(['dataStatus' => 'true']); } public function deletePaymentEntry() { $payment_id = $this->request->getUri()->getSegment(4); //echo $payment_id; $this->invPaymentDetailsModel->update($payment_id, ['is_active' => 0]); return $this->respond(['dataStatus' => true, 'code' => 200], 200); } public function downloadSampleInsurerStatement() { $filePath = ROOTPATH . 'public/sample_excel/insurer_stament_sample.xlsx'; // Check if the file exists if (file_exists($filePath)) { // Set the appropriate MIME type $mimeType = mime_content_type($filePath); // Send the file to the client for download return $this->response->download($filePath, null, $mimeType); } else { // File not found, show an error message or redirect echo view('errors/html/production'); } } public function getFileErr() { $file_id = $this->request->getUri()->getSegment(4); $file = $this->insurerStatements->find($file_id); return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $file['reason']], 200); } public function dmsSearch() { // echo 'scbsc';die(); if ($this->request->getMethod() == 'post') { // $jsonData = (array)$this->request->getJSON(); $customer_id = $this->request->getPost('customer_id'); $policy_id = $this->request->getPost('policy_id'); $cus_doc_name = $this->request->getPost('cus_doc_name'); $policy_doc_name = $this->request->getPost('policy_doc_name'); $pt_files = []; $kyc_files = []; $batch_files = []; $files = []; // print_r($jsonData);die(); if ($policy_id != "") { //get policy docs from policy transation related tables $pt_files = $this->PTFileModel->getPolicyDriveFilesIndex($policy_id, $policy_doc_name); $batch_files = $this->batchFileModel->getBatchFilesDataForDocumentSearch($policy_id, $policy_doc_name); $files = $this->filesModel->getFilesDataForDocumentSearch($policy_id, $policy_doc_name); // dd($files); // dd($this->PTFileModel->getLastQuery()); // ~dd($pt_files); } if ($customer_id != "") { $kyc_files = $this->clientKYCDocsModel->getClientKYCDriveFilesIndex($customer_id, $cus_doc_name); // dd($this->clientKYCDocsModel->getLastQuery()); // !dd($kyc_files); } $data['files'] = array_merge($pt_files, $kyc_files, $batch_files, $files); // dd($data['files']); } $data['page_name'] = 'Documents Search'; $data['customers'] = $this->clientModel->select('id,client_name,short_name as display_value')->where('is_active', 1)->get()->getResultarray(); $data['policies'] = $this->clientPolicyModel->select("client_policy.id,client_policy.policy_no,policy_type.policy_type,concat(policy_type.policy_type,' - ',client_policy.policy_no) as display_value") ->join('policy_type', 'client_policy.policy_type_id = policy_type.id') ->where('client_policy.is_active', 1)->get()->getResultarray(); // dd($data); $this->loadLayout('dms_search', $data); } //--------------------------------------------------------------------------------------------------- public function getCoShareStatementDetails($pt_id) { if (!$pt_id) { return $this->respond([ 'status' => false, 'code' => 400, 'message' => 'No data found' ], 200); } // Fetch data from the database $data = db_connect()->table("co_share_stmt_details") ->select(" co_share_stmt_details.*, insurer_statements.month, insurer_statements.invoice_status, insurer_statements.invoice_date, insurer_statements.invoice_no, insurer_statements.invoice_amount, insurer_statements.stmt_sno, (co_share_stmt_details.actual_bp_amt + co_share_stmt_details.actual_tp_amt + co_share_stmt_details.actual_tep_amt) AS sum_of_actual_amt ") ->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id') ->where([ 'co_share_stmt_details.is_active' => 1, 'insurer_statements.is_active' => 1, 'co_share_stmt_details.co_share_id' => $pt_id ]) ->get() ->getResultArray(); // Check if data exists before formatting if ($data) { foreach ($data as &$row) { // Check if invoice_date is not null before formatting $row['invoice_date'] = $row['invoice_date'] ? change_date_format($row['invoice_date'], 'Y-m-d', 'd/m/Y') : null; // Check if month is not null before formatting $row['month'] = $row['month'] ? change_date_format($row['month'], 'Y-m-d', 'M-Y') : null; } return $this->respond([ 'status' => true, 'code' => 200, 'data' => $data ], 200); } else { return $this->respond([ 'status' => false, 'code' => 400, 'message' => 'No data found' ], 200); } } public function getClientPolicyDataBasedOnClientAndInsuer() { $client_id = $this->request->getGet('client_id') ?? 0; $client_branch_id = $this->request->getGet('client_branch_id') ?? 0; $insurer_id = $this->request->getGet('insurer_id') ?? 0; $insurer_branch_id = $this->request->getGet('insurer_branch_id') ?? 0; $policy_type_id = $this->request->getGet('policy_type_id') ?? 0; $builder = db_connect()->table("client_policy") ->select(" client_policy.*, policy_type.policy_type, ") ->join('policy_type', 'client_policy.policy_type_id = policy_type.id') ->where([ 'client_policy.is_active' => 1, ]); if (!empty($client_id)) { $builder->where('client_policy.client_id', $client_id); } if (!empty($client_branch_id)) { $builder->where('client_policy.client_branch_id', $client_branch_id); } if (!empty($insurer_id)) { $builder->where('client_policy.insurer_id', $insurer_id); } if (!empty($insurer_branch_id)) { $builder->where('client_policy.insurer_branch_id', $insurer_branch_id); } if (!empty($policy_type_id)) { $builder->where('client_policy.policy_type_id', $policy_type_id); } $result = $builder->get()->getResultArray(); if ($result) { return $this->respond(['status' => true, 'code' => 200, 'data' => $result, 'getData' => $this->request->getGet()], 200); } else { return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found'], 200); } } public function checkCDAmountForBasePremium() { $base_premium = $this->request->getGet('base_premium') ?? 0; $cd_ac_no = $this->request->getGet('cd_ac_no') ?? 0; // Validate inputs if (empty($cd_ac_no)) { return $this->respond(['status' => false, 'code' => 400, 'message' => 'CD Account Number is required'], 200); } // Build query $db = db_connect(); $builder = $db->table("cash_deposit") ->where('cd_ac_pk', $cd_ac_no) ->where('is_active', 1) ->orderBy('id', 'desc') ->limit(1); $result = $builder->get()->getRowArray(); if ($result) { // Check if base premium exceeds balance $base_premium_greater_than_balance = $base_premium > $result['balance']; return $this->respond([ 'status' => true, 'code' => 200, 'data' => $result, 'base_premium' => $base_premium, 'cd_ac_no' => $cd_ac_no, 'base_premium_greater_than_balance' => $base_premium_greater_than_balance, ], 200); } return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found for this CD'], 200); } public function getInsurerStatementMonth() { $insurer_id = $this->request->getGet('insurer_id'); $month = $this->request->getGet('month'); // echo $month; $insurer_branch_id = explode('-', $insurer_id)[1]; $insurer_id = explode('-', $insurer_id)[0]; $month = $month . '-01'; $month = change_date_format($month, 'Y-M-d', 'Y-m-d'); // echo $month; $res_data = $this->insurerStatements ->where('insurer_id', $insurer_id) ->where('branch_id', $insurer_branch_id) ->where('month', $month) ->where('is_active', 1) ->where('file_status', 'success') ->findAll(); return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $res_data], 200); } public function deleteStatement($id) { // echo $id;die(); $this->coShareStmtDetailsModel->where('statement_id', $id) ->set(['is_active' => 0]) ->update(); $this->invPaymentDetailsModel->where('statement_id', $id) ->set(['is_active' => 0]) ->update(); $this->insurerStatements->where('id', $id) ->set(['is_active' => 0]) ->update(); return $this->respond(['dataStatus' => true, 'code' => 200], 200); } }