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

$page_title = 'Payments';
$active_nav = 'payments';

include 'header.php';
?>

<!-- Today's collections -->
<div style="background:linear-gradient(135deg,#057a55,#0e9f6e);border-radius:14px;padding:16px;margin-bottom:16px;color:#fff;">
    <div style="font-size:12px;opacity:.85;font-weight:600;text-transform:uppercase;letter-spacing:.5px;">
        <i class="fas fa-coins"></i> Today's Collections
    </div>
    <div style="font-size:28px;font-weight:800;margin:4px 0;">
        ₱<?php echo number_format($daily_total, 2); ?>
    </div>
    <div style="font-size:12px;opacity:.75;"><?php echo date('F j, Y'); ?></div>
</div>

<a href="/cash_lending/mobile/add-payment.php" class="btn btn-primary btn-block mb-3">
    <i class="fas fa-plus"></i> Record Payment
</a>

<!-- Search & date filter -->
<form method="GET" style="display:flex;gap:8px;margin-bottom:14px;">
    <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);">
    <input type="date" name="date" value="<?php echo htmlspecialchars($date); ?>"
           style="padding:9px 10px;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>
<?php if ($search || $date): ?>
<a href="/cash_lending/mobile/payments.php"
   style="display:block;text-align:center;font-size:12px;color:var(--muted);margin-bottom:12px;">
    <i class="fas fa-times"></i> Clear filters
</a>
<?php endif; ?>

<!-- Expand / Collapse all -->
<?php if (!empty($grouped)): ?>
<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): ?>

<!-- Borrower card -->
<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(s) ·
                <?php echo array_sum(array_map(fn($l) => count($l['payments']), $borrower['loans'])); ?> payment(s)
            </div>
        </div>
        <div style="text-align:right;flex-shrink:0;">
            <div style="font-weight:800;color:#057a55;font-size:15px;">
                ₱<?php echo number_format($borrower['total'], 2); ?>
            </div>
            <i class="fas fa-chevron-down" id="bicon-<?php echo $bid; ?>"
               style="font-size:12px;color:var(--muted);transition:.2s;"></i>
        </div>
    </div>

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

        <!-- Loan sub-header -->
        <div style="border-top:1px solid var(--border);background:#f0f4ff;">
            <div onclick="toggleLoan('<?php echo $bid; ?>_<?php echo $lid; ?>')"
                 style="display:flex;align-items:center;justify-content:space-between;padding:10px 16px;cursor:pointer;">
                <div>
                    <span style="font-weight:600;font-size:13px;">
                        <i class="fas fa-file-contract" style="color:#1a56db;"></i>
                        Loan #<?php echo $lid; ?>
                    </span>
                    <?php
                    $lsBadge = match($loan['loan_status']) {
                        'paid'     => '#057a55',
                        'overdue'  => '#e02424',
                        'released' => '#1a56db',
                        'approved' => '#0694a2',
                        default    => '#6b7280'
                    };
                    ?>
                    <span style="font-size:10px;font-weight:700;color:#fff;background:<?php echo $lsBadge; ?>;
                                 border-radius:6px;padding:2px 7px;margin-left:6px;">
                        <?php echo ucfirst($loan['loan_status']); ?>
                    </span>
                    <a href="/cash_lending/mobile/loan-details.php?id=<?php echo $lid; ?>"
                       onclick="event.stopPropagation()"
                       style="font-size:11px;color:#1a56db;margin-left:8px;">View →</a>
                </div>
                <div style="display:flex;align-items:center;gap:8px;">
                    <div style="text-align:right;">
                        <div style="font-size:11px;color:var(--muted);">₱<?php echo number_format($loan['loan_amount'],2); ?> loan</div>
                        <div style="font-size:12px;font-weight:700;color:#057a55;">₱<?php echo number_format($loan['loan_total'],2); ?> paid</div>
                    </div>
                    <i class="fas fa-chevron-down" id="licon-<?php echo $bid; ?>_<?php echo $lid; ?>"
                       style="font-size:11px;color:var(--muted);transition:.2s;transform:rotate(-90deg);"></i>
                </div>
            </div>
        </div>

        <!-- Payment rows -->
        <div id="loan-<?php echo $bid; ?>_<?php echo $lid; ?>" style="display:none;">
            <?php foreach ($loan['payments'] as $p): ?>
            <div style="display:flex;align-items:center;justify-content:space-between;
                        padding:10px 16px;border-top:1px solid var(--border);">
                <div style="min-width:0;">
                    <div style="font-size:13px;font-weight:600;">
                        <?php echo date('M d, Y', strtotime($p['payment_date'])); ?>
                        <?php if (($p['payment_type'] ?? '') === 'interest_only'): ?>
                            <span style="font-size:10px;background:#fef3c7;color:#92400e;border-radius:5px;padding:1px 6px;margin-left:4px;">Interest Only</span>
                        <?php endif; ?>
                    </div>
                    <div style="font-size:11px;color:var(--muted);">
                        <code style="font-size:10px;"><?php echo htmlspecialchars($p['receipt_number'] ?? '—'); ?></code>
                        <?php if (!empty($p['payment_method'])): ?>
                            · <?php echo htmlspecialchars($p['payment_method']); ?>
                        <?php endif; ?>
                    </div>
                </div>
                <div style="text-align:right;flex-shrink:0;">
                    <div style="font-weight:800;color:#057a55;">+₱<?php echo number_format($p['amount'],2); ?></div>
                    <?php if ($p['penalty_paid'] > 0): ?>
                        <div style="font-size:11px;color:#e02424;">+₱<?php echo number_format($p['penalty_paid'],2); ?> penalty</div>
                    <?php endif; ?>
                    <a href="/cash_lending/receipt.php?id=<?php echo $p['id']; ?>" target="_blank"
                       style="font-size:11px;color:var(--muted);">
                        <i class="fas fa-receipt"></i> Receipt
                    </a>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

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

<?php endforeach; ?>

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

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

<script>
function toggleBorrower(bid) {
    const body = document.getElementById('borrower-' + bid);
    const icon = document.getElementById('bicon-' + 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('licon-' + 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('[id^="borrower-"]').forEach(el => {
        el.style.display = open ? '' : 'none';
    });
    document.querySelectorAll('[id^="loan-"]').forEach(el => {
        el.style.display = open ? '' : 'none';
    });
    document.querySelectorAll('[id^="bicon-"]').forEach(icon => {
        icon.style.transform = open ? 'rotate(0deg)' : 'rotate(-90deg)';
    });
    document.querySelectorAll('[id^="licon-"]').forEach(icon => {
        icon.style.transform = open ? 'rotate(0deg)' : 'rotate(-90deg)';
    });
}
</script>
