diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 877ba46e..a7e41f8f 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -48,6 +48,7 @@ $routes->get("frontend_content", "AppContentManagementController::frontend_conte $routes->get('/test', 'Home::index'); $routes->get('/check_gemini', 'Home::check_Gemini'); $routes->get('/check_gemini2', 'Home::check_gemini_2'); +$routes->get('/checkPolicyDoc', 'Home::checkPolicyDoc'); $routes->get('/login', 'LoginController::index'); ///auth/google $routes->get('/loginPos', 'LoginController::loginPos'); //login POS team $routes->post('/getVerifyPosMobileNo', 'LoginController::getVerifyPosMobileNo'); //Verify POS team mobile no @@ -427,6 +428,7 @@ $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) { $routes->group("report", ["filter" => "authMVC"], function ($routes) { $routes->match(['get', 'post'],"list", "PolicyTransactionController::reportBDS"); + $routes->match(['get', 'post'],"listNew", "PolicyTransactionController::reportBDSNew"); $routes->get("report-varience-list", "PolicyTransactionController::reportVarience"); $routes->get("report-business-list", "PolicyTransactionController::reportBusinessList"); $routes->get("report-finance-list", "PolicyTransactionController::reportFinanceList"); diff --git a/app/Controllers/Home.php b/app/Controllers/Home.php index 68eb0402..84d0d8c9 100755 --- a/app/Controllers/Home.php +++ b/app/Controllers/Home.php @@ -60,6 +60,8 @@ class Home extends PublicController //print_rr($data); } + + //for insurer statement upload public function check_gemini_2() { @@ -158,6 +160,143 @@ class Home extends PublicController + // The final JSON payload + $data = [ + "contents" => [ + $content_parts + ] + ]; + + // Encode the data to a JSON string + $json_data = json_encode($data); + + // Initialize cURL + $ch = curl_init($url); + + // Set cURL options + curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // Set the Content-Type header + curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data); // Set the JSON payload + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Optional: to bypass SSL verification if needed (not recommended for production) + + // Execute the cURL request and get the response + $response = curl_exec($ch); + + // Check for cURL errors + if (curl_errno($ch)) { + echo 'cURL Error: ' . curl_error($ch); + } + + // Close the cURL handle + curl_close($ch); + + // Decode the JSON response + $responseData = json_decode($response, true); + echo '
';
+                print_r($responseData);
+            echo '
';
+            // Check if the response contains generated text
+            if (isset($responseData['candidates'][0]['content']['parts'][0]['text'])) {
+                $generatedText = $responseData['candidates'][0]['content']['parts'][0]['text'];
+                echo "Generated Text: " . $generatedText;
+            } else {
+                echo "Error or no text generated. Response: " . $response;
+            }
+
+    }
+
+
+    //for insurer policy doc upload
+    public function checkPolicyDoc()
+    {
+
+            // $this->convertToPdf();die();
+            // Replace with your actual Gemini API key
+           $apiKey = 'AIzaSyBbx-uotRBqkYhqLpmD60420E_a0G0duP8';
+
+            // The model to use and the API endpoint
+            $model = "gemini-pro";
+            $model = "gemini-2.5-flash";
+            // $model = "gemini-1.5-pro";
+            // $model = "gemini-1.5-pro";
+            $url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$apiKey}";
+
+            $filePath = 'C:\Users\Venba\AppData\Local\Programs\Python\pyenv\pdfreader\bike-0904023124P114268957.pdf';
+            $filePath = 'C:\Users\Venba\AppData\Local\Programs\Python\pyenv\pdfreader\car-insurance-0904023124P114213011.pdf';
+
+            // Check if the file exists
+            if (!file_exists($filePath)) {
+                die("Error: File not found at {$filePath}");
+            }
+
+            // Get the file's MIME type using the finfo extension
+            $finfo = finfo_open(FILEINFO_MIME_TYPE);
+            $mimeType = finfo_file($finfo, $filePath);
+            finfo_close($finfo);
+            // print_r($mimeType);die();
+             // Define supported inline MIME types
+             $supportedInlineMimeTypes = ['application/pdf','text/csv'];
+
+            // Read the file content and encode it to Base64
+            $fileContent = file_get_contents($filePath);
+            $base64Content = base64_encode($fileContent);
+            // The prompt you want to send to the model
+            // $prompt = "give me a json with emp data like name,age,dob,mobile and email. only json not any explanations";
+            $prompt = "Read the following motor policy pdf document and convert into JSON format as sample specified. Give me only JSON,not any explanations.";
+            $prompt .= '"{\"policy\":{\"policy_number\":\"\",\"issue_date\":\"\",\"period\":{\"start\":\"\",\"end\":\"\"},\"insurer\":\"\",\"previous_policy_number\":\"\"},\"insured\":{\"name\":\"\",\"father_name\":\"\",\"address\":[\"\"],\"mobile\":\"\",\"id_proofs\":{\"aadhaar\":\"\",\"pan\":\"\"}},\"vehicle\":{\"reg_no\":\"\",\"engine_no\":\"\",\"chassis_no\":\"\",\"make\":\"\",\"model\":\"\",\"year\":\"\",\"cubic_capacity\":\"\",\"vehicle_type\":\"\"},\"rto\":\"\",\"premium\":{\"tp\":0,\"od\":0,\"pa_od\":0,\"taxes\":{},\"total\":0,\"in_words\":\"\"},\"endorsements\":[{\"code\":\"\",\"desc\":\"\"}]}"';
+
+            $payloadPart = null;
+
+            // The text part of the prompt
+            $text_part = [
+                "text" => $prompt
+            ];
+            // Conditionally handle the file upload based on MIME type
+            if (in_array($mimeType, $supportedInlineMimeTypes)) {
+                 echo "Detected supported format inline MIME type ({$mimeType})";
+                // Handle PDF as inline data
+                $fileContent = file_get_contents($filePath);
+                $base64Content = base64_encode($fileContent);
+                $payloadPart = [
+                    "inlineData" => [
+                        "mimeType" => $mimeType,
+                        "data" => $base64Content
+                    ]
+                ];
+
+                 $content_parts = [
+                        "parts" => [
+                            $text_part,
+                            $payloadPart
+                        ]
+                ];
+            } else {
+                // Handle Excel/CSV using the Files API
+                echo "Detected unsupported inline MIME type ({$mimeType}). Uploading via Files API...\n";
+                $fileInfo = $this->uploadFileToGemini($filePath, $apiKey); // Pass apiKey
+
+                print_r($fileInfo);
+                 // The file part, using the URI from the Files API upload
+                    $file_part = [
+                        "fileData" => [
+                            "fileUri" => $fileInfo['uri'],
+                            "mimeType" => $fileInfo['mimeType']
+                        ]
+                    ];
+
+                    // The full content array, containing both parts
+                    $content_parts = [
+                        "parts" => [
+                            $text_part,
+                            $file_part
+                        ]
+                    ];
+            }
+
+           
+
+          
+
             // The final JSON payload
             $data = [
                 "contents" => [
diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php
index 19cde67b..9e4a5a08 100755
--- a/app/Controllers/MasterController.php
+++ b/app/Controllers/MasterController.php
@@ -2073,7 +2073,7 @@ class MasterController extends AdminController
                 }
             }
 
