$data['amount'], 'sub_type' => $data['sub_type_id'], 'client_id' => $data['client_id'], 'client_policy_id' => $data['client_policy_id'] ?? 0, 'cd_ac_no' => $data['cd_ac_no'], 'endorsement_no' => $data['endorsement_no'], 'insurer_id' => $data['insurer_id'], 'unit' => $data['unit'] ?? null, 'description' => $data['description'] ?? null, 'event_name' => $data['event_name'] ?? null, 'transaction_type' => $data['transaction_type'], 'is_active' => 1, 'created_by' => $loggedInUserID, 'updated_by' => $data['updated_by'], 'balance' => $newBalance, // Include the new balance in the data array ]; // Insert data and get the insert ID $insertId = $model->insert($insertData); // Return the response if ($insertId) { return [ 'success' => true, 'message' => 'Transaction saved successfully', 'insert_id' => $insertId, ]; } else { return [ 'success' => false, 'message' => 'Failed to save transaction', ]; } } /** * Calculate the last balance based on client and insurer ID. * * @param int $clientId The client ID. * @param int $insurerId The insurer ID. * * @return float The last known balance. */ public static function calculateLastBalance(int $clientId, int $insurerId, $cd_ac_no): float { $model = new ClientDepositModel(); // $getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE client_id = ? AND insurer_id = ? ORDER BY created_at DESC LIMIT 1"; // $getLastBalanceParams = [$clientId, $insurerId]; $getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE cd_ac_no = ? AND is_active = 1 ORDER BY created_at DESC LIMIT 1"; $getLastBalanceParams = [$cd_ac_no]; $lastBalance = $model->query($getLastBalanceQuery, $getLastBalanceParams)->getRow()->balance ?? 0; // if(empty($lastBalance) && $lastBalance == null){ // $cd_model = new ClientDepositModel(); // $getLastBalanceQuery = "SELECT opening_bal FROM cd_master WHERE client_id = ? AND insurer_id = ? AND cd_ac_no = ? AND is_active = 1 ORDER BY created_at DESC LIMIT 1"; // $getLastBalanceParams = [$clientId, $insurerId, $cd_ac_no]; // $lastBalance = $cd_model->query($getLastBalanceQuery, $getLastBalanceParams)->getRow()->opening_bal ?? 0; // } return $lastBalance; } } ?>