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

// Auto-migrate: add 'released' to status enum if not present
$enumRow = $conn->query("SHOW COLUMNS FROM loans LIKE 'status'")->fetch_assoc();
if ($enumRow && strpos($enumRow['Type'], 'released') === false) {
    $conn->query("ALTER TABLE loans MODIFY COLUMN status ENUM('pending','approved','released','paid','overdue') DEFAULT 'pending'");
}
// Auto-migrate: renewed_from column
$col = $conn->query("SHOW COLUMNS FROM loans LIKE 'renewed_from'");
if ($col && $col->num_rows === 0) {
    $conn->query("ALTER TABLE loans ADD COLUMN renewed_from INT DEFAULT NULL AFTER status");
    $conn->query("ALTER TABLE loans ADD CONSTRAINT fk_renewed_from FOREIGN KEY (renewed_from) REFERENCES loans(id) ON DELETE SET NULL");
}

$id   = intval($_GET['id'] ?? 0);
$loan = fetchOne($conn,
    "SELECT l.*, b.first_name, b.last_name, b.contact, b.photo FROM loans l
     JOIN borrowers b ON l.borrower_id = b.id WHERE l.id = ?", [$id], "i");
if (!$loan) { header('Location: /cash_lending/mobile/loans.php'); exit(); }

$payments = fetchAll($conn,
    "SELECT * FROM payments WHERE loan_id = ? ORDER BY payment_date DESC", [$id], "i");

$renewal = canRenewLoan($conn, $loan);

$page_title = 'Loan Details';
$active_nav = 'loans';
$badge = match($loan['status']) {
    'paid'     => 'badge-success',
    'overdue'  => 'badge-danger',
    'released' => 'badge-primary',
    'approved' => 'badge-info',
    default    => 'badge-warning'
};

include 'header.php';
?>

<!-- Borrower card -->
<div class="card mb-3">
    <div class="card-body">
        <div class="d-flex align-center gap-2 mb-2">
            <?php
            $initials  = urlencode($loan['first_name'] . '+' . $loan['last_name']);
            $photo_src = !empty($loan['photo']) && file_exists($loan['photo'])
                ? '/cash_lending/' . $loan['photo']
                : "https://ui-avatars.com/api/?name={$initials}&size=44&background=1a56db&color=fff&rounded=true";
            ?>
            <img src="<?php echo htmlspecialchars($photo_src); ?>"
                 style="width:44px;height:44px;border-radius:12px;object-fit:cover;" alt="">
            <div>
                <div class="fw-bold"><?php echo htmlspecialchars($loan['first_name'] . ' ' . $loan['last_name']); ?></div>
                <div class="text-muted" style="font-size:12px;"><?php echo htmlspecialchars($loan['contact']); ?></div>
            </div>
            <div style="margin-left:auto;">
                <span class="badge <?php echo $badge; ?>"><?php echo ucfirst($loan['status']); ?></span>
            </div>
        </div>
    </div>
</div>

<!-- Summary tiles -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:16px;">
    <?php foreach ([
        ['Loan Amount',   '₱' . number_format($loan['loan_amount'],2),       '#dbeafe','#1a56db'],
        ['Balance',       '₱' . number_format($loan['balance'],2),            '#fee2e2','#e02424'],
        ['Interest Rate', $loan['interest_rate'] . '% / mo',                  '#d1fae5','#057a55'],
        ['Installment',   '₱' . number_format($loan['installment_amount'],2), '#fef3c7','#c27803'],
    ] as [$lbl, $val, $bg, $clr]): ?>
        <div style="background:<?php echo $bg; ?>;border-radius:12px;padding:14px;">
            <div style="font-size:11px;font-weight:600;color:<?php echo $clr; ?>;opacity:.8;text-transform:uppercase;"><?php echo $lbl; ?></div>
            <div style="font-size:20px;font-weight:800;color:<?php echo $clr; ?>;"><?php echo $val; ?></div>
        </div>
    <?php endforeach; ?>
</div>

<!-- Loan details -->
<div class="card mb-3">
    <div class="card-body" style="font-size:13px;">
        <?php foreach ([
            ['Application Date', date('M d, Y', strtotime($loan['created_at']))],
            ['Release Date',  in_array($loan['status'], ['pending','approved']) ? '— (set on release)' : date('M d, Y', strtotime($loan['release_date']))],
            ['Due Date',      in_array($loan['status'], ['pending','approved']) ? '— (set on release)' : date('M d, Y', strtotime($loan['due_date']))],
            ['Payment Mode',  ucfirst($loan['payment_mode'])],
            ['Total Interest','₱' . number_format($loan['total_interest'],2)],
            ['Total Payable', '₱' . number_format($loan['total_payable'],2)],
        ] as [$lbl, $val]): ?>
            <div class="d-flex justify-between" style="padding:7px 0;border-bottom:1px solid var(--border);">
                <span class="text-muted"><?php echo $lbl; ?></span>
                <span class="fw-bold"><?php echo htmlspecialchars($val); ?></span>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Action buttons -->
<div style="display:flex;flex-direction:column;gap:10px;margin-bottom:16px;">

    <?php if (in_array($loan['status'], ['released', 'overdue'])): ?>
        <a href="/cash_lending/mobile/add-payment.php?loan_id=<?php echo $id; ?>"
           class="btn btn-success btn-block">
            <i class="fas fa-money-bill-wave"></i> Record Payment
        </a>
    <?php endif; ?>

    <?php if ($loan['status'] === 'pending' && isAdmin()): ?>
        <button class="btn btn-info btn-block text-white" onclick="approveLoan(<?php echo $id; ?>)">
            <i class="fas fa-check"></i> Approve Loan
        </button>
    <?php endif; ?>

    <?php if ($loan['status'] === 'approved' && isAdmin()): ?>
        <button class="btn btn-primary btn-block" onclick="releaseLoan(<?php echo $id; ?>)">
            <i class="fas fa-hand-holding-usd"></i> Mark as Released
        </button>
    <?php endif; ?>

    <?php if ($renewal['allowed']): ?>
        <a href="/cash_lending/renew-loan.php?loan_id=<?php echo $id; ?>"
           class="btn btn-warning btn-block">
            <i class="fas fa-sync-alt"></i> Renew Loan
        </a>
    <?php elseif (in_array($loan['status'], ['released','overdue','paid'])): ?>
        <button class="btn btn-warning btn-block" disabled
                style="opacity:.6;" title="<?php echo htmlspecialchars($renewal['reason']); ?>">
            <i class="fas fa-sync-alt"></i> Renew Loan
        </button>
        <div style="background:#fffbeb;border:1px solid #fcd34d;border-radius:10px;padding:10px 12px;font-size:12px;color:#92400e;">
            <i class="fas fa-lock"></i> <strong>Renewal blocked:</strong> <?php echo htmlspecialchars($renewal['reason']); ?>
        </div>
    <?php endif; ?>

</div>

<!-- Payment history -->
<div class="section-title">Payment History</div>
<div class="card mb-3">
    <?php if (!empty($payments)): ?>
        <?php foreach ($payments as $p): ?>
            <div class="list-row">
                <div class="row-info">
                    <div class="row-name">₱<?php echo number_format($p['amount'],2); ?></div>
                    <div class="row-sub">
                        <?php echo date('M d, Y', strtotime($p['payment_date'])); ?>
                        · <?php echo htmlspecialchars($p['receipt_number'] ?? '—'); ?>
                        <?php if (!empty($p['payment_method'])): ?>
                            · <?php echo htmlspecialchars($p['payment_method']); ?>
                        <?php endif; ?>
                    </div>
                </div>
                <span class="badge badge-success">Paid</span>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="empty-state"><i class="fas fa-receipt"></i><p>No payments yet</p></div>
    <?php endif; ?>
</div>

<?php include 'footer.php'; ?>

<script>
function approveLoan(id) {
    if (!confirm('Approve this loan?')) return;
    fetch('/cash_lending/api/approve-loan.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'id=' + id
    }).then(r => r.json()).then(d => { if (d.success) location.reload(); else alert(d.message); });
}

function releaseLoan(id) {
    if (!confirm('Mark this loan as Released? This means cash has been handed to the borrower.')) return;
    fetch('/cash_lending/api/release-loan.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'id=' + id
    }).then(r => r.json()).then(d => { if (d.success) location.reload(); else alert(d.message); });
}
</script>