-            $data = $nhanceBranchModel->where('is_active', 1)->findAll();
+            $data = $nhanceBranchModel->where('is_active', 1)->orderBy('id', 'DESC')->findAll();
             return $this->loadLayout('nhance_branch_list', ['data' => $data]);
 
         } elseif ($method === 'delete') {
@@ -2156,7 +2156,7 @@ class MasterController extends AdminController
                 }
             }
 
-            $data = $vehicleTypeModel->where('is_active', 1)->findAll();
+            $data = $vehicleTypeModel->where('is_active', 1)->orderBy('id', 'DESC')->findAll();
             return $this->loadLayout('vehicle_type_master_list', ['data' => $data]);
 
         } elseif ($method === 'delete') {
@@ -2239,7 +2239,7 @@ class MasterController extends AdminController
                 }
             }
 
-            $data = $rtoModel->where('is_active', 1)->findAll();
+            $data = $rtoModel->where('is_active', 1)->orderBy('id', 'DESC')->findAll();
             return $this->loadLayout('rto_master_list', ['data' => $data]);
 
         } elseif ($method === 'delete') {
diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php
index b8f21a84..94033074 100644
--- a/app/Controllers/PolicyTransactionController.php
+++ b/app/Controllers/PolicyTransactionController.php
@@ -1047,14 +1047,14 @@ class PolicyTransactionController extends BaseController
                 $this->policyTransactionModel->where('client_policy_id', $policy_transaction_data['client_policy_id'])->set($data)->update();
 
                 $cd_transaction_model = new ClientDepositModel();
-                $this->$cd_transaction_model->where('policy_transaction_id', $id)->set($data)->update();
+                $cd_transaction_model->where('policy_transaction_id', $id)->set($data)->update();
 
             }else{
                 $this->policyTransactionModel->where('id', $id)->set($data)->update();
                 $this->PTCOShareDetailsModel->where('pt_id', $id)->set($data)->update();
                 
                 $cd_transaction_model = new ClientDepositModel();
-                $this->$cd_transaction_model->where('policy_transaction_id', $id)->set($data)->update();
+                $cd_transaction_model->where('policy_transaction_id', $id)->set($data)->update();
 
             }
             return $this->respond(['status' => true, 'code' => 200, 'message' => 'Policy Transaction removed successfully'], 200);
@@ -3168,4 +3168,116 @@ class PolicyTransactionController extends BaseController
 
         return [$policyList, $policyListByClient];
     }
+
+
+public function reportBDSNew()
+{
+    // ๐Ÿงญ Basic Page Info
+    $data['tab_name']   = 'BDS Report';
+    $data['page_name']  = 'BDS Report';
+
+    // ๐Ÿ“‹ Dropdown Data
+    $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',
+    ];
+
+    // ๐Ÿข Fetch Active Data
+    $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['users']         = $this->userModel->where('is_active', 1)->findAll();
+    $data['policy_count']  = $this->policyTransactionModel->where('is_active', 1)->countAllResults();
+
+    // ๐Ÿ• Filters
+    $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');
+    $user_id           = $this->request->getGet('user_id');
+
+    // Handle statement month range
+    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));
+    }
+
+    // Ensure default values
+    $start_date        = $start_date        ?: 0;
+    $end_date          = $end_date          ?: 0;
+    $client_id         = $client_id         ?: 0;
+    $insurer_id        = $insurer_id        ?: 0;
+    $policy_type_id    = $policy_type_id    ?: 0;
+    $date_type         = $date_type         ?: 0;
+    $issuer            = $issuer            ?: 0;
+    $client_branch_id  = $client_branch_id  ?: 0;
+    $insurer_branch_id = $insurer_branch_id ?: 0;
+    $client_policy_id  = $client_policy_id  ?: 0;
+    $user_id           = $user_id           ?: 0;
+
+    // ๐Ÿงพ Handle POST requests (Dashboard filters)
+    if ($this->request->is('post')) {
+        $isFromDashboard = $this->request->getPost('is_dashboard');
+
+        if (!empty($isFromDashboard) && $isFromDashboard == 1) {
+            $ids = array_filter(explode(',', $this->request->getPost('ids')));
+
+            if (!empty($ids)) {
+                $idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs
+                $where  = "policy_transaction.id IN ($idsStr)";
+            } else {
+                $where = []; // No valid IDs
+            }
+        }
+    }
+
+    // ๐Ÿ“Š Fetch report data
+    $data['report_list'] = $this->policyTransactionModel->reportBDSNew(
+        $start_date,
+        $end_date,
+        $client_id,
+        $insurer_id,
+        $policy_type_id,
+        $date_type,
+        $issuer,
+        $client_branch_id,
+        $insurer_branch_id,
+        $client_policy_id,
+        $user_id,
+        $where ?? ''
+    );
+
+    // ๐Ÿงฉ Load View
+    $this->loadLayout('report_bds_filter', $data);
+}
+
+
+
 }
diff --git a/app/Models/PolicyTransactionModel.php b/app/Models/PolicyTransactionModel.php
index 2e935ead..a9629d73 100644
--- a/app/Models/PolicyTransactionModel.php
+++ b/app/Models/PolicyTransactionModel.php
@@ -1806,4 +1806,307 @@ class PolicyTransactionModel extends Model
 
         return $result[0];
     }
+
+    public function reportBDSNew(
+        $start_date = 0,
+        $end_date = 0,
+        $client_id = 0,
+        $insurer_id = 0,
+        $policy_type_id = 0,
+        $date_type = 0,
+        $issuer = 0,
+        $client_branch_id = 0,
+        $insurer_branch_id = 0,
+        $client_policy_id = 0,
+        $user_id = 0,
+        $where = []
+    ) {
+        
+        $date_condition = '';
+
+        // ==============================
+        // DATE FILTER FOR STATEMENT MONTH
+        // ==============================
+        if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) {
+            $date_condition = "
+                AND insurer_statements.month >= '{$start_date}'
+                AND insurer_statements.month <= '{$end_date}'
+            ";
+        }
+
+        // ==============================
+        // BASE QUERY
+        // ==============================
+        $builder = $this->db->table('policy_transaction')
+            ->select("
+                policy_transaction.*,
+                DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date,
+                DATE_FORMAT(
+                    IF(policy_transaction.month IS NULL, 
+                        policy_transaction.policy_issue_date, 
+                        policy_transaction.month
+                    ), '%b %Y'
+                ) AS policy_issue_month,
+
+                CASE
+                    WHEN clients.client_type = 1 THEN 'Group'
+                    WHEN clients.client_type = 2 THEN 'Retail'
+                    ELSE '-'
+                END AS client_type,
+
+                CASE
+                    WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh'
+                    ELSE 'Renewal'
+                END AS revenue_type,
+
+                CASE
+                    WHEN policy_transaction.action_type = 'inception' THEN 'Policy'
+                    ELSE 'Endorsement'
+                END AS action_type,
+
+                clients.client_name AS client_name,
+                clients.short_name AS client_short_name,
+                client_branch.branch_name AS client_branch_name,
+                client_branch.address1 AS client_address,
+                policy_type.policy_type,
+                policy_type.bap,
+                insurers.name AS insurer_name,
+                insurers.short_name AS insurer_short_name,
+                insurer_branch.branch_name AS insurer_branch_name,
+                insurer_branch.branch_code AS insurer_branch_code,
+                user_profiles.first_name AS user_name,
+                vehicle.vehicle_no,
+                tpa.name AS tpa_name,
+                pt_co_share_details.remark AS remarks,
+                pt_co_share_details.cop_amt AS bp_amt,
+                pt_co_share_details.exp_amt,
+                pt_co_share_details.id AS pt_id,
+                sales_user.first_name AS salse_person_name,
+                service_user.first_name AS service_person_name,
+
+                ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS premium_wo_gst,
+                ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2) AS gst_amount,
+                ROUND(
+                    ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) + 
+                    ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2),
+                2) AS total_premium,
+
+                ROUND(pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS tp_or_ter,
+                DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days,
+                (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per,
+                pt_co_share_details.agreed_bp_per,
+
+                -- ==============================
+                -- SUBQUERY: Total IRDA Amount
+                -- ==============================
+                ROUND((
+                    SELECT (
+                        SUM(co_share_stmt_details.actual_bp_brokerage_amt) + 
+                        SUM(co_share_stmt_details.actual_tp_brokerage_amt) + 
+                        SUM(co_share_stmt_details.actual_tep_brokerage_amt) +
+                        SUM(co_share_stmt_details.reward)
+                    )
+                    FROM co_share_stmt_details
+                    JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+                    WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
+                    AND co_share_stmt_details.is_active = 1
+                    AND insurer_statements.is_active = 1
+                    {$date_condition}
+                ), 2) AS total_irda_amt,
+
+                -- Reward Only
+                ROUND((
+                    SELECT SUM(co_share_stmt_details.reward)
+                    FROM co_share_stmt_details
+                    JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+                    WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
+                    AND co_share_stmt_details.is_active = 1
+                    AND insurer_statements.is_active = 1
+                    {$date_condition}
+                ), 2) AS reward,
+
+                -- Billed Amount
+                ROUND((
+                    SELECT SUM(
+                        COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) +
+                        COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) +
+                        COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) +
+                        COALESCE(co_share_stmt_details.reward, 0)
+                    )
+                    FROM co_share_stmt_details
+                    JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
+                    JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+                    WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
+                    AND co_share_stmt_details.is_active = 1
+                    AND pt_table.is_active = 1
+                    AND insurer_statements.is_active = 1
+                    AND insurer_statements.invoice_status IS NOT NULL
+                    {$date_condition}
+                ), 2) AS billed_amt,
+
+                -- Unbilled Amount
+                ROUND(
+                (
+                    (
+                        SELECT 
+                            SUM(
+                                COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) +
+                                COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) +
+                                COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) +
+                                COALESCE(co_share_stmt_details.reward, 0)
+                            )
+                        FROM co_share_stmt_details
+                        JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+                        WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
+                        AND co_share_stmt_details.is_active = 1
+                        {$date_condition}
+                    ) 
+                        -
+                    (
+                        SELECT 
+                            SUM(
+                                COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) +
+                                COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) +
+                                COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) +
+                                COALESCE(co_share_stmt_details.reward, 0)
+                            )
+                        FROM co_share_stmt_details
+                        JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
+                        JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+                        WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
+                        AND co_share_stmt_details.is_active = 1
+                        AND pt_table.is_active = 1
+                        AND insurer_statements.is_active = 1
+                        AND insurer_statements.invoice_status IS NULL
+                        {$date_condition}
+                    )
+                ), 2) AS unbilled_amt,
+
+                created_user.first_name AS user_name,
+
+                CASE 
+                    WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no
+                    WHEN pt_co_share_details.co_share_type > 1 THEN 
+                        CASE 
+                            WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = '' 
+                            THEN policy_transaction.policy_no
+                            ELSE pt_co_share_details.follower_policy_no
+                        END
+                    ELSE policy_transaction.policy_no
+                END AS policy_no
+            ")
+
+            // ==============================
+            // JOINS
+            // ==============================
+            ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
+            ->join('clients', 'clients.id = policy_transaction.client_id')
+            ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
+            ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+            ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left')
+            ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left')
+            ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
+            ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
+            ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left')
+            ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left')
+            ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left')
+            ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left')
+            ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
+            ->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left')
+            ->where('policy_transaction.is_active', 1)
+            ->where('pt_co_share_details.is_active', 1);
+
+        // ==============================
+        // ROLE-BASED FILTERS
+        // ==============================
+        if (
+            (!in_array(get_role_id(), [1, 5])) &&
+            !(
+                in_array(MANAGEMENT_TEAM_ID, user_team()) ||
+                in_array(FINANCE_TEAM_ID, user_team()) ||
+                in_array(BUSINESS_TEAM_ID, user_team())
+            )
+        ) {
+            if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+                $builder->where('policy_transaction.created_by', get_session_userid());
+            }
+        }
+
+        // ==============================
+        // ADDITIONAL FILTERS
+        // ==============================
+        if (!empty($where)) {
+            log_message('info', 'Where condition: ' . json_encode($where));
+            $builder->where($where);
+        }
+
+        if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') {
+            $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
+            $endDate   = date('Y-m-d 23:59:59', strtotime($end_date));
+
+            $builder->where("policy_transaction.{$date_type} >=", $startDate)
+                    ->where("policy_transaction.{$date_type} <=", $endDate);
+        }
+
+        // JOIN FOR STATEMENT MONTH FILTER
+        if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) {
+            $startDate = date('Y-m-d', strtotime($start_date));
+            $endDate   = date('Y-m-d', strtotime($end_date));
+
+            $builder->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id', 'left')
+                    ->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id', 'left')
+                    ->where('insurer_statements.is_active', 1)
+                    ->where('insurer_statements.month >=', $startDate)
+                    ->where('insurer_statements.month <=', $endDate)
+                    ->groupBy('co_share_stmt_details.co_share_id');
+        }
+
+        // ==============================
+        // FILTER BY IDs
+        // ==============================
+        if ($client_id != 0) $builder->where('policy_transaction.client_id', $client_id);
+        if ($insurer_id != 0) $builder->where('policy_transaction.insurer_id', $insurer_id);
+        if ($client_branch_id != 0) $builder->where('policy_transaction.client_branch_id', $client_branch_id);
+        if ($insurer_branch_id != 0) $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id);
+        if ($client_policy_id != 0) $builder->where('policy_transaction.client_policy_id', $client_policy_id);
+        if ($user_id != 0) $builder->where('policy_transaction.created_by', $user_id);
+        if ($policy_type_id != 0) $builder->where('client_policy.policy_type_id', $policy_type_id);
+        if ($issuer != 0) $builder->where('policy_transaction.issuer', $issuer);
+
+        // ==============================
+        // DEFAULT 90-DAY FILTER
+        // ==============================
+        if (
+            $client_id == 0 && 
+            $insurer_id == 0 && 
+            $policy_type_id == 0 && 
+            $date_type == 0 && 
+            $issuer == 0
+        ) {
+            $fromDate = date('Y-m-d', strtotime('-90 days'));
+            $toDate   = date('Y-m-d 23:59:59');
+
+            if (empty($where)) {
+                $builder->where('policy_transaction.created_at >=', $fromDate)
+                        ->where('policy_transaction.created_at <=', $toDate);
+            }
+        }
+
+        // ==============================
+        // ORDER & EXECUTION
+        // ==============================
+        $builder->orderBy('policy_transaction.id', 'desc');
+
+        $result = $builder->get()->getResultArray();
+
+        // Uncomment if you need to debug SQL
+        // dd($this->db->getLastQuery());
+
+        return $result;
+    }
+
+
+ 
+
+
 }
diff --git a/app/Views/client_policy.php b/app/Views/client_policy.php
index 11e9f37f..253d690b 100755
--- a/app/Views/client_policy.php
+++ b/app/Views/client_policy.php
@@ -742,37 +742,41 @@ input:checked + .slider::before {
 
                     var policy_name_data = `${item.policy_type_name ?? ''}` + ' - ' +  `${item.policy_no ?? ''}`;
 
-                    policyTable += `
-                        
-                            ${item.insurer_short} - ${item.insurer_branch_name}
-                            ${policy_name_data}
-                            ${item.branch_name ? item.branch_name : ' - '}
-                            ${tpaValue}
-
-                            ${(item.policy_start_date)} / ${(item.policy_end_date)}
-                            ${checkDateStatus(item.policy_end_date, 1)}
-                            
-                                
-                            
-                        
-                    `;
                 });
                 $('#policy_table').append(policyTable);
                 // console.log(policyTable);
@@ -799,6 +803,9 @@ input:checked + .slider::before {
                         //console.log('Unknown error occurred', 'Warning');
                     }
                 }, 1000);
+            },
+            complete :function(){
+                console.log('AJAX request completed');
             }
         });
 
diff --git a/app/Views/insurer_statement_list.php b/app/Views/insurer_statement_list.php
index 6c5d67bb..8e89fcb2 100644
--- a/app/Views/insurer_statement_list.php
+++ b/app/Views/insurer_statement_list.php
@@ -508,7 +508,7 @@
                              -->
                             
 
-                            
+
@@ -964,14 +964,32 @@ var modal_received_amt_div = document.getElementById('modal_received_amt_div'); modal_received_amt_div.style.display = 'none'; // alert(); - // console.log(event.target.data) - var dataId = event.target.getAttribute('data-id'); + // make sure event exists + event = event || window.event; + + // the element actually clicked + const clicked = event.target; + + // find the nearest ancestor (or element) that has data-id + const anchor = clicked.closest('a[data-id], .btnEdit'); + + if (!anchor) { + console.warn('Could not find element with data-id'); + return; + } + + const dataId = anchor.getAttribute('data-id'); + const expAmt = anchor.getAttribute('data-exp-amt'); + const receivedAmt = anchor.getAttribute('data-received-amt'); + + console.log('stmt id :', dataId, expAmt, receivedAmt); + var dataExpAmt = event.target.getAttribute('data-exp-amt'); var dataReceivedAmt = event.target.getAttribute('data-received-amt'); // Set the value to a hidden input field in the modal document.getElementById('hidden_statement_id').value = dataId; // document.getElementById('modal_exp_amt').value = dataExpAmt; - document.getElementById('modal_received_amt').value = dataReceivedAmt; + document.getElementById('modal_received_amt').value = receivedAmt; $('.loader').fadeIn(); $('.loader-mask').fadeIn(); @@ -981,10 +999,78 @@ method: 'get', // data: { id: dataId }, // dataType: 'json', + // success: function(response) { + // $('.loader').fadeOut(); + // $('.loader-mask').delay(10).fadeOut('slow'); + // console.log(response); + // // Assuming response contains the necessary data + // if (response.dataStatus === true && response.code === 200) { + // // Populate modal fields + // if (response.data.invoice_status !== null) { + // var inv_status_element = document.getElementById('invoice_status'); + // inv_status_element.value = response.data.invoice_status; + // var event = new Event('change'); + // inv_status_element.dispatchEvent(event); + // } + + // document.getElementById('invoice_no_modal').value = response.data.invoice_no; + // document.getElementById('invoice_date_modal').value = response.data.invoice_date === '' ? : response.data.invoice_date; + // document.getElementById('invoice_amount_no_modal').value = response.data.invoice_amount; + + // document.getElementById('invoice_value_modal').value = response.data.invoice_value; + // document.getElementById('gst_per_modal').value = response.data.gst_per; + // document.getElementById('gst_value_modal').value = response.data.gst_value; + // console.log('response.data.gst_value - ' + response.data.gst_value); + // if (response.data.gst_value == 0 || response.data.gst_value == '' || response.data.gst_value == null) { + // calcGSTValue(); + // } + + // if (!$('#invoice_date_modal').val()) { + // // alert('nope'); + // // Set today's date as the default date + // $('#invoice_date_modal').datepicker('setDate', new Date()); + // } + // // Clear existing rows in the payment table + // var paymentTableBody = document.querySelector('#payment_table_modal tbody'); + // // var paymentTableBody = document.getElementById('payment_card_container'); + + // console.log('response.data.payments.length', response.data.payments.length) + // // Populate payment table rows + // if (response.data.payments.length) { + // paymentTableBody.innerHTML = ''; + // response.data.payments.forEach(function(payment) { + // var row = paymentTableBody.insertRow(); + + // row.innerHTML = ` + // + // + // + // + // + // + // + // `; + // }); + // } + // $('.payment_date').datepicker({ + // format: 'dd/mm/yyyy', + // autoclose: true + // }); + // // Show the modal + // var myModal = new bootstrap.Modal(document.getElementById('invoice_modal')); + // myModal.show(); + // } else { + // // Handle error if the response is not successful + // console.error('Failed to fetch data:', response); + // alert("Something went wrong! Couldn't get data"); + // } + // }, + success: function(response) { $('.loader').fadeOut(); $('.loader-mask').delay(10).fadeOut('slow'); console.log(response); + // Assuming response contains the necessary data if (response.dataStatus === true && response.code === 200) { // Populate modal fields @@ -996,46 +1082,79 @@ } document.getElementById('invoice_no_modal').value = response.data.invoice_no; - document.getElementById('invoice_date_modal').value = response.data.invoice_date === '' ? : response.data.invoice_date; + document.getElementById('invoice_date_modal').value = response.data.invoice_date === '' ? '' : response.data.invoice_date; document.getElementById('invoice_amount_no_modal').value = response.data.invoice_amount; document.getElementById('invoice_value_modal').value = response.data.invoice_value; document.getElementById('gst_per_modal').value = response.data.gst_per; document.getElementById('gst_value_modal').value = response.data.gst_value; console.log('response.data.gst_value - ' + response.data.gst_value); + if (response.data.gst_value == 0 || response.data.gst_value == '' || response.data.gst_value == null) { calcGSTValue(); } if (!$('#invoice_date_modal').val()) { - // alert('nope'); // Set today's date as the default date $('#invoice_date_modal').datepicker('setDate', new Date()); } - // Clear existing rows in the payment table - var paymentTableBody = document.querySelector('#payment_table_modal tbody'); + + // Clear existing payment cards in the container + var defaultPaymentCardContainer = document.getElementById('default_payment_card'); + defaultPaymentCardContainer.style.display = 'block'; + var paymentCardContainer = document.getElementById('payment_card_container'); + paymentCardContainer.innerHTML = ''; - console.log('response.data.payments.length', response.data.payments.length) - // Populate payment table rows + console.log('response.data.payments.length', response.data.payments.length); + + // Populate payment cards if (response.data.payments.length) { - paymentTableBody.innerHTML = ''; - response.data.payments.forEach(function(payment) { - var row = paymentTableBody.insertRow(); - row.innerHTML = ` - - - - - - - + defaultPaymentCardContainer.style.display = 'none'; + response.data.payments.forEach(function(payment, index) { + var paymentCard = document.createElement('div'); + paymentCard.className = 'payment-card'; + + paymentCard.innerHTML = ` + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
`; + + paymentCardContainer.appendChild(paymentCard); }); } + + // Initialize datepicker for all payment date fields $('.payment_date').datepicker({ format: 'dd/mm/yyyy', autoclose: true }); + // Show the modal var myModal = new bootstrap.Modal(document.getElementById('invoice_modal')); myModal.show(); diff --git a/app/Views/layout/header.php b/app/Views/layout/header.php index 2342bcb0..a8f91141 100755 --- a/app/Views/layout/header.php +++ b/app/Views/layout/header.php @@ -149,7 +149,7 @@