<?php
$lifetime = 60 * 60 * 24 * 30; 
session_set_cookie_params($lifetime, '/');
session_start();

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header('Location: ../ca/login.php');
    exit;
}

require_once '../db_connect.php';

// =================================================================================
// 1. AJAX HANDLER: SEARCH ACCOUNT NUMBERS FOR THE MODAL
// =================================================================================
if (isset($_GET['ajax_search_account']) && $_GET['ajax_search_account'] === '1') {
    $term = $_GET['term'] ?? '';
    
    try {
        $sql = "SELECT rider_ops_id, REPLACE(full_name, '?', 'Ñ') as full_name, hub, bank, account_number 
                FROM account_numbers 
                WHERE rider_ops_id LIKE ? OR full_name LIKE ? OR last_name LIKE ? OR first_name LIKE ?
                LIMIT 15";
                
        $stmt = $pdo->prepare($sql);
        $like_term = "%" . str_replace('Ñ', '?', $term) . "%";
        $stmt->execute([$like_term, $like_term, $like_term, $like_term]);
        
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($results);
    } catch (Exception $e) {
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit;
}

// =================================================================================
// 2. AJAX HANDLER: GET LOAN SCHEDULE (BALANCING)
// =================================================================================
if (isset($_GET['ajax_get_schedule']) && $_GET['ajax_get_schedule'] === '1') {
    $loan_no = $_GET['loan_no'] ?? '';
    
    $sql = "SELECT s.*, ca.amount as total_loan, ca.additional_loan_amount as topped_up_amount 
            FROM cash_advance_schedule s 
            JOIN cash_advances ca ON s.loan_no = ca.loan_no 
            WHERE s.loan_no = ? ORDER BY s.payment_date ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$loan_no]);
    
    echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    exit;
}

// =================================================================================
// 3. AJAX HANDLER: SAVE NEW CASH ADVANCE & GENERATE SCHEDULE
// =================================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_ca') {
    $date_of_voucher = $_POST['date_of_voucher'];
    $rgs_id = $_POST['rgs_id'];
    $name = $_POST['employee_name'];
    $account_client = $_POST['account_client']; 
    $amount = $_POST['amount'];
    $gives = $_POST['gives'] ?: 1; 
    $remarks = $_POST['remarks'];
    
    $calc_mode = $_POST['calc_mode'] ?? 'by_gives';
    $cutoff_amt = !empty($_POST['cutoff_amt']) ? (float)$_POST['cutoff_amt'] : 0;
    
    $start_payment_date = !empty($_POST['start_payment_date']) ? $_POST['start_payment_date'] : date('Y-m-d'); 

    $stmt_max = $pdo->query("SELECT MAX(id) as max_id FROM cash_advances");
    $max_row = $stmt_max->fetch(PDO::FETCH_ASSOC);
    $next_id = ($max_row['max_id'] ?? 0) + 1;
    $loan_no = 'CA-' . date('Ym') . '-' . str_pad($next_id, 4, '0', STR_PAD_LEFT);

    try {
        $pdo->beginTransaction();

        $sql = "INSERT INTO cash_advances (loan_no, date_of_voucher, rider_ops_id, name, account, amount, gives, remarks, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Pending')";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$loan_no, $date_of_voucher, $rgs_id, str_replace('Ñ', '?', $name), $account_client, $amount, $gives, $remarks]);

        $is_15_30 = ($account_client === 'SPX' || $account_client === 'SCOMMERCE');
        
        try {
            $current_date = new DateTime($start_payment_date);
        } catch (Exception $e) {
            $current_date = new DateTime(date('Y-m-d')); 
        }
        
        $schedule_sql = "INSERT INTO cash_advance_schedule (loan_no, payment_date, amount_due, amount_paid, status) VALUES (?, ?, ?, 0.00, 'Pending')";
        $stmt_sched = $pdo->prepare($schedule_sql);

        $remaining_balance = $amount;

        for ($i = 0; $i < $gives; $i++) {
            $formatted_date = $current_date->format('Y-m-d');
            
            if ($calc_mode === 'by_cutoff' && $cutoff_amt > 0) {
                $amount_due = min($cutoff_amt, $remaining_balance);
                $remaining_balance -= $amount_due;
            } else {
                $amount_due = $amount / $gives;
            }
            
            $stmt_sched->execute([$loan_no, $formatted_date, $amount_due]);
            
            $day = (int)$current_date->format('d');
            $month = (int)$current_date->format('m');
            $year = (int)$current_date->format('Y');
            
            if ($is_15_30) {
                if ($day == 15) {
                    $day = 30;
                } else {
                    $day = 15;
                    $month++;
                    if ($month > 12) { $month = 1; $year++; }
                }
            } else {
                if ($day == 10) {
                    $day = 25;
                } else {
                    $day = 10;
                    $month++;
                    if ($month > 12) { $month = 1; $year++; }
                }
            }
            
            $next_date_str = sprintf('%04d-%02d-01', $year, $month);
            $last_day_of_month = (int)(new DateTime($next_date_str))->format('t');
            $actual_day = min($day, $last_day_of_month);
            
            $current_date = new DateTime(sprintf('%04d-%02d-%02d', $year, $month, $actual_day));
        }

        $pdo->commit();
        echo json_encode(['status' => 'success']);
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// =================================================================================
// 4. AJAX HANDLER: COLLECT PAYMENT (WITH AUTO-CARRYOVER)
// =================================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'collect_payment') {
    $sched_id = $_POST['schedule_id'];
    $amount_paid = (float)$_POST['amount_paid'];
    $paid_date = $_POST['paid_date'];

    try {
        $pdo->beginTransaction();

        $stmt = $pdo->prepare("SELECT * FROM cash_advance_schedule WHERE id = ?");
        $stmt->execute([$sched_id]);
        $sched = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$sched) throw new Exception("Schedule not found.");

        $loan_no = $sched['loan_no'];
        $amount_due = (float)$sched['amount_due'];

        $update_sql = "UPDATE cash_advance_schedule SET status = 'Paid', amount_paid = ?, paid_date = ? WHERE id = ?";
        $update_stmt = $pdo->prepare($update_sql);
        $update_stmt->execute([$amount_paid, $paid_date, $sched_id]);

        // Auto-Carryover if they paid less than the amount due
        if ($amount_paid < $amount_due) {
            $shortfall = $amount_due - $amount_paid;

            // Find next schedule
            $next_stmt = $pdo->prepare("SELECT id FROM cash_advance_schedule WHERE loan_no = ? AND status = 'Pending' AND payment_date > ? ORDER BY payment_date ASC LIMIT 1");
            $next_stmt->execute([$loan_no, $sched['payment_date']]);
            $next_sched = $next_stmt->fetch(PDO::FETCH_ASSOC);

            if ($next_sched) {
                // Add to existing next schedule
                $add_stmt = $pdo->prepare("UPDATE cash_advance_schedule SET amount_due = amount_due + ? WHERE id = ?");
                $add_stmt->execute([$shortfall, $next_sched['id']]);
            } else {
                // Generate a new schedule for the shortfall
                $acc_stmt = $pdo->prepare("SELECT account FROM cash_advances WHERE loan_no = ?");
                $acc_stmt->execute([$loan_no]);
                $account_client = $acc_stmt->fetchColumn();

                $is_15_30 = ($account_client === 'SPX' || $account_client === 'SCOMMERCE');
                $current_date = new DateTime($sched['payment_date']);
                $day = (int)$current_date->format('d');
                $month = (int)$current_date->format('m');
                $year = (int)$current_date->format('Y');
                
                if ($is_15_30) {
                    if ($day == 15) { $day = 30; } else { $day = 15; $month++; if ($month > 12) { $month = 1; $year++; } }
                } else {
                    if ($day == 10) { $day = 25; } else { $day = 10; $month++; if ($month > 12) { $month = 1; $year++; } }
                }
                
                $next_date_str = sprintf('%04d-%02d-01', $year, $month);
                $last_day_of_month = (int)(new DateTime($next_date_str))->format('t');
                $actual_day = min($day, $last_day_of_month);
                $next_payment_date = sprintf('%04d-%02d-%02d', $year, $month, $actual_day);

                $insert_stmt = $pdo->prepare("INSERT INTO cash_advance_schedule (loan_no, payment_date, amount_due, amount_paid, status) VALUES (?, ?, ?, 0.00, 'Pending')");
                $insert_stmt->execute([$loan_no, $next_payment_date, $shortfall]);
            }
        }

        $pdo->commit();
        echo json_encode(['status' => 'success']);
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// =================================================================================
// 5. AJAX HANDLER: ADD ADDITIONAL LOAN (TOP-UP WITHOUT INTEREST)
// =================================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'topup_ca') {
    $loan_no = $_POST['loan_no'];
    $additional_amount = (float)$_POST['additional_amount'];

    try {
        $pdo->beginTransaction();

        $stmt = $pdo->prepare("SELECT id FROM cash_advance_schedule WHERE loan_no = ? AND status = 'Pending' ORDER BY payment_date ASC");
        $stmt->execute([$loan_no]);
        $pending_schedules = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $remaining_gives = count($pending_schedules);

        if ($remaining_gives === 0) {
            throw new Exception("There are no pending gives left to absorb the additional amount.");
        }

        $amount_per_give = $additional_amount / $remaining_gives;

        $update_sched = $pdo->prepare("UPDATE cash_advance_schedule SET amount_due = amount_due + ? WHERE id = ?");
        foreach ($pending_schedules as $sched) {
            $update_sched->execute([$amount_per_give, $sched['id']]);
        }

        $update_main = $pdo->prepare("UPDATE cash_advances SET amount = amount + ?, additional_loan_amount = additional_loan_amount + ?, is_topped_up = 1 WHERE loan_no = ?");
        $update_main->execute([$additional_amount, $additional_amount, $loan_no]);

        $pdo->commit();
        echo json_encode(['status' => 'success']);
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// =================================================================================
// 5.5 AJAX HANDLER: GENERATE SCHEDULE FOR ORPHANED BALANCE
// =================================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_shortfall_schedule') {
    $loan_no = $_POST['loan_no'];
    
    try {
        $pdo->beginTransaction();
        
        $stmt = $pdo->prepare("SELECT account, amount FROM cash_advances WHERE loan_no = ?");
        $stmt->execute([$loan_no]);
        $loan = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $paid_stmt = $pdo->prepare("SELECT COALESCE(SUM(amount_paid), 0) FROM cash_advance_schedule WHERE loan_no = ? AND status = 'Paid'");
        $paid_stmt->execute([$loan_no]);
        $total_paid = (float)$paid_stmt->fetchColumn();
        
        $shortfall = (float)$loan['amount'] - $total_paid;
        
        if ($shortfall <= 0) {
            throw new Exception("There is no remaining balance to schedule.");
        }
        
        $last_sched_stmt = $pdo->prepare("SELECT payment_date FROM cash_advance_schedule WHERE loan_no = ? ORDER BY payment_date DESC LIMIT 1");
        $last_sched_stmt->execute([$loan_no]);
        $last_date = $last_sched_stmt->fetchColumn() ?: date('Y-m-d');
        
        $account_client = $loan['account'];
        $is_15_30 = ($account_client === 'SPX' || $account_client === 'SCOMMERCE');
        
        $current_date = new DateTime($last_date);
        $day = (int)$current_date->format('d');
        $month = (int)$current_date->format('m');
        $year = (int)$current_date->format('Y');
        
        if ($is_15_30) {
            if ($day == 15) { $day = 30; } else { $day = 15; $month++; if ($month > 12) { $month = 1; $year++; } }
        } else {
            if ($day == 10) { $day = 25; } else { $day = 10; $month++; if ($month > 12) { $month = 1; $year++; } }
        }
        
        $next_date_str = sprintf('%04d-%02d-01', $year, $month);
        $last_day_of_month = (int)(new DateTime($next_date_str))->format('t');
        $actual_day = min($day, $last_day_of_month);
        $next_payment_date = sprintf('%04d-%02d-%02d', $year, $month, $actual_day);
        
        $insert_stmt = $pdo->prepare("INSERT INTO cash_advance_schedule (loan_no, payment_date, amount_due, amount_paid, status) VALUES (?, ?, ?, 0.00, 'Pending')");
        $insert_stmt->execute([$loan_no, $next_payment_date, $shortfall]);
        
        $pdo->commit();
        echo json_encode(['status' => 'success']);
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// =================================================================================
// 6. MAIN TABLE RENDERER (Admin View)
// =================================================================================
$searched_name_or_id = isset($_GET['search_term']) ? $_GET['search_term'] : '';
$is_ajax = isset($_GET['ajax']) && $_GET['ajax'] === '1';

function renderCashAdvanceTable($pdo, $searched_name_or_id) {
    ob_start();
    $sql = "SELECT ca.*, 
                   REPLACE(an.full_name, '?', 'Ñ') AS linked_name_cor,
                   an.hub,
                   an.bank,
                   an.account_number AS bank_account,
                   (SELECT COALESCE(SUM(amount_paid), 0) FROM cash_advance_schedule WHERE loan_no = ca.loan_no AND status = 'Paid') as total_paid
            FROM `cash_advances` ca
            LEFT JOIN `account_numbers` an ON ca.rider_ops_id = an.rider_ops_id";

    $conditions = [];
    $params = [];

    if (!empty($searched_name_or_id)) {
        $db_friendly_search = str_replace('Ñ', '?', $searched_name_or_id);
        $conditions[] = "(ca.loan_no LIKE ? OR ca.rider_ops_id LIKE ? OR an.full_name LIKE ? OR ca.name LIKE ?)";
        $params[] = "%" . $db_friendly_search . "%";
        $params[] = "%" . $db_friendly_search . "%";
        $params[] = "%" . $db_friendly_search . "%";
        $params[] = "%" . $db_friendly_search . "%";
    }

    if (!empty($conditions)) {
        $sql .= " WHERE " . implode(" AND ", $conditions);
    }

    $sql .= " ORDER BY ca.date_of_voucher DESC LIMIT 1000";
    $stmt = $pdo->prepare($sql);

    if ($stmt) {
        $stmt->execute($params);
        $total_rows = $stmt->rowCount();
        
        echo "<p class='result-count text-lg font-semibold text-gray-700 mb-4'>Found <strong>" . $total_rows . "</strong> cash advance record(s).</p>";

        echo "<div class='table-wrapper'>";
        echo "<table class='min-w-full divide-y divide-gray-200 border border-gray-200'>";
        echo "<thead class='bg-gray-50'>";
        echo "<tr>";
        echo "<th class='col-actions px-6 py-3 text-center text-xs font-bold text-gray-600 uppercase tracking-wider'>ACTIONS</th>";
        echo "<th class='col-id px-6 py-3 text-left text-xs font-bold text-gray-600 uppercase tracking-wider no-wrap'>LOAN NO.</th>";
        echo "<th class='col-id px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider no-wrap'>DATE OF VOUCHER</th>";
        echo "<th class='col-status px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider no-wrap'>ID</th>";
        echo "<th class='col-name px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider'>EMPLOYEE NAME</th>";
        echo "<th class='col-small px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider'>HUB</th>";
        echo "<th class='col-small px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider'>BANK</th>";
        echo "<th class='col-small px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider'>AMOUNT</th>";
        echo "<th class='col-small px-6 py-3 text-left text-xs font-bold text-red-600 uppercase tracking-wider'>REMAINING BAL.</th>";
        echo "<th class='col-small px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider'>GIVES</th>";
        echo "<th class='col-notes px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider'>REMARKS</th>";
        echo "</tr>";
        echo "</thead>";
        echo "<tbody class='bg-white divide-y divide-gray-200 text-sm text-gray-600'>";

        if ($total_rows > 0) {
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $display_name = !empty($row["linked_name_cor"]) ? $row["linked_name_cor"] : str_replace('?', 'Ñ', $row["name"]);
                $remaining_balance = $row["amount"] - $row["total_paid"];
                $topup_badge = !empty($row["is_topped_up"]) ? '<br><span class="bg-blue-100 text-blue-800 text-xs font-semibold px-2 py-0.5 rounded mt-1 inline-block">Topped Up</span>' : '';
                
                $additional_amount = (float)$row["additional_loan_amount"];
                $amount_display = "₱ " . number_format((float)$row["amount"], 2);
                if ($additional_amount > 0) {
                    $amount_display .= "<br><small class='text-blue-600 font-bold'>(+ ₱ " . number_format($additional_amount, 2) . " Top-up)</small>";
                }
                
                echo "<tr class='hover:bg-gray-50'>";
                echo "<td class='col-actions px-6 py-4 text-center whitespace-nowrap'>";
                echo "<button class='text-blue-600 hover:text-blue-900 font-medium btn-view-schedule mr-3' data-loan='" . htmlspecialchars($row["loan_no"]) . "' data-name='" . htmlspecialchars($display_name, ENT_QUOTES, 'UTF-8') . "'><i class='fas fa-eye'></i> View</button>";
                echo "<a href='print_moa.php?loan_no=" . urlencode($row["loan_no"]) . "' target='_blank' class='text-green-600 hover:text-green-900 font-medium mr-3'><i class='fas fa-print'></i> Print MOA</a>";
                echo "<a href='print_soa.php?loan_no=" . urlencode($row["loan_no"]) . "' target='_blank' class='text-purple-600 hover:text-purple-900 font-medium'><i class='fas fa-file-invoice-dollar'></i> Print SOA</a>";
                echo "</td>";
                
                echo "<td class='col-id px-6 py-4 whitespace-nowrap font-semibold text-gray-800'>" . htmlspecialchars($row["loan_no"] ?? '') . $topup_badge . "</td>";
                echo "<td class='col-id px-6 py-4 whitespace-nowrap'>" . htmlspecialchars($row["date_of_voucher"] ?? '') . "</td>";
                echo "<td class='col-status px-6 py-4 whitespace-nowrap font-medium'>" . htmlspecialchars($row["rider_ops_id"] ?? '') . "</td>";
                echo "<td class='col-name px-6 py-4 font-medium text-gray-900 whitespace-nowrap'>" . htmlspecialchars($display_name, ENT_QUOTES, 'UTF-8') . "</td>";
                echo "<td class='col-small px-6 py-4 whitespace-nowrap'>" . htmlspecialchars($row["hub"] ?? 'N/A') . "</td>";
                echo "<td class='col-small px-6 py-4 whitespace-nowrap'>" . htmlspecialchars($row["bank"] ?? 'N/A') . "</td>";
                echo "<td class='col-small px-6 py-4 whitespace-nowrap text-gray-700 font-semibold'>" . $amount_display . "</td>";
                echo "<td class='col-small px-6 py-4 whitespace-nowrap text-red-600 font-bold'>₱ " . number_format((float)$remaining_balance, 2) . "</td>";
                echo "<td class='col-small px-6 py-4 whitespace-nowrap'>" . htmlspecialchars($row["gives"] ?? '') . "</td>";
                echo "<td class='col-notes px-6 py-4'>" . htmlspecialchars($row["remarks"] ?? '') . "</td>";
                
                echo "</tr>";
            }
        } else {
            echo "<tr><td colspan='11' class='px-6 py-4 text-center text-gray-500'>No cash advance records found.</td></tr>";
        }
        echo "</tbody></table></div>";
    }
    return ob_get_clean();
}

if ($is_ajax && !isset($_GET['ajax_search_account']) && !isset($_GET['ajax_get_schedule'])) {
    echo '<div id="ca-table-container">';
    echo renderCashAdvanceTable($pdo, $searched_name_or_id);
    echo '</div>';
    exit; 
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>RGServe HRIS - Standard Cash Advances</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.6.0/css/bootstrap.min.css"> 
    <style>
        .table-wrapper { overflow-x: auto; }
        .table-wrapper::-webkit-scrollbar { height: 12px; background-color: #f1f1f1; border-radius: 6px; }
        .table-wrapper::-webkit-scrollbar-thumb { background-color: #888; border-radius: 6px; border: 2px solid #f1f1f1; }
        
        #search_results {
            position: absolute;
            z-index: 1050;
            width: 100%;
            background: white;
            border: 1px solid #ccc;
            max-height: 200px;
            overflow-y: auto;
            border-radius: 0 0 5px 5px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .search-item { padding: 10px; cursor: pointer; border-bottom: 1px solid #eee; }
        .search-item:hover { background-color: #f0fdf4; }
    </style>
</head>
<body class="bg-gray-100">

    <div class="flex h-screen">
        <aside class="w-64 bg-gray-800 text-white flex-shrink-0 shadow-xl z-20">
            <div class="p-4 border-b border-gray-700 flex justify-center"><img src="../logo9.png" alt="Logo" class="h-15 w-auto" onerror="this.style.display='none'"></div>
            <nav class="p-4 space-y-2">
                <a href="cash_advances.php" class="flex items-center space-x-3 py-2.5 px-4 rounded-lg bg-green-600 text-white transition duration-200"><i class="fas fa-money-check-alt w-5 h-5"></i><span>Standard CA</span></a>
                <a href="cash_advances_interest.php" class="flex items-center space-x-3 py-2.5 px-4 rounded-lg text-gray-300 hover:bg-gray-700 hover:text-white transition duration-200"><i class="fas fa-percentage w-5 h-5"></i><span>CA With Interest</span></a>
                <a href="ca_reports.php" class="flex items-center space-x-3 py-2.5 px-4 rounded-lg text-gray-300 hover:bg-gray-700 hover:text-white transition duration-200"><i class="fas fa-chart-pie w-5 h-5"></i><span>Financial Reports</span></a>
            </nav>
        </aside>

        <main class="flex-1 overflow-y-auto p-8">
            <div class="flex justify-between items-center mb-8 pb-4 border-b border-gray-200 bg-white p-4 rounded-lg shadow-sm">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900">Standard Cash Advances</h1>
                    <p class="text-gray-500 text-sm mt-1">Manage standard loans and top-ups</p>
                </div>
                <div class="flex items-center space-x-4">
                    <div class="text-right hidden md:block">
                        <p class="text-sm font-bold text-gray-800"><?php echo htmlspecialchars($_SESSION['full_name'] ?? 'User'); ?></p>
                        <p class="text-xs text-gray-500 uppercase"><?php echo htmlspecialchars($_SESSION['username'] ?? 'Dept'); ?></p>
                    </div>
                    <div class="h-10 w-10 rounded-full bg-blue-600 flex items-center justify-center text-white font-bold text-lg shadow">
                        <i class="fas fa-user"></i>
                    </div>
                    <div class="border-l border-gray-300 h-8 mx-2"></div>
                    <a href="../ca/login.php" class="px-4 py-2 bg-red-50 hover:bg-red-100 text-red-600 text-sm font-bold rounded-lg transition flex items-center">
                        <i class="fas fa-sign-out-alt mr-2"></i> Logout
                    </a>
                </div>
            </div>

            <div class="bg-white shadow-xl rounded-lg overflow-hidden border border-gray-200 p-6">
                <div class="flex justify-between items-center mb-4">
                    <form id="filter-form" action="" method="get" class="flex items-end w-1/2">
                        <input type="text" id="main_search" name="search_term" placeholder="Search Loan No, ID, or Name..." class="w-full p-2 border border-gray-300 rounded-l-md text-sm focus:ring-green-500">
                        <button type="submit" class="p-2 bg-blue-600 text-white text-sm font-medium rounded-r-md hover:bg-blue-700">Search</button>
                    </form>
                    
                    <button type="button" class="px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-md hover:bg-green-700" data-toggle="modal" data-target="#fileCAModal">
                        <i class="fas fa-plus-circle mr-2"></i> File Cash Advance
                    </button>
                </div>

                <div id="ca-table-container">
                    <?php echo renderCashAdvanceTable($pdo, $searched_name_or_id); ?>
                </div> 
            </div>
        </main>
    </div>

    <div class="modal fade" id="fileCAModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header bg-gray-50">
                    <h5 class="modal-title font-bold text-xl text-gray-800">File Cash Advance</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body p-6 bg-white">
                    
                    <div class="form-group position-relative mb-2">
                        <label class="font-semibold text-gray-700">Search ID or Employee Name</label>
                        <input type="text" id="modal_account_search" class="form-control form-control-lg border-green-500 shadow-sm" placeholder="Type to search account numbers..." autocomplete="off">
                        <div id="search_results" class="hidden"></div>
                    </div>

                    <div class="mb-4">
                        <input type="checkbox" id="manualEncodeCB" class="mr-2">
                        <label for="manualEncodeCB" class="text-sm font-semibold text-red-600 cursor-pointer">Employee not in database? Check here for manual encoding</label>
                    </div>
                    
                    <hr class="my-4">

                    <form id="saveCAForm">
                        <input type="hidden" name="action" value="save_ca">
                        
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="text-sm font-medium text-gray-600">Date of voucher</label>
                                <input type="date" name="date_of_voucher" class="form-control bg-gray-50" required value="<?php echo date('Y-m-d'); ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="text-sm font-medium text-gray-600">ID</label>
                                <input type="text" id="frm_rgs_id" name="rgs_id" class="form-control bg-gray-100" readonly required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="text-sm font-medium text-gray-600">Employee Name</label>
                                <input type="text" id="frm_name" name="employee_name" class="form-control bg-gray-100" readonly required>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="text-sm font-medium text-gray-600">Hub</label>
                                <input type="text" id="frm_hub" class="form-control bg-gray-100" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="text-sm font-medium text-gray-600">Bank</label>
                                <input type="text" id="frm_bank" class="form-control bg-gray-100" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="text-sm font-medium text-gray-600">Bank Account No.</label>
                                <input type="text" id="frm_account_no" class="form-control bg-gray-100" readonly>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="text-sm font-medium text-gray-600">Account</label>
                                <select id="frm_account_client" name="account_client" class="form-control" required>
                                    <option value="" disabled selected>Select Account...</option>
                                    <option value="ADMIN">ADMIN</option>
                                    <option value="COORDINATOR">COORDINATOR</option>
                                    <option value="2GO EXPRESS INC.">2GO EXPRESS INC.</option>
                                    <option value="AIR FREGHT 21">AIR FREGHT 21</option>
                                    <option value="ENTREGO">ENTREGO</option>
                                    <option value="F2 LOGISTICS">F2 LOGISTICS</option>
                                    <option value="LAZADA">LAZADA</option>
                                    <option value="SCOMMERCE">SCOMMERCE</option>
                                    <option value="SM ONLINE">SM ONLINE</option>
                                    <option value="SOBIDA">SOBIDA</option>
                                    <option value="SPX">SPX</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="text-sm font-medium text-gray-600">1st Payment Date <small class="text-danger">(10/25 or 15/30)</small></label>
                                <input type="date" name="start_payment_date" class="form-control" required>
                            </div>
                        </div>

                        <div class="row bg-green-50 p-3 rounded mb-3 border border-green-200 mx-1">
                            <div class="col-md-12 mb-3">
                                <label class="text-sm font-bold text-gray-700 uppercase border-b border-green-300 pb-1 block">Loan Computation</label>
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="text-sm font-medium text-gray-600">Total Amount</label>
                                <input type="number" step="0.01" id="calc_amount" name="amount" class="form-control border-green-400 font-bold" placeholder="0.00" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="text-sm font-medium text-gray-600">Compute By</label>
                                <select id="calc_mode" name="calc_mode" class="form-control font-semibold text-blue-700">
                                    <option value="by_gives" selected>Input Total Gives</option>
                                    <option value="by_cutoff">Input Amount per Cutoff</option>
                                </select>
                            </div>
                            <div class="col-md-3 mb-3" id="div_cutoff">
                                <label class="text-sm font-medium text-gray-600">Amount per Cutoff</label>
                                <input type="number" step="0.01" id="calc_cutoff_amt" name="cutoff_amt" class="form-control bg-gray-200" placeholder="0.00" readonly>
                            </div>
                            <div class="col-md-2 mb-3">
                                <label class="text-sm font-medium text-gray-600">Gives</label>
                                <input type="number" id="calc_gives" name="gives" class="form-control font-bold text-center" placeholder="e.g. 4" required>
                            </div>
                        </div>

                        <div class="form-group mb-0">
                            <label class="text-sm font-medium text-gray-600">Remarks</label>
                            <textarea name="remarks" class="form-control" rows="2" placeholder="e.g. ONE TIME DEDUCTION"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer bg-gray-50">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" id="btnSaveCA" class="btn btn-success px-4 py-2 font-medium">Save Record</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="scheduleModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content position-relative">
                <div class="modal-header bg-gray-800 text-white">
                    <h5 class="modal-title font-bold" id="schedModalTitle">Loan Schedule & Payments</h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body p-0" style="max-height: 80vh; overflow-y: auto;">
                    <div class="p-4 bg-gray-100 border-b flex justify-between items-center">
                        <div>
                            <h6 class="font-bold text-gray-800 text-lg" id="schedModalEmpName">Name</h6>
                            <p class="text-sm text-gray-600 mb-0" id="schedModalLoanNo">Loan No</p>
                        </div>
                        <div class="text-right">
                            <p class="text-sm text-gray-600 mb-1">Total Loan: <strong class="text-gray-900 text-lg" id="schedModalTotal">₱ 0.00</strong></p>
                            <p class="text-sm text-blue-600 mb-1 hidden" id="schedModalTopUpContainer">Top-up: <strong class="text-lg" id="schedModalTopUp">₱ 0.00</strong></p>
                            <p class="text-sm text-red-600 mb-2 font-bold">Remaining Balance: <strong class="text-xl" id="schedModalRemaining">₱ 0.00</strong></p>
                            
                            <button type="button" class="btn btn-sm btn-outline-warning font-bold mt-1" id="btnCreateShortfall" style="display:none;">
                                <i class="fas fa-calendar-plus"></i> Add Payment Row
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-info font-bold mt-1" id="btnTopUpLoan">
                                <i class="fas fa-plus"></i> Add Additional
                            </button>
                        </div>
                    </div>
                    
                    <table class="table table-bordered mb-0">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="text-xs text-gray-600 uppercase">Exp. Date</th>
                                <th class="text-xs text-gray-600 uppercase text-right">Amt Due</th>
                                <th class="text-xs text-gray-600 uppercase text-center">Date Paid</th>
                                <th class="text-xs text-gray-600 uppercase text-right">Amt Paid</th>
                                <th class="text-xs text-gray-600 uppercase text-center">Status</th>
                                <th class="text-xs text-gray-600 uppercase text-center">Action</th>
                            </tr>
                        </thead>
                        <tbody id="scheduleTableBody">
                        </tbody>
                    </table>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>

                <div id="paymentFormSection" style="display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); z-index: 1050; align-items: center; justify-content: center; border-radius: 0.3rem;">
                    <div class="bg-white p-5 rounded shadow-2xl" style="width: 90%; max-width: 450px;">
                        <h5 class="font-bold text-blue-800 mb-4 border-b pb-2"><i class="fas fa-money-bill-wave"></i> Collect Payment</h5>
                        <form id="collectPaymentForm">
                            <input type="hidden" name="action" value="collect_payment">
                            <input type="hidden" id="pay_sched_id" name="schedule_id">
                            
                            <div class="form-group mb-3">
                                <label class="text-sm font-medium text-gray-700">Date Collected</label>
                                <input type="date" id="pay_date" name="paid_date" class="form-control border-blue-300" required value="<?php echo date('Y-m-d'); ?>">
                            </div>
                            
                            <div class="form-group mb-3">
                                <label class="text-sm font-medium text-gray-700">Amount to Collect</label>
                                <div class="input-group">
                                    <div class="input-group-prepend"><span class="input-group-text bg-blue-100 border-blue-300">₱</span></div>
                                    <input type="number" step="0.01" id="pay_amount" name="amount_paid" class="form-control border-blue-300 bg-gray-100" readonly required>
                                </div>
                            </div>
                            
                            <div class="form-group mb-4">
                                <div class="form-check">
                                    <input type="checkbox" class="form-check-input cursor-pointer" id="editAmountCB">
                                    <label class="form-check-label text-sm text-red-600 font-bold cursor-pointer" for="editAmountCB">Change Amount?</label>
                                </div>
                            </div>
                            
                            <div class="text-right border-t pt-3">
                                <button type="button" class="btn btn-secondary px-4 mr-2" onclick="$('#paymentFormSection').fadeOut('fast')">Cancel</button>
                                <button type="button" id="btnSubmitPayment" class="btn btn-primary px-4 font-bold shadow">Confirm Payment</button>
                            </div>
                        </form>
                    </div>
                </div>

            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.6.0/js/bootstrap.bundle.min.js"></script>

    <script>
        $(document).ready(function() {
            
            // -------------------------------------------------------------
            // LIVE SEARCH
            // -------------------------------------------------------------
            let typingTimer;
            const doneTypingInterval = 300;

            $('#modal_account_search').on('keyup', function() {
                clearTimeout(typingTimer);
                const query = $(this).val();
                if (query.length > 2) {
                    typingTimer = setTimeout(() => { searchAccount(query); }, doneTypingInterval);
                } else {
                    $('#search_results').hide().empty();
                }
            });

            function searchAccount(query) {
                $.ajax({
                    url: 'cash_advances.php',
                    type: 'GET',
                    data: { ajax_search_account: 1, term: query },
                    dataType: 'json',
                    success: function(data) {
                        if (data && data.error) return;
                        
                        const resultsBox = $('#search_results');
                        resultsBox.empty();
                        
                        if (data.length > 0) {
                            data.forEach(item => {
                                const div = $(`<div class="search-item">
                                    <strong>${item.rider_ops_id}</strong> - ${item.full_name} 
                                    <span class="text-muted text-sm ml-2">(${item.hub})</span>
                                </div>`);
                                
                                div.on('click', function() {
                                    $('#frm_rgs_id').val(item.rider_ops_id);
                                    $('#frm_name').val(item.full_name);
                                    $('#frm_hub').val(item.hub);
                                    $('#frm_bank').val(item.bank);
                                    $('#frm_account_no').val(item.account_number);
                                    
                                    $('#modal_account_search').val('');
                                    resultsBox.hide();
                                });
                                resultsBox.append(div);
                            });
                            resultsBox.removeClass('hidden').show();
                        } else {
                            resultsBox.html('<div class="p-2 text-red-500">No account number found.</div>').removeClass('hidden').show();
                        }
                    }
                });
            }

            $(document).on('click', function (e) {
                if ($(e.target).closest("#modal_account_search, #search_results").length === 0) {
                    $("#search_results").hide();
                }
            });

            $('#manualEncodeCB').change(function() {
                if ($(this).is(':checked')) {
                    $('#frm_rgs_id, #frm_name, #frm_hub, #frm_bank, #frm_account_no')
                        .prop('readonly', false).removeClass('bg-gray-100').val('');
                    $('#modal_account_search').prop('disabled', true).val('');
                    $('#search_results').hide();
                } else {
                    $('#frm_rgs_id, #frm_name, #frm_hub, #frm_bank, #frm_account_no')
                        .prop('readonly', true).addClass('bg-gray-100').val('');
                    $('#modal_account_search').prop('disabled', false);
                }
            });

            // -------------------------------------------------------------
            // COMPUTATION LOGIC
            // -------------------------------------------------------------
            $('#calc_mode').change(function() {
                if ($(this).val() === 'by_cutoff') {
                    $('#calc_cutoff_amt').prop('readonly', false).removeClass('bg-gray-200').val('');
                    $('#calc_gives').prop('readonly', true).addClass('bg-gray-200').val('');
                } else {
                    $('#calc_gives').prop('readonly', false).removeClass('bg-gray-200').val('');
                    $('#calc_cutoff_amt').prop('readonly', true).addClass('bg-gray-200').val('');
                }
                calculateLoan();
            });

            $('#calc_amount, #calc_cutoff_amt, #calc_gives').on('input', function() {
                calculateLoan();
            });

            function calculateLoan() {
                let total = parseFloat($('#calc_amount').val()) || 0;
                let mode = $('#calc_mode').val();
                
                if (mode === 'by_cutoff') {
                    let perCutoff = parseFloat($('#calc_cutoff_amt').val()) || 0;
                    if (total > 0 && perCutoff > 0) {
                        let gives = Math.ceil(total / perCutoff);
                        $('#calc_gives').val(gives);
                    } else {
                        $('#calc_gives').val('');
                    }
                } else {
                    let gives = parseFloat($('#calc_gives').val()) || 0;
                    if (total > 0 && gives > 0) {
                        let perCutoff = (total / gives).toFixed(2);
                        $('#calc_cutoff_amt').val(perCutoff);
                    } else {
                        $('#calc_cutoff_amt').val('');
                    }
                }
            }

            // -------------------------------------------------------------
            // FORM SUBMISSION
            // -------------------------------------------------------------
            $('#btnSaveCA').click(function() {
                if (!$('#frm_rgs_id').val() || !$('#frm_name').val()) {
                    alert("Please provide the ID and Employee Name.");
                    return;
                }
                if (!$('#frm_account_client').val()) {
                    alert("Please select an Account from the dropdown.");
                    return;
                }
                if ($('#calc_mode').val() === 'by_cutoff' && !$('#calc_cutoff_amt').val()) {
                    alert("Please input the Amount per Cutoff.");
                    return;
                }

                const formData = $('#saveCAForm').serialize();

                $.ajax({
                    url: 'cash_advances.php',
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    success: function(response) {
                        if(response.status === 'success') {
                            alert("Cash Advance & Schedule recorded successfully!");
                            $('#fileCAModal').modal('hide');
                            $('#saveCAForm')[0].reset();
                            location.reload(); 
                        } else {
                            alert("Error: " + response.message);
                        }
                    },
                    error: function() {
                        alert("An error occurred while saving.");
                    }
                });
            });
            
            // -------------------------------------------------------------
            // TABLE FILTER
            // -------------------------------------------------------------
            $('#filter-form').on('submit', function(event) {
                event.preventDefault();
                const formData = $(this).serialize();
                const url = 'cash_advances.php?' + formData + '&ajax=1';

                const container = $('#ca-table-container');
                container.html('<div class="text-center py-10"><i class="fas fa-spinner fa-spin mr-2"></i> Loading...</div>');

                $.ajax({
                    url: url,
                    type: 'GET',
                    success: function(response) {
                        container.html($(response).filter('#ca-table-container').html());
                        history.pushState(null, '', url.replace('&ajax=1', ''));
                    }
                });
            });

            // -------------------------------------------------------------
            // SCHEDULE & BALANCING
            // -------------------------------------------------------------
            function loadScheduleData(loanNo, empName) {
                $('#paymentFormSection').hide();
                $('#scheduleTableBody').html('<tr><td colspan="6" class="text-center py-4"><i class="fas fa-spinner fa-spin"></i> Loading...</td></tr>');
                
                $.ajax({
                    url: 'cash_advances.php',
                    type: 'GET',
                    data: { ajax_get_schedule: 1, loan_no: loanNo },
                    dataType: 'json',
                    success: function(data) {
                        const tbody = $('#scheduleTableBody');
                        tbody.empty();
                        
                        if (data.length > 0) {
                            let totalLoan = parseFloat(data[0].total_loan);
                            let topUpAmount = parseFloat(data[0].topped_up_amount || 0);
                            let totalPaid = 0;
                            let hasPending = false;

                            data.forEach(row => {
                                if(row.status === 'Paid') {
                                    totalPaid += parseFloat(row.amount_paid || 0);
                                }
                                if(row.status === 'Pending') {
                                    hasPending = true;
                                }
                            });

                            let remaining = totalLoan - totalPaid;
                            
                            $('#schedModalTotal').text('₱ ' + totalLoan.toFixed(2));
                            $('#schedModalRemaining').text('₱ ' + remaining.toFixed(2));

                            if (topUpAmount > 0) {
                                $('#schedModalTopUp').text('+ ₱ ' + topUpAmount.toFixed(2));
                                $('#schedModalTopUpContainer').removeClass('hidden');
                            } else {
                                $('#schedModalTopUpContainer').addClass('hidden');
                            }

                            if (remaining > 0.01 && !hasPending) {
                                $('#btnCreateShortfall').show();
                            } else {
                                $('#btnCreateShortfall').hide();
                            }

                            data.forEach(row => {
                                const statusBadge = row.status === 'Pending' 
                                    ? '<span class="badge badge-warning">Pending</span>'
                                    : '<span class="badge badge-success">Paid</span>';
                                
                                const actionBtn = row.status === 'Pending'
                                    ? `<button class="btn btn-sm btn-outline-primary font-bold btn-pay-sched" data-id="${row.id}" data-amount="${row.amount_due}">Collect</button>`
                                    : '<span class="text-success"><i class="fas fa-check-circle"></i></span>';

                                const paidDateDisplay = row.paid_date ? row.paid_date : '-';
                                const amountPaidDisplay = row.status === 'Paid' ? `₱ ${parseFloat(row.amount_paid).toFixed(2)}` : '-';

                                tbody.append(`
                                    <tr>
                                        <td class="font-medium align-middle">${row.payment_date}</td>
                                        <td class="text-right text-gray-700 font-bold align-middle">₱ ${parseFloat(row.amount_due).toFixed(2)}</td>
                                        <td class="text-center align-middle">${paidDateDisplay}</td>
                                        <td class="text-right text-green-700 font-bold align-middle">${amountPaidDisplay}</td>
                                        <td class="text-center align-middle">${statusBadge}</td>
                                        <td class="text-center align-middle">${actionBtn}</td>
                                    </tr>
                                `);
                            });
                        } else {
                            tbody.html('<tr><td colspan="6" class="text-center text-gray-500">No schedule found for this loan.</td></tr>');
                        }
                    }
                });
            }

            $(document).on('click', '.btn-view-schedule', function() {
                const loanNo = $(this).data('loan');
                const empName = $(this).data('name');
                
                $('#schedModalTitle').text('Loan Schedule: ' + loanNo);
                $('#schedModalEmpName').text(empName);
                $('#schedModalLoanNo').text(loanNo);
                
                $('#scheduleModal').data('active-loan', loanNo);
                $('#scheduleModal').data('active-name', empName);

                $('#scheduleModal').modal('show');
                loadScheduleData(loanNo, empName);
            });

            $(document).on('click', '.btn-pay-sched', function() {
                const schedId = $(this).data('id');
                const amountDue = parseFloat($(this).data('amount')).toFixed(2);
                
                $('#pay_sched_id').val(schedId);
                $('#pay_amount').val(amountDue).data('original', amountDue).prop('readonly', true).addClass('bg-gray-100');
                $('#editAmountCB').prop('checked', false);
                $('#pay_date').val(new Date().toISOString().split('T')[0]);
                
                $('#paymentFormSection').css('display', 'flex').hide().fadeIn('fast');
            });

            $('#editAmountCB').change(function() {
                if ($(this).is(':checked')) {
                    $('#pay_amount').prop('readonly', false).removeClass('bg-gray-100').focus();
                } else {
                    const origAmount = $('#pay_amount').data('original');
                    $('#pay_amount').prop('readonly', true).addClass('bg-gray-100').val(origAmount);
                }
            });

            $('#btnSubmitPayment').click(function() {
                const formData = $('#collectPaymentForm').serialize();
                
                if(!$('#pay_amount').val() || $('#pay_amount').val() <= 0) {
                    alert("Please enter a valid payment amount.");
                    return;
                }

                $(this).prop('disabled', true).text('Saving...');

                $.ajax({
                    url: 'cash_advances.php',
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    success: function(response) {
                        $('#btnSubmitPayment').prop('disabled', false).text('Confirm Payment');
                        if(response.status === 'success') {
                            $('#paymentFormSection').fadeOut('fast');
                            const activeLoan = $('#scheduleModal').data('active-loan');
                            const activeName = $('#scheduleModal').data('active-name');
                            loadScheduleData(activeLoan, activeName);
                            $('#filter-form').submit();
                        } else {
                            alert("Error: " + response.message);
                        }
                    },
                    error: function() {
                        $('#btnSubmitPayment').prop('disabled', false).text('Confirm Payment');
                        alert("An error occurred while saving the payment.");
                    }
                });
            });

            $('#btnCreateShortfall').click(function() {
                const loanNo = $('#scheduleModal').data('active-loan');
                if(confirm("Generate a new payment schedule row for the remaining balance?")) {
                    $.ajax({
                        url: 'cash_advances.php',
                        type: 'POST',
                        data: {
                            action: 'add_shortfall_schedule',
                            loan_no: loanNo
                        },
                        dataType: 'json',
                        success: function(response) {
                            if(response.status === 'success') {
                                const activeName = $('#scheduleModal').data('active-name');
                                loadScheduleData(loanNo, activeName);
                                $('#filter-form').submit(); 
                            } else {
                                alert("Error: " + response.message);
                            }
                        },
                        error: function() {
                            alert("A server error occurred while adding the schedule row.");
                        }
                    });
                }
            });

            $('#btnTopUpLoan').click(function() {
                const loanNo = $('#scheduleModal').data('active-loan');
                const additionalAmount = prompt("Enter the ADDITIONAL base amount to add to this loan:");
                
                if (additionalAmount !== null && additionalAmount !== "" && !isNaN(additionalAmount)) {
                    if(confirm("Are you sure you want to top-up ₱" + additionalAmount + " to " + loanNo + "?")) {
                        $.ajax({
                            url: 'cash_advances.php',
                            type: 'POST',
                            data: {
                                action: 'topup_ca',
                                loan_no: loanNo,
                                additional_amount: additionalAmount
                            },
                            dataType: 'json',
                            success: function(response) {
                                if(response.status === 'success') {
                                    alert("Additional loan applied successfully!");
                                    const activeName = $('#scheduleModal').data('active-name');
                                    loadScheduleData(loanNo, activeName);
                                    $('#filter-form').submit(); 
                                } else {
                                    alert("Error: " + response.message);
                                }
                            },
                            error: function() {
                                alert("A server error occurred while applying the top-up.");
                            }
                        });
                    }
                }
            });

        });
    </script>
</body>
</html>