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

require_once 'db_connect.php';

if (!isset($_GET['loan_no'])) {
    die("Loan Number is required.");
}

$loan_no = $_GET['loan_no'];

// Fetch the main cash advance data
$sql = "SELECT ca.*, 
               REPLACE(an.full_name, '?', 'Ñ') AS linked_name_cor
        FROM `cash_advances` ca
        LEFT JOIN `account_numbers` an ON ca.rider_ops_id = an.rider_ops_id
        WHERE ca.loan_no = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$loan_no]);
$ca_data = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$ca_data) {
    die("Cash Advance record not found.");
}

$display_name = !empty($ca_data["linked_name_cor"]) ? $ca_data["linked_name_cor"] : str_replace('?', 'Ñ', $ca_data["name"]);

// Fetch the schedule
$sql_sched = "SELECT * FROM `cash_advance_schedule` WHERE loan_no = ? ORDER BY payment_date ASC";
$stmt_sched = $pdo->prepare($sql_sched);
$stmt_sched->execute([$loan_no]);
$schedule = $stmt_sched->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Disclosure Statement - <?php echo htmlspecialchars($loan_no); ?></title>
    <style>
        body {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            color: #333;
            line-height: 1.6;
            font-size: 14px;
            padding: 40px;
            max-width: 800px;
            margin: 0 auto;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 2px solid #2c3e50;
            padding-bottom: 10px;
        }
        .header h1 { margin: 0; color: #2c3e50; font-size: 24px; text-transform: uppercase; }
        .header h2 { margin: 5px 0 0 0; color: #7f8c8d; font-size: 16px; font-weight: normal; }
        .details-table { width: 100%; margin-bottom: 20px; border-collapse: collapse; }
        .details-table td { padding: 8px; vertical-align: top; }
        .details-table td:first-child { font-weight: bold; width: 30%; }
        .schedule-table { width: 100%; border-collapse: collapse; margin-top: 15px; margin-bottom: 30px; }
        .schedule-table th, .schedule-table td { border: 1px solid #bdc3c7; padding: 10px; text-align: left; }
        .schedule-table th { background-color: #ecf0f1; color: #2c3e50; }
        .amount { text-align: right; font-family: monospace; font-size: 15px; }
        .signatures { margin-top: 60px; width: 100%; display: flex; justify-content: space-between; }
        .signature-block { width: 45%; }
        .signature-line { border-bottom: 1px solid #000; margin-bottom: 5px; height: 50px; }
        
        @media print {
            body { padding: 0; }
            .no-print { display: none; }
        }
    </style>
</head>
<body onload="window.print()">
    <button class="no-print" onclick="window.print()" style="padding: 10px 20px; margin-bottom: 20px; cursor: pointer;">Print Disclosure Statement</button>
    
    <div class="header">
        <h1>Disclosure Statement</h1>
        <h2>Cash Advance & Salary Deduction Authorization</h2>
    </div>

    <div class="content">
        <p>This Disclosure Statement (hereinafter referred to as the "Agreement") is entered into by and between <strong>RGServe</strong> (hereinafter referred to as the "Company") and the employee named below.</p>
        
        <table class="details-table">
            <tr><td>Employee Name:</td><td><strong><?php echo htmlspecialchars($display_name); ?></strong></td></tr>
            <tr><td>ID:</td><td><?php echo htmlspecialchars($ca_data['rider_ops_id']); ?></td></tr>
            <tr><td>Account:</td><td><?php echo htmlspecialchars($ca_data['account']); ?></td></tr>
            <tr><td>Loan Number:</td><td><?php echo htmlspecialchars($ca_data['loan_no']); ?></td></tr>
            <tr><td>Total Cash Advance:</td><td><strong>₱ <?php echo number_format($ca_data['amount'], 2); ?></strong></td></tr>
        </table>

        <p>The Employee acknowledges receipt of the total cash advance amount stated above. The Employee hereby voluntarily authorizes the Company to deduct the corresponding installment amounts from their salary/wages according to the payment schedule outlined below until the cash advance is fully paid.</p>

        <table class="schedule-table">
            <thead>
                <tr>
                    <th>Installment #</th>
                    <th>Payment Date</th>
                    <th style="text-align: right;">Amount Due</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $count = 1;
                foreach ($schedule as $row): ?>
                <tr>
                    <td><?php echo $count++; ?></td>
                    <td><?php echo date('F d, Y', strtotime($row['payment_date'])); ?></td>
                    <td class="amount">₱ <?php echo number_format($row['amount_due'], 2); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr>
                    <th colspan="2" style="text-align: right;">Total Balance:</th>
                    <th class="amount" style="background-color: #ecf0f1; text-align: right;">₱ <?php echo number_format($ca_data['amount'], 2); ?></th>
                </tr>
            </tfoot>
        </table>

        <p>In the event of resignation, termination, or separation from the Company before the full amount is settled, the Employee authorizes the Company to deduct the remaining outstanding balance from their final pay, separation pay, or any other monetary benefits due to the Employee.</p>
    </div>

    <div class="signatures">
        <div class="signature-block">
            <div class="signature-line"></div>
            <strong><?php echo htmlspecialchars($display_name); ?></strong><br>
            Employee Signature over Printed Name<br>
            Date: __________________
        </div>
        <div class="signature-block">
            <div class="signature-line"></div>
            <strong>Authorized Representative</strong><br>
            For RGServe<br>
            Date: __________________
        </div>
    </div>
</body>
</html>