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

$status  = $_GET['status'] ?? '';
$search  = trim($_GET['search'] ?? '');
$grouped = getLoansGrouped($conn, $status, $search);

$page_title = 'Loans';
$active_nav = 'loans';

include 'header.php';
?>

<!-- Filter tabs -->
<div style="display:flex;gap:6px;overflow-x:auto;padding-bottom:4px;margin-bottom:12px;-webkit-overflow-scrolling:touch;">
    <?php foreach ([''=>'All','pending'=>'Pending','approved'=>'Approved','released'=>'Released','overdue'=>'Overdue','paid'=>'Paid'] as $s => $label): ?>
        <a href="?status=<?php echo $s; ?>&search=<?php echo urlencode($search); ?>"
           style="flex-shrink:0;padding:6px 14px;border-radius:20px;font-size:12px;font-weight:700;text-decoration:none;
                  <?php echo $status === $s
                    ? 'background:var(--primary);color:#fff;'
                    : 'background:var(--surface);color:var(--muted);border:1.5px solid var(--border);'; ?>">
            <?php echo $label; ?>
        </a>
    <?php endforeach; ?>
</div>

<!-- Search -->
<form method="GET" style="display:flex;gap:8px;margin-bottom:12px;">
    <input type="hidden" name="status" value="<?php echo htmlspecialchars($status); ?>">
    <input type="text" name="search" placeholder="Search borrower…"
           value="<?php echo htmlspecialchars($search); ?>"
           style="flex:1;padding:9px 12px;border:1.5px solid var(--border);border-radius:10px;font-size:13px;background:var(--card);">
    <button type="submit" style="padding:9px 13px;background:var(--primary);color:#fff;border:none;border-radius:10px;">
        <i class="fas fa-search"></i>
    </button>
</form>

<a href="/cash_lending/mobile/add-loan.php" class="btn btn-primary btn-block mb-3">
    <i class="fas fa-plus"></i> New Loan
</a>

<?php if (empty($grouped)): ?>
<div style="text-align:center;padding:48px 0;color:var(--muted);">
    <i class="fas fa-file-contract" style="font-size:40px;opacity:.3;display:block;margin-bottom:12px;"></i>
    No loans found
</div>
<?php else: ?>

<!-- Expand / Collapse all -->
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
    <small style="color:var(--muted);"><?php echo count($grouped); ?> borrower(s)</small>
    <div style="display:flex;gap:8px;">
        <button onclick="toggleAll(true)"
                style="font-size:11px;padding:5px 10px;border:1px solid var(--border);border-radius:8px;background:var(--card);color:var(--text);">
            Expand All
        </button>
        <button onclick="toggleAll(false)"
                style="font-size:11px;padding:5px 10px;border:1px solid var(--border);border-radius:8px;background:var(--card);color:var(--text);">
            Collapse All
        </button>
    </div>
</div>

<?php foreach ($grouped as $bid => $borrower): ?>
<div style="background:var(--card);border-radius:14px;margin-bottom:12px;overflow:hidden;box-shadow:0 1px 4px rgba(0,0,0,.07);">

    <!-- Borrower header -->
    <div onclick="toggleBorrower(<?php echo $bid; ?>)"
         style="display:flex;align-items:center;gap:12px;padding:14px 16px;cursor:pointer;">
        <div style="width:40px;height:40px;border-radius:50%;background:#1a56db;color:#fff;
                    display:flex;align-items:center;justify-content:center;font-weight:800;font-size:16px;flex-shrink:0;">
            <?php echo strtoupper(substr($borrower['name'], 0, 1)); ?>
        </div>
        <div style="flex:1;min-width:0;">
            <div style="font-weight:700;font-size:15px;"><?php echo htmlspecialchars($borrower['name']); ?></div>
            <div style="font-size:12px;color:var(--muted);">
                <?php echo count($borrower['loans']); ?> loan account(s)
            </div>
        </div>
        <i class="fas fa-chevron-down" id="icon-<?php echo $bid; ?>"
           style="font-size:13px;color:var(--muted);transition:.2s;flex-shrink:0;"></i>
    </div>

    <!-- Loan rows -->
    <div id="borrower-<?php echo $bid; ?>">
        <?php foreach ($borrower['loans'] as $l):
            $badgeColor = match($l['status']) {
                'paid'     => '#057a55',
                'overdue'  => '#e02424',
                'released' => '#1a56db',
                'approved' => '#0694a2',
                default    => '#c27803'
            };
            $penalty = calculatePenalty($l);
        ?>
        <div style="border-top:1px solid var(--border);">
            <!-- Loan summary row -->
            <div style="display:flex;align-items:center;justify-content:space-between;padding:12px 16px;">
                <div style="min-width:0;flex:1;">
                    <div style="font-size:13px;font-weight:700;">
                        Loan #<?php echo $l['id']; ?>
                        <span style="font-size:10px;font-weight:700;color:#fff;background:<?php echo $badgeColor; ?>;
                                     border-radius:6px;padding:2px 7px;margin-left:4px;">
                            <?php echo ucfirst($l['status']); ?>
                        </span>
                    </div>
                    <div style="font-size:12px;color:var(--muted);margin-top:2px;">
                        Applied: <?php echo date('M d, Y', strtotime($l['created_at'])); ?>
                        <?php if (!in_array($l['status'], ['pending','approved'])): ?>
                            · Due: <?php echo date('M d, Y', strtotime($l['due_date'])); ?>
                        <?php endif; ?>
                    </div>
                    <?php if ($penalty > 0): ?>
                    <div style="font-size:11px;color:#e02424;">
                        Penalty: +₱<?php echo number_format($penalty,2); ?>
                    </div>
                    <?php endif; ?>
                </div>
                <div style="text-align:right;flex-shrink:0;margin-left:12px;">
                    <div style="font-weight:800;font-size:15px;">₱<?php echo number_format($l['loan_amount'],2); ?></div>
                    <div style="font-size:11px;color:var(--muted);">Bal ₱<?php echo number_format($l['balance'],2); ?></div>
                </div>
            </div>
            <!-- Action buttons -->
            <div style="display:flex;gap:8px;padding:0 16px 12px;">
                <a href="/cash_lending/mobile/loan-details.php?id=<?php echo $l['id']; ?>"
                   style="flex:1;text-align:center;padding:7px;border:1.5px solid #1a56db;border-radius:9px;
                          font-size:12px;font-weight:700;color:#1a56db;text-decoration:none;">
                    <i class="fas fa-eye"></i> View
                </a>
                <?php if ($l['status'] === 'pending' && isAdmin()): ?>
                <button onclick="approveLoan(<?php echo $l['id']; ?>)"
                        style="flex:1;padding:7px;border:none;border-radius:9px;background:#0694a2;
                               color:#fff;font-size:12px;font-weight:700;cursor:pointer;">
                    <i class="fas fa-check"></i> Approve
                </button>
                <?php endif; ?>
                <?php if ($l['status'] === 'approved' && isAdmin()): ?>
                <button onclick="releaseLoan(<?php echo $l['id']; ?>)"
                        style="flex:1;padding:7px;border:none;border-radius:9px;background:#1a56db;
                               color:#fff;font-size:12px;font-weight:700;cursor:pointer;">
                    <i class="fas fa-hand-holding-usd"></i> Release
                </button>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

</div>
<?php endforeach; ?>
<?php endif; ?>

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

<script>
function toggleBorrower(bid) {
    const body = document.getElementById('borrower-' + bid);
    const icon = document.getElementById('icon-' + bid);
    const hidden = body.style.display === 'none';
    body.style.display = hidden ? '' : 'none';
    icon.style.transform = hidden ? 'rotate(0deg)' : 'rotate(-90deg)';
}

function toggleAll(open) {
    document.querySelectorAll('[id^="borrower-"]').forEach(el => {
        el.style.display = open ? '' : 'none';
    });
    document.querySelectorAll('[id^="icon-"]').forEach(icon => {
        icon.style.transform = open ? 'rotate(0deg)' : 'rotate(-90deg)';
    });
}

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?')) 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>
