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

$total_borrowers     = getTotalBorrowers($conn);
$active_loans        = getActiveLoans($conn);
$paid_loans          = getPaidLoans($conn);
$overdue_loans       = getOverdueLoans($conn);
$pending_approvals   = getPendingApprovals($conn);
$daily_collections   = getDailyCollections($conn);
$monthly_collections = getMonthlyCollections($conn);
$recent_loans        = getAllLoans($conn, null, 5);

// Borrowers with loans due tomorrow
$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",
    [], "");

$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",
    [], "");

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

<div style="text-align:right;margin-bottom:8px;">
    <a href="/cash_lending/mobile/dashboard.php" style="font-size:12px;color:#6b7280;text-decoration:none;">
        <i class="fas fa-mobile-alt"></i> Switch to Mobile View
    </a>
</div>

<div class="row mb-4">
    <div class="col-lg-12">
        <div class="d-flex justify-content-between align-items-center">
            <h3><i class="fas fa-chart-line"></i> Dashboard</h3>
            <small class="text-muted">Last updated: <?php echo date('M d, Y - h:i A'); ?></small>
        </div>
    </div>
</div>

<!-- Stats Cards -->
<div class="row mb-4">
    <div class="col-md-6 col-lg-2">
        <a href="/cash_lending/borrowers.php" class="text-decoration-none">
        <div class="card stat-card primary">
            <div class="stat-label">Borrowers</div>
            <div class="stat-number"><?php echo number_format($total_borrowers); ?></div>
            <small>Active Members</small>
        </div></a>
    </div>
    <div class="col-md-6 col-lg-2">
        <a href="/cash_lending/loans.php" class="text-decoration-none">
        <div class="card stat-card success">
            <div class="stat-label">Active Loans</div>
            <div class="stat-number"><?php echo number_format($active_loans); ?></div>
            <small>Pending, Approved &amp; Released</small>
        </div></a>
    </div>
    <div class="col-md-6 col-lg-2">
        <!-- Fix 13: Pending approvals card -->
        <a href="/cash_lending/loans.php?status=pending" class="text-decoration-none">
        <div class="card stat-card warning">
            <div class="stat-label">Pending Approval</div>
            <div class="stat-number"><?php echo number_format($pending_approvals); ?></div>
            <small>Awaiting Review</small>
        </div></a>
    </div>
    <div class="col-md-6 col-lg-2">
        <a href="/cash_lending/loans.php?status=paid" class="text-decoration-none">
        <div class="card stat-card info">
            <div class="stat-label">Paid Loans</div>
            <div class="stat-number"><?php echo number_format($paid_loans); ?></div>
            <small>Completed</small>
        </div></a>
    </div>
    <div class="col-md-6 col-lg-2">
        <a href="/cash_lending/loans.php?status=overdue" class="text-decoration-none">
        <div class="card stat-card danger">
            <div class="stat-label">Overdue Loans</div>
            <div class="stat-number"><?php echo number_format($overdue_loans); ?></div>
            <small>Action Required</small>
        </div></a>
    </div>
    <div class="col-md-6 col-lg-2">
        <a href="/cash_lending/payments.php" class="text-decoration-none">
        <div class="card stat-card" style="background:linear-gradient(135deg,#6366f1,#4f46e5);color:#fff;">
            <div class="stat-label" style="color:rgba(255,255,255,.8);">Monthly</div>
            <div class="stat-number">₱<?php echo number_format($monthly_collections/1000,1); ?>k</div>
            <small style="color:rgba(255,255,255,.7);"><?php echo date('F Y'); ?></small>
        </div></a>
    </div>
</div>

<!-- Collections Row -->
<div class="row mb-4">
    <div class="col-md-6">
        <div class="card h-100">
            <div class="card-body text-center">
                <h6 class="text-muted"><i class="fas fa-calendar-day"></i> Today's Collections</h6>
                <h2 class="text-success fw-bold">₱<?php echo number_format($daily_collections, 2); ?></h2>
                <small class="text-muted"><?php echo date('F j, Y'); ?></small>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card h-100">
            <div class="card-body text-center">
                <h6 class="text-muted"><i class="fas fa-calendar-alt"></i> Monthly Collections</h6>
                <h2 class="text-info fw-bold">₱<?php echo number_format($monthly_collections, 2); ?></h2>
                <small class="text-muted"><?php echo date('F Y'); ?></small>
            </div>
        </div>
    </div>
</div>

<!-- Recent Payments & Recent Loans -->
<div class="row mb-4">
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="fas fa-money-bill-wave"></i> Today's Payments</h5>
                <a href="/cash_lending/payments.php" class="btn btn-sm btn-outline-secondary">View All</a>
            </div>
            <div class="card-body p-0">
                <?php if (!empty($today_payments)): ?>
                <div class="table-responsive">
                    <table class="table table-hover mb-0" style="font-size:13px;">
                        <thead class="bg-light">
                            <tr><th>Borrower</th><th>Amount</th><th>Penalty</th><th>Time</th></tr>
                        </thead>
                        <tbody>
                        <?php foreach ($today_payments as $p): ?>
                            <tr>
                                <td><strong><?php echo htmlspecialchars($p['first_name'].' '.$p['last_name']); ?></strong></td>
                                <td><span class="badge bg-success">₱<?php echo number_format($p['amount'],2); ?></span></td>
                                <!-- Fix 14: show penalty_paid -->
                                <td><?php echo $p['penalty_paid']>0 ? '<span class="badge bg-danger">₱'.number_format($p['penalty_paid'],2).'</span>' : '<span class="text-muted">—</span>'; ?></td>
                                <td><small class="text-muted"><?php echo date('h:i A', strtotime($p['created_at'])); ?></small></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <div class="empty-state p-4"><i class="fas fa-inbox"></i><h5>No Payments Today</h5></div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="col-lg-6">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="fas fa-file-contract"></i> Recent Loans</h5>
                <a href="/cash_lending/loans.php" class="btn btn-sm btn-outline-secondary">View All</a>
            </div>
            <div class="card-body p-0">
                <?php if (!empty($recent_loans)): ?>
                <div class="table-responsive">
                    <table class="table table-hover mb-0" style="font-size:13px;">
                        <thead class="bg-light">
                            <tr><th>Borrower</th><th>Amount</th><th>Status</th></tr>
                        </thead>
                        <tbody>
                        <?php foreach ($recent_loans as $loan):
                            $bc = match($loan['status']) {
                                'pending'  => 'bg-warning text-dark',
                                'approved' => 'bg-info',
                                'released' => 'bg-primary',
                                'paid'     => 'bg-success',
                                'overdue'  => 'bg-danger',
                                default    => 'bg-secondary',
                            };
                        ?>
                        <!-- Fix 12: rows are now clickable links -->
                        <tr style="cursor:pointer;" onclick="location.href='/cash_lending/loan-details.php?id=<?php echo $loan['id']; ?>'">
                            <td><strong><?php echo htmlspecialchars($loan['first_name'].' '.$loan['last_name']); ?></strong></td>
                            <td>₱<?php echo number_format($loan['loan_amount'],2); ?></td>
                            <td><span class="badge <?php echo $bc; ?>"><?php echo ucfirst($loan['status']); ?></span></td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <div class="empty-state p-4"><i class="fas fa-inbox"></i><h5>No Loans Yet</h5></div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Due Today / Tomorrow Ticker — always visible -->
<div class="row mb-4">
    <div class="col-lg-12">
        <div class="card" style="border:1.5px solid #fcd34d;">
            <div class="card-header d-flex justify-content-between align-items-center py-2"
                 style="background:#fffbeb;border-bottom:1px solid #fcd34d;">
                <h6 class="mb-0" style="color:#92400e;">
                    <i class="fas fa-bell" style="color:#c27803;"></i>
                    Due Today &amp; Tomorrow —
                    <strong><?php echo count($due_tomorrow); ?></strong> borrower(s)
                </h6>
                <a href="/cash_lending/loans.php?status=released" class="btn btn-sm btn-warning" style="font-size:11px;">
                    View All
                </a>
            </div>
            <div class="card-body p-0" style="overflow:hidden;min-height:48px;">
                <?php if (empty($due_tomorrow)): ?>
                    <div class="px-3 py-3 text-muted" style="font-size:13px;">
                        <i class="fas fa-check-circle text-success"></i> No loans due today or tomorrow.
                    </div>
                <?php else: ?>
                <div id="dueTicker" style="height:<?php echo min(count($due_tomorrow),3) * 52; ?>px;overflow:hidden;position:relative;">
                    <div id="dueInner" style="position:absolute;width:100%;transition:none;">
                        <?php foreach ($due_tomorrow as $d):
                            $isToday = $d['due_date'] === date('Y-m-d');
                        ?>
                        <div class="d-flex align-items-center justify-content-between px-3"
                             style="height:52px;border-bottom:1px solid #f3f4f6;">
                            <div class="d-flex align-items-center gap-3">
                                <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:700;font-size:13px;flex-shrink:0;">
                                    <?php echo strtoupper(substr($d['first_name'],0,1)); ?>
                                </div>
                                <div>
                                    <div class="fw-semibold" style="font-size:13px;line-height:1.3;">
                                        <?php echo htmlspecialchars($d['first_name'].' '.$d['last_name']); ?>
                                        <?php if ($isToday): ?>
                                            <span class="badge bg-danger ms-1" style="font-size:9px;">TODAY</span>
                                        <?php else: ?>
                                            <span class="badge bg-warning text-dark ms-1" style="font-size:9px;">TOMORROW</span>
                                        <?php endif; ?>
                                    </div>
                                    <div style="font-size:11px;color:#6b7280;">
                                        <?php echo htmlspecialchars($d['contact']); ?>
                                    </div>
                                </div>
                            </div>
                            <div class="text-end">
                                <div class="fw-bold" style="font-size:13px;color:<?php echo $isToday ? '#e02424' : '#c27803'; ?>;">
                                    ₱<?php echo number_format($d['installment_amount'],2); ?>
                                </div>
                                <a href="/cash_lending/loan-details.php?id=<?php echo $d['loan_id']; ?>"
                                   style="font-size:11px;color:#1a56db;">View →</a>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php if (count($due_tomorrow) > 3): ?>
<script>
(function() {
    const ticker  = document.getElementById('dueTicker');
    const inner   = document.getElementById('dueInner');
    const rowH    = 48;
    const visible = 3;
    const total   = <?php echo count($due_tomorrow); ?>;
    if (total <= visible) return;

    // Clone rows for seamless loop
    inner.innerHTML += inner.innerHTML;

    let pos = 0;
    let paused = false;
    ticker.addEventListener('mouseenter', () => paused = true);
    ticker.addEventListener('mouseleave', () => paused = false);

    setInterval(() => {
        if (paused) return;
        pos += 0.5;
        if (pos >= rowH * total) pos = 0;
        inner.style.transform = 'translateY(-' + pos + 'px)';
    }, 30);
})();
</script>
<?php endif; ?>

<!-- Quick Actions -->
<div class="card">
    <div class="card-header"><h5 class="mb-0"><i class="fas fa-bolt"></i> Quick Actions</h5></div>
    <div class="card-body">
        <div class="row g-2">
            <div class="col-md-3"><a href="/cash_lending/add-borrower.php" class="btn btn-outline-primary w-100"><i class="fas fa-plus"></i> Add Borrower</a></div>
            <div class="col-md-3"><a href="/cash_lending/add-loan.php" class="btn btn-outline-success w-100"><i class="fas fa-file-contract"></i> Create Loan</a></div>
            <div class="col-md-3"><a href="/cash_lending/add-payment.php" class="btn btn-outline-info w-100"><i class="fas fa-money-bill-wave"></i> Record Payment</a></div>
            <div class="col-md-3"><a href="/cash_lending/reports.php" class="btn btn-outline-secondary w-100"><i class="fas fa-file-alt"></i> View Reports</a></div>
        </div>
    </div>
</div>

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