<?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);
$statuses = [''=>'All','pending'=>'Pending','approved'=>'Approved','released'=>'Released','overdue'=>'Overdue','paid'=>'Paid'];

$total_loans = array_sum(array_map(fn($b) => count($b['loans']), $grouped));

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<div class="row mb-4">
    <div class="col-lg-8"><h3><i class="fas fa-file-contract"></i> Loans</h3></div>
    <div class="col-lg-4 text-end">
        <a href="/cash_lending/add-loan.php" class="btn btn-primary">
            <i class="fas fa-plus"></i> New Loan
        </a>
    </div>
</div>

<!-- Filters -->
<div class="card mb-3">
    <div class="card-body py-2">
        <form method="GET" class="d-flex flex-wrap gap-2 align-items-center">
            <input type="text" class="form-control" name="search" placeholder="Search borrower name…"
                   value="<?php echo htmlspecialchars($search); ?>" style="max-width:240px;">
            <select class="form-select" name="status" style="max-width:150px;" onchange="this.form.submit()">
                <?php foreach ($statuses as $k => $v): ?>
                    <option value="<?php echo $k; ?>" <?php echo $status===$k?'selected':''; ?>><?php echo $v; ?></option>
                <?php endforeach; ?>
            </select>
            <button type="submit" class="btn btn-outline-primary"><i class="fas fa-search"></i> Search</button>
            <?php if ($search || $status): ?>
                <a href="/cash_lending/loans.php" class="btn btn-outline-secondary"><i class="fas fa-times"></i> Clear</a>
            <?php endif; ?>
        </form>
    </div>
</div>

<?php if (empty($grouped)): ?>
<div class="card">
    <div class="p-5 text-center">
        <i class="fas fa-file-contract fa-3x mb-3 text-muted opacity-25"></i>
        <h5>No loans found</h5>
    </div>
</div>
<?php else: ?>

<!-- Expand / Collapse all -->
<div class="d-flex justify-content-between align-items-center mb-2">
    <small class="text-muted">
        <?php echo count($grouped); ?> borrower(s) · <?php echo number_format($total_loans); ?> loan(s)
    </small>
    <div class="d-flex gap-2">
        <button class="btn btn-sm btn-outline-secondary" onclick="toggleAll(true)">
            <i class="fas fa-expand-alt"></i> Expand All
        </button>
        <button class="btn btn-sm btn-outline-secondary" onclick="toggleAll(false)">
            <i class="fas fa-compress-alt"></i> Collapse All
        </button>
    </div>
</div>

<?php foreach ($grouped as $bid => $borrower): ?>
<div class="card mb-3">

    <!-- Borrower header -->
    <div class="card-header d-flex justify-content-between align-items-center"
         style="cursor:pointer;background:#f8faff;" onclick="toggleBorrower(<?php echo $bid; ?>)">
        <div class="d-flex align-items-center gap-3">
            <div style="width:38px;height:38px;border-radius:50%;background:#1a56db;color:#fff;
                        display:flex;align-items:center;justify-content:center;font-weight:700;font-size:15px;">
                <?php echo strtoupper(substr($borrower['name'], 0, 1)); ?>
            </div>
            <div>
                <div class="fw-bold"><?php echo htmlspecialchars($borrower['name']); ?></div>
                <small class="text-muted">
                    <?php echo htmlspecialchars($borrower['contact'] ?? ''); ?>
                    &nbsp;·&nbsp; <?php echo count($borrower['loans']); ?> loan account(s)
                </small>
            </div>
        </div>
        <i class="fas fa-chevron-down" id="icon-<?php echo $bid; ?>"
           style="transition:.2s;color:#6b7280;"></i>
    </div>

    <!-- Loans table -->
    <div id="borrower-<?php echo $bid; ?>">
        <div class="table-responsive">
            <table class="table table-hover mb-0" style="font-size:13px;">
                <thead class="bg-light">
                    <tr>
                        <th class="ps-4">Loan #</th>
                        <th>Amount</th>
                        <th>Balance</th>
                        <th>Installment</th>
                        <th>Mode</th>
                        <th>Applied</th>
                        <th>Due Date</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($borrower['loans'] as $l):
                        $badge = match($l['status']) {
                            'paid'     => 'bg-success',
                            'overdue'  => 'bg-danger',
                            'released' => 'bg-primary',
                            'approved' => 'bg-info',
                            default    => 'bg-warning text-dark',
                        };
                        $penalty = calculatePenalty($l);
                    ?>
                    <tr>
                        <td class="ps-4 fw-semibold">#<?php echo $l['id']; ?></td>
                        <td>₱<?php echo number_format($l['loan_amount'],2); ?></td>
                        <td>
                            ₱<?php echo number_format($l['balance'],2); ?>
                            <?php if ($penalty > 0): ?>
                                <br><small class="text-danger">+₱<?php echo number_format($penalty,2); ?> penalty</small>
                            <?php endif; ?>
                        </td>
                        <td>₱<?php echo number_format($l['installment_amount'],2); ?></td>
                        <td><?php echo ucfirst($l['payment_mode']); ?></td>
                        <td><?php echo date('M d, Y', strtotime($l['created_at'])); ?></td>
                        <td><?php echo in_array($l['status'], ['pending','approved']) ? '<span class="text-muted">—</span>' : date('M d, Y', strtotime($l['due_date'])); ?></td>
                        <td><span class="badge <?php echo $badge; ?>"><?php echo ucfirst($l['status']); ?></span></td>
                        <td>
                            <a href="/cash_lending/loan-details.php?id=<?php echo $l['id']; ?>"
                               class="btn btn-sm btn-outline-primary" title="View">
                                <i class="fas fa-eye"></i>
                            </a>
                            <?php if ($l['status'] === 'pending' && isAdmin()): ?>
                                <button class="btn btn-sm btn-info text-white" title="Approve"
                                        onclick="approveLoan(<?php echo $l['id']; ?>)">
                                    <i class="fas fa-check"></i>
                                </button>
                            <?php endif; ?>
                            <?php if ($l['status'] === 'approved' && isAdmin()): ?>
                                <button class="btn btn-sm btn-primary" title="Mark as Released"
                                        onclick="releaseLoan(<?php echo $l['id']; ?>)">
                                    <i class="fas fa-hand-holding-usd"></i>
                                </button>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

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

<?php include 'includes/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>
