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

$search      = trim($_GET['search'] ?? '');
$date        = $_GET['date'] ?? '';
$daily_total = getDailyCollections($conn);
$grouped     = getPaymentsGrouped($conn, $search, $date);

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

<div class="row mb-4">
    <div class="col-lg-8"><h3><i class="fas fa-money-bill-wave"></i> Payments</h3></div>
    <div class="col-lg-4 text-end">
        <a href="/cash_lending/add-payment.php" class="btn btn-primary">
            <i class="fas fa-plus"></i> Record Payment
        </a>
    </div>
</div>

<div class="alert alert-success py-2 mb-3">
    <i class="fas fa-coins"></i> <strong>Today's Collections:</strong>
    ₱<?php echo number_format($daily_total, 2); ?>
    <span class="text-muted small ms-2">(<?php echo date('F j, Y'); ?>)</span>
</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 or receipt #…"
                   value="<?php echo htmlspecialchars($search); ?>" style="max-width:220px;">
            <input type="date" class="form-control" name="date"
                   value="<?php echo htmlspecialchars($date); ?>" style="max-width:160px;">
            <button type="submit" class="btn btn-outline-primary"><i class="fas fa-search"></i> Search</button>
            <?php if ($search || $date): ?>
                <a href="/cash_lending/payments.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-receipt fa-3x mb-3 text-muted opacity-25"></i>
        <h5>No payments 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) with payments</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>

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

    <!-- 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 count($borrower['loans']); ?> loan account(s)
                    &nbsp;·&nbsp;
                    <?php $totalPay = array_sum(array_column($borrower['loans'], 'loan_total')); ?>
                    <?php echo array_sum(array_map(fn($l) => count($l['payments']), $borrower['loans'])); ?> payment(s)
                </small>
            </div>
        </div>
        <div class="text-end d-flex align-items-center gap-3">
            <div>
                <div class="fw-bold text-success fs-6">₱<?php echo number_format($borrower['total'], 2); ?></div>
                <small class="text-muted">total paid</small>
            </div>
            <i class="fas fa-chevron-down toggle-icon" id="icon-<?php echo $bid; ?>"
               style="transition:.2s;color:#6b7280;"></i>
        </div>
    </div>

    <!-- Loans inside this borrower -->
    <div id="borrower-<?php echo $bid; ?>" class="borrower-body">
        <?php foreach ($borrower['loans'] as $lid => $loan): ?>

        <!-- Loan sub-header -->
        <div class="px-3 pt-3 pb-2" style="background:#f0f4ff;border-top:1px solid #e5e7eb;">
            <div class="d-flex justify-content-between align-items-center"
                 style="cursor:pointer;" onclick="toggleLoan('<?php echo $bid; ?>_<?php echo $lid; ?>')">
                <div>
                    <span class="fw-semibold">
                        <i class="fas fa-file-contract text-primary"></i>
                        Loan #<?php echo $lid; ?>
                    </span>
                    <a href="/cash_lending/loan-details.php?id=<?php echo $lid; ?>"
                       class="btn btn-sm btn-outline-primary ms-2 py-0 px-2"
                       style="font-size:11px;" onclick="event.stopPropagation()">
                        View
                    </a>
                    <?php
                    $lsBadge = match($loan['loan_status']) {
                        'paid'     => 'bg-success',
                        'overdue'  => 'bg-danger',
                        'released' => 'bg-primary',
                        'approved' => 'bg-info',
                        default    => 'bg-secondary'
                    };
                    ?>
                    <span class="badge <?php echo $lsBadge; ?> ms-1" style="font-size:10px;">
                        <?php echo ucfirst($loan['loan_status']); ?>
                    </span>
                </div>
                <div class="text-end d-flex align-items-center gap-3">
                    <div>
                        <span class="text-muted" style="font-size:12px;">
                            ₱<?php echo number_format($loan['loan_amount'],2); ?> loan
                            &nbsp;·&nbsp; ₱<?php echo number_format($loan['balance'],2); ?> balance
                        </span>
                        <div class="fw-bold text-success" style="font-size:13px;">
                            ₱<?php echo number_format($loan['loan_total'],2); ?> paid
                        </div>
                    </div>
                    <i class="fas fa-chevron-down toggle-icon" id="icon-<?php echo $bid; ?>_<?php echo $lid; ?>"
                       style="transition:.2s;color:#6b7280;font-size:12px;transform:rotate(-90deg);"></i>
                </div>
            </div>
        </div>

        <!-- Payments table for this loan -->
        <div id="loan-<?php echo $bid; ?>_<?php echo $lid; ?>" style="display:none;">
            <div class="table-responsive">
                <table class="table table-sm table-hover mb-0" style="font-size:13px;">
                    <thead class="bg-light">
                        <tr>
                            <th class="ps-4">Receipt #</th>
                            <th>Date</th>
                            <th>Type</th>
                            <th>Amount</th>
                            <th>Penalty</th>
                            <th>Method</th>
                            <th>Notes</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($loan['payments'] as $p): ?>
                        <tr>
                            <td class="ps-4"><code style="font-size:11px;"><?php echo htmlspecialchars($p['receipt_number'] ?? '—'); ?></code></td>
                            <td><?php echo date('M d, Y', strtotime($p['payment_date'])); ?></td>
                            <td>
                                <?php if (($p['payment_type'] ?? '') === 'interest_only'): ?>
                                    <span class="badge bg-warning text-dark">Interest Only</span>
                                <?php else: ?>
                                    <span class="badge bg-success">Regular</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-success fw-bold">₱<?php echo number_format($p['amount'],2); ?></td>
                            <td><?php echo $p['penalty_paid']>0 ? '<span class="text-danger">₱'.number_format($p['penalty_paid'],2).'</span>' : '—'; ?></td>
                            <td><?php echo htmlspecialchars($p['payment_method'] ?? '—'); ?></td>
                            <td class="text-muted" style="max-width:140px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                                <?php echo htmlspecialchars($p['notes'] ?? '—'); ?>
                            </td>
                            <td>
                                <a href="/cash_lending/receipt.php?id=<?php echo $p['id']; ?>"
                                   class="btn btn-sm btn-outline-secondary" target="_blank" title="Print Receipt">
                                    <i class="fas fa-receipt"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <?php endforeach; ?>
    </div><!-- end borrower-body -->
</div><!-- end borrower-block -->
<?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 toggleLoan(key) {
    const body = document.getElementById('loan-' + key);
    const icon = document.getElementById('icon-' + key);
    const hidden = body.style.display === 'none';
    body.style.display = hidden ? '' : 'none';
    icon.style.transform = hidden ? 'rotate(0deg)' : 'rotate(-90deg)';
}

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