<?php
require_once 'config/db.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
requireLogin();

// Support both ?id= (payment) and ?loan_id= (loan summary)
$payment_id = intval($_GET['id'] ?? 0);
$loan_id    = intval($_GET['loan_id'] ?? 0);

if ($payment_id) {
    $payment = fetchOne($conn,
        "SELECT p.*, l.loan_amount, l.interest_rate, l.term, l.payment_mode, l.total_payable,
                l.installment_amount, l.balance as loan_balance, l.release_date, l.due_date,
                b.first_name, b.last_name, b.address, b.contact, b.id_type, b.id_number, b.photo
         FROM payments p
         JOIN loans l ON p.loan_id=l.id
         JOIN borrowers b ON l.borrower_id=b.id
         WHERE p.id=?", [$payment_id], "i");
    if (!$payment) { header('Location: /cash_lending/payments.php'); exit(); }
    $loan_id_used = $payment['loan_id'];
} elseif ($loan_id) {
    $loan = fetchOne($conn,
        "SELECT l.*, b.first_name, b.last_name, b.address, b.contact, b.id_type, b.id_number, b.photo
         FROM loans l JOIN borrowers b ON l.borrower_id=b.id WHERE l.id=?",
        [$loan_id], "i");
    if (!$loan) { header('Location: /cash_lending/loans.php'); exit(); }
    $payment = null;
    $loan_id_used = $loan_id;
} else {
    header('Location: /cash_lending/payments.php'); exit();
}

$settings     = getSettings($conn);
$company_name = $settings['company_name'] ?? 'Cash Lending System';
$company_phone= $settings['phone'] ?? '';
$company_addr = $settings['address'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Receipt — <?php echo htmlspecialchars($company_name); ?></title>
    <style>
        * { box-sizing:border-box; margin:0; padding:0; }
        body { font-family: 'Segoe UI', sans-serif; font-size:13px; background:#f0f2f5; }
        .receipt-wrapper { max-width:420px; margin:30px auto; background:#fff;
                           border-radius:12px; box-shadow:0 4px 20px rgba(0,0,0,.12); overflow:hidden; }
        .receipt-header { background:linear-gradient(135deg,#1a56db,#3b82f6); color:#fff; padding:24px 20px; text-align:center; }
        .receipt-header h2 { font-size:18px; font-weight:800; margin-bottom:4px; }
        .receipt-header p  { font-size:12px; opacity:.8; }
        .receipt-badge { display:inline-block; background:rgba(255,255,255,.2); padding:4px 14px;
                         border-radius:20px; font-size:12px; font-weight:700; margin-top:8px; }
        .receipt-body { padding:20px; }
        .section-label { font-size:10px; font-weight:700; color:#9ca3af; text-transform:uppercase;
                         letter-spacing:.5px; margin:16px 0 8px; }
        .info-row { display:flex; justify-content:space-between; align-items:flex-start;
                    padding:6px 0; border-bottom:1px dashed #f3f4f6; font-size:13px; }
        .info-row:last-child { border-bottom:none; }
        .info-row .label { color:#6b7280; }
        .info-row .value { font-weight:600; text-align:right; max-width:55%; word-break:break-word; }
        .amount-box { background:#f0fdf4; border:2px solid #bbf7d0; border-radius:10px;
                      padding:16px; text-align:center; margin:16px 0; }
        .amount-box .amount { font-size:32px; font-weight:800; color:#15803d; }
        .amount-box .label  { font-size:12px; color:#6b7280; margin-top:2px; }
        .sig-area { margin-top:24px; display:grid; grid-template-columns:1fr 1fr; gap:20px; }
        .sig-box  { text-align:center; }
        .sig-line { border-top:1.5px solid #374151; margin-top:40px; padding-top:6px;
                    font-size:11px; color:#6b7280; }
        .receipt-footer { background:#f9fafb; border-top:1px dashed #e5e7eb;
                          padding:14px 20px; text-align:center; }
        .receipt-footer p { font-size:11px; color:#9ca3af; }
        .receipt-footer .thank-you { font-size:14px; font-weight:700; color:#374151; margin-bottom:4px; }
        .action-bar { display:flex; justify-content:center; gap:10px; margin:20px auto; max-width:420px; padding: 0 16px; }
        .back-btn  { padding:10px 20px; background:#fff; color:#374151; border:1.5px solid #d1d5db;
                     border-radius:8px; font-size:14px; font-weight:600; cursor:pointer; text-decoration:none;
                     display:inline-flex; align-items:center; gap:6px; }
        .back-btn:hover { background:#f9fafb; }
        .print-btn { padding:10px 28px; background:#1a56db; color:#fff; border:none; border-radius:8px;
                     font-size:14px; font-weight:700; cursor:pointer; display:inline-flex; align-items:center; gap:6px; }
        @media print {
            body { background:#fff; }
            .receipt-wrapper { box-shadow:none; border-radius:0; margin:0; max-width:100%; }
            .action-bar { display:none; }
        }
    </style>
</head>
<body>

<div class="action-bar">
    <a href="/cash_lending/loan-details.php?id=<?php echo $loan_id_used; ?>" class="back-btn">
        &#8592; Back to Loan
    </a>
    <button class="print-btn" onclick="window.print()">🖨️ Print Receipt</button>
</div>

<div class="receipt-wrapper">
    <div class="receipt-header">
        <h2><?php echo htmlspecialchars($company_name); ?></h2>
        <?php if ($company_phone): ?><p><?php echo htmlspecialchars($company_phone); ?></p><?php endif; ?>
        <?php if ($company_addr): ?><p><?php echo htmlspecialchars($company_addr); ?></p><?php endif; ?>
        <div class="receipt-badge">
            <?php echo $payment ? 'OFFICIAL RECEIPT' : 'LOAN CONTRACT RECEIPT'; ?>
        </div>
    </div>

    <div class="receipt-body">
        <?php if ($payment): ?>
        <!-- Payment receipt -->
        <div class="amount-box">
            <div class="amount">₱<?php echo number_format($payment['amount'],2); ?></div>
            <div class="label">Payment Amount</div>
            <?php if ($payment['penalty_paid'] > 0): ?>
                <div style="font-size:12px;color:#dc2626;margin-top:4px;">
                    + ₱<?php echo number_format($payment['penalty_paid'],2); ?> penalty
                </div>
            <?php endif; ?>
        </div>

        <div class="section-label">Receipt Information</div>
        <div class="info-row"><span class="label">Receipt #</span><span class="value"><?php echo htmlspecialchars($payment['receipt_number']); ?></span></div>
        <div class="info-row"><span class="label">Date</span><span class="value"><?php echo date('F j, Y', strtotime($payment['payment_date'])); ?></span></div>
        <div class="info-row"><span class="label">Method</span><span class="value"><?php echo htmlspecialchars($payment['payment_method']??'Cash'); ?></span></div>
        <?php if ($payment['notes']): ?>
        <div class="info-row"><span class="label">Notes</span><span class="value"><?php echo htmlspecialchars($payment['notes']); ?></span></div>
        <?php endif; ?>

        <div class="section-label">Borrower</div>
        <div class="info-row"><span class="label">Name</span><span class="value"><?php echo htmlspecialchars($payment['first_name'].' '.$payment['last_name']); ?></span></div>
        <div class="info-row"><span class="label">Address</span><span class="value"><?php echo htmlspecialchars($payment['address']); ?></span></div>
        <div class="info-row"><span class="label">Contact</span><span class="value"><?php echo htmlspecialchars($payment['contact']); ?></span></div>

        <div class="section-label">Loan Details</div>
        <div class="info-row"><span class="label">Loan Amount</span><span class="value">₱<?php echo number_format($payment['loan_amount'],2); ?></span></div>
        <div class="info-row"><span class="label">Remaining Balance</span><span class="value">₱<?php echo number_format($payment['loan_balance'],2); ?></span></div>

        <?php else:
        // Loan contract receipt
        ?>
        <div class="amount-box">
            <div class="amount">₱<?php echo number_format($loan['loan_amount'],2); ?></div>
            <div class="label">Loan Amount Released</div>
        </div>

        <div class="section-label">Borrower</div>
        <div class="info-row"><span class="label">Name</span><span class="value"><?php echo htmlspecialchars($loan['first_name'].' '.$loan['last_name']); ?></span></div>
        <div class="info-row"><span class="label">Address</span><span class="value"><?php echo htmlspecialchars($loan['address']); ?></span></div>
        <div class="info-row"><span class="label">Contact</span><span class="value"><?php echo htmlspecialchars($loan['contact']); ?></span></div>
        <div class="info-row"><span class="label">ID Type</span><span class="value"><?php echo htmlspecialchars($loan['id_type']); ?></span></div>
        <div class="info-row"><span class="label">ID Number</span><span class="value"><?php echo htmlspecialchars($loan['id_number']); ?></span></div>

        <div class="section-label">Loan Terms</div>
        <div class="info-row"><span class="label">Interest Rate</span><span class="value"><?php echo $loan['interest_rate']; ?>%</span></div>
        <div class="info-row"><span class="label">Term</span><span class="value"><?php echo $loan['term']; ?> <?php echo $loan['payment_mode']==='daily'?'days':($loan['payment_mode']==='weekly'?'weeks':'months'); ?></span></div>
        <div class="info-row"><span class="label">Payment Mode</span><span class="value"><?php echo ucfirst($loan['payment_mode']); ?></span></div>
        <div class="info-row"><span class="label">Installment</span><span class="value">₱<?php echo number_format($loan['installment_amount'],2); ?></span></div>
        <div class="info-row"><span class="label">Total Payable</span><span class="value">₱<?php echo number_format($loan['total_payable'],2); ?></span></div>
        <div class="info-row"><span class="label">Release Date</span><span class="value"><?php echo in_array($loan['status'],['pending','approved']) ? '— (pending approval)' : date('F j, Y', strtotime($loan['release_date'])); ?></span></div>
        <div class="info-row"><span class="label">Due Date</span><span class="value"><?php echo in_array($loan['status'],['pending','approved']) ? '— (pending approval)' : date('F j, Y', strtotime($loan['due_date'])); ?></span></div>
        <?php endif; ?>

        <!-- Signature area -->
        <div class="sig-area">
            <div class="sig-box">
                <div class="sig-line">Received by / Staff</div>
            </div>
            <div class="sig-box">
                <div class="sig-line">Borrower's Signature</div>
            </div>
        </div>
    </div>

    <div class="receipt-footer">
        <p class="thank-you">Thank you!</p>
        <p>Keep this receipt for your records.</p>
        <p style="margin-top:6px;">Printed: <?php echo date('F j, Y h:i A'); ?></p>
    </div>
</div>

</body>
</html>
