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

$page_title  = 'Dashboard';
$active_nav  = 'dashboard';

$total_borrowers     = getTotalBorrowers($conn);
$active_loans        = getActiveLoans($conn);
$overdue_loans       = getOverdueLoans($conn);
$paid_loans          = getPaidLoans($conn);
$pending_approvals   = getCount($conn, "SELECT COUNT(*) FROM loans WHERE status = 'pending'");
$daily_collections   = getDailyCollections($conn);
$monthly_collections = getMonthlyCollections($conn);

$recent_loans = getRecentLoans($conn, 5);  // Fix: SQL LIMIT, not PHP slice
$pending_approvals = getPendingApprovals($conn);

$today_payments = fetchAll($conn,
    "SELECT p.*, b.first_name, b.last_name FROM payments p
     JOIN loans l ON p.loan_id = l.id
     JOIN borrowers b ON l.borrower_id = b.id
     WHERE p.payment_date = CURDATE()
     ORDER BY p.created_at DESC LIMIT 10",
    [], ""
);

$due_tomorrow = fetchAll($conn,
    "SELECT b.first_name, b.last_name, b.contact, l.id as loan_id,
            l.balance, l.installment_amount, l.due_date
     FROM loans l
     JOIN borrowers b ON l.borrower_id = b.id
     WHERE l.due_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 1 DAY)
       AND l.status IN ('released','overdue')
     ORDER BY l.due_date ASC, b.last_name ASC",
    [], "");

include 'header.php';
?>

<!-- Daily collection banner -->
<div class="collection-banner">
    <div class="cb-label">Today's Collections</div>
    <div class="cb-amount">₱<?php echo number_format($daily_collections, 2); ?></div>
    <div class="cb-sub"><?php echo date('l, F j, Y'); ?></div>
</div>

<!-- Stat grid -->
<div class="stat-grid">
    <div class="stat-card blue">
        <div class="stat-label">Borrowers</div>
        <div class="stat-num"><?php echo number_format($total_borrowers); ?></div>
        <div class="stat-sub">Total active</div>
    </div>
    <div class="stat-card green">
        <div class="stat-label">Active Loans</div>
        <div class="stat-num"><?php echo number_format($active_loans); ?></div>
        <div class="stat-sub">Active & Released</div>
    </div>
    <div class="stat-card red">
        <div class="stat-label">Overdue</div>
        <div class="stat-num"><?php echo number_format($overdue_loans); ?></div>
        <div class="stat-sub">Needs action</div>
    </div>
    <div class="stat-card orange">
        <div class="stat-label">Monthly</div>
        <div class="stat-num">₱<?php echo number_format($monthly_collections/1000, 1); ?>k</div>
        <div class="stat-sub"><?php echo date('M Y'); ?></div>
    </div>
    <div class="stat-card" style="background:#fef3c7;">
        <div class="stat-label" style="color:#92400e;">Pending Approval</div>
        <div class="stat-num" style="color:#c27803;"><?php echo number_format($pending_approvals); ?></div>
        <div class="stat-sub" style="color:#c27803;"><a href="/cash_lending/mobile/loans.php?status=pending" style="color:inherit;">View →</a></div>
    </div>
    <div class="stat-card" style="background:#fef3c7;color:#92400e;">
        <div class="stat-label">Pending</div>
        <div class="stat-num"><?php echo number_format($pending_approvals); ?></div>
        <div class="stat-sub">Need Approval</div>
    </div>
</div>

<!-- Quick actions -->
<div class="section-title">Quick Actions</div>
<!-- Due Today & Tomorrow — always visible -->
<div style="background:#fffbeb;border:1.5px solid #fcd34d;border-radius:14px;margin-bottom:16px;overflow:hidden;">
    <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 14px;border-bottom:1px solid #fcd34d;">
        <div style="font-size:13px;font-weight:700;color:#92400e;">
            <i class="fas fa-bell" style="color:#c27803;"></i>
            Due Today &amp; Tomorrow · <strong><?php echo count($due_tomorrow); ?></strong>
        </div>
        <a href="/cash_lending/mobile/loans.php?status=released"
           style="font-size:11px;font-weight:700;color:#c27803;text-decoration:none;">View All →</a>
    </div>
    <?php if (empty($due_tomorrow)): ?>
        <div style="padding:12px 14px;font-size:13px;color:#92400e;">
            <i class="fas fa-check-circle" style="color:#057a55;"></i> No loans due today or tomorrow.
        </div>
    <?php else: ?>
    <div id="mobileTicker" style="height:<?php echo min(count($due_tomorrow),3)*52; ?>px;overflow:hidden;position:relative;">
        <div id="mobileInner" style="position:absolute;width:100%;">
            <?php foreach ($due_tomorrow as $d):
                $isToday = $d['due_date'] === date('Y-m-d');
            ?>
            <div style="display:flex;align-items:center;justify-content:space-between;
                        padding:10px 14px;height:52px;border-bottom:1px solid #fef3c7;">
                <div style="display:flex;align-items:center;gap:10px;min-width:0;">
                    <div style="width:34px;height:34px;border-radius:50%;
                                background:<?php echo $isToday?'#fee2e2':'#fef3c7'; ?>;
                                color:<?php echo $isToday?'#e02424':'#c27803'; ?>;
                                display:flex;align-items:center;justify-content:center;
                                font-weight:800;font-size:13px;flex-shrink:0;">
                        <?php echo strtoupper(substr($d['first_name'],0,1)); ?>
                    </div>
                    <div style="min-width:0;">
                        <div style="font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                            <?php echo htmlspecialchars($d['first_name'].' '.$d['last_name']); ?>
                            <span style="font-size:9px;font-weight:700;color:#fff;padding:1px 5px;border-radius:4px;
                                         background:<?php echo $isToday?'#e02424':'#c27803'; ?>;">
                                <?php echo $isToday?'TODAY':'TOMORROW'; ?>
                            </span>
                        </div>
                        <div style="font-size:11px;color:#92400e;"><?php echo htmlspecialchars($d['contact']); ?></div>
                    </div>
                </div>
                <div style="text-align:right;flex-shrink:0;margin-left:10px;">
                    <div style="font-weight:800;color:<?php echo $isToday?'#e02424':'#c27803'; ?>;font-size:13px;">
                        ₱<?php echo number_format($d['installment_amount'],2); ?>
                    </div>
                    <a href="/cash_lending/mobile/loan-details.php?id=<?php echo $d['loan_id']; ?>"
                       style="font-size:11px;color:#1a56db;font-weight:600;">View →</a>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php if (count($due_tomorrow) > 3): ?>
    <script>
    (function() {
        const ticker = document.getElementById('mobileTicker');
        const inner  = document.getElementById('mobileInner');
        const rowH   = 52, total = <?php echo count($due_tomorrow); ?>;
        inner.innerHTML += inner.innerHTML;
        let pos = 0, paused = false;
        ticker.addEventListener('touchstart', () => paused = true, {passive:true});
        ticker.addEventListener('touchend',   () => setTimeout(()=>paused=false,2000));
        setInterval(() => {
            if (paused) return;
            pos += 0.4;
            if (pos >= rowH * total) pos = 0;
            inner.style.transform = 'translateY(-' + pos + 'px)';
        }, 30);
    })();
    </script>
    <?php endif; ?>
    <?php endif; ?>
</div>

<div class="quick-actions">
    <a href="/cash_lending/mobile/add-borrower.php" class="qa-btn">
        <div class="qa-icon" style="background:#dbeafe; color:#1a56db;"><i class="fas fa-user-plus"></i></div>
        Add Borrower
    </a>
    <a href="/cash_lending/mobile/add-loan.php" class="qa-btn">
        <div class="qa-icon" style="background:#d1fae5; color:#057a55;"><i class="fas fa-file-contract"></i></div>
        New Loan
    </a>
    <a href="/cash_lending/mobile/add-payment.php" class="qa-btn">
        <div class="qa-icon" style="background:#fef3c7; color:#c27803;"><i class="fas fa-money-bill-wave"></i></div>
        Payment
    </a>
    <a href="/cash_lending/mobile/loans.php?status=released" class="qa-btn">
        <div class="qa-icon" style="background:#dbeafe; color:#1a56db;"><i class="fas fa-hand-holding-usd"></i></div>
        Released
    </a>
    <a href="/cash_lending/mobile/loans.php?status=overdue" class="qa-btn">
        <div class="qa-icon" style="background:#fee2e2; color:#e02424;"><i class="fas fa-exclamation-circle"></i></div>
        Overdue
    </a>
</div>

<!-- Today's payments -->
<div class="section-title">Today's Payments</div>
<div class="card mb-3">
    <?php if (!empty($today_payments)): ?>
        <?php foreach ($today_payments as $p): ?>
            <div class="list-row">
                <div class="row-info">
                    <div class="row-name"><?php echo htmlspecialchars($p['first_name'] . ' ' . $p['last_name']); ?></div>
                    <div class="row-sub"><?php echo date('h:i A', strtotime($p['created_at'])); ?></div>
                </div>
                <div class="row-right">
                    <div class="row-amount" style="color:var(--success);">+₱<?php echo number_format($p['amount'], 2); ?></div>
                    <?php if (!empty($p['penalty_paid']) && $p['penalty_paid'] > 0): ?>
                    <div style="font-size:11px;color:#e02424;">+₱<?php echo number_format($p['penalty_paid'],2); ?> penalty</div>
                    <?php endif; ?>
                    <?php if (($p['penalty_paid'] ?? 0) > 0): ?>
                    <div style="font-size:11px;color:#e02424;">+₱<?php echo number_format($p['penalty_paid'],2); ?> penalty</div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="empty-state"><i class="fas fa-inbox"></i><p>No payments today</p></div>
    <?php endif; ?>
</div>

<!-- Recent loans -->
<div class="section-title">Recent Loans</div>
<div class="card mb-3">
    <?php if (!empty($recent_loans)): ?>
        <?php foreach ($recent_loans as $loan): ?>
            <?php
            $badge = match($loan['status']) {
                'paid'    => 'badge-success',
                'overdue' => 'badge-danger',
                'approved'=> 'badge-info',
                'released'=> 'badge-primary',
                default   => 'badge-warning',
            };
            ?>
            <a href="/cash_lending/mobile/loan-details.php?id=<?php echo $loan['id']; ?>" class="list-row">
                <div class="row-info">
                    <div class="row-name"><?php echo htmlspecialchars($loan['first_name'] . ' ' . $loan['last_name']); ?></div>
                    <div class="row-sub mt-1"><span class="badge <?php echo $badge; ?>"><?php echo ucfirst($loan['status']); ?></span></div>
                </div>
                <div class="row-right">
                    <div class="row-amount">₱<?php echo number_format($loan['loan_amount'], 2); ?></div>
                </div>
                <i class="fas fa-chevron-right chevron"></i>
            </a>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="empty-state"><i class="fas fa-inbox"></i><p>No loans yet</p></div>
    <?php endif; ?>
</div>

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