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

$page_title = 'Dashboard';

// Stats
$total_lost = $conn->query("SELECT COUNT(*) as c FROM lost_items")->fetch_assoc()['c'];
$total_found = $conn->query("SELECT COUNT(*) as c FROM found_items")->fetch_assoc()['c'];
$total_returned = $conn->query("SELECT COUNT(*) as c FROM lost_items WHERE status='returned'")->fetch_assoc()['c'];
$total_users = $conn->query("SELECT COUNT(*) as c FROM users WHERE role='user'")->fetch_assoc()['c'];
$pending_matches = $conn->query("SELECT COUNT(*) as c FROM matches WHERE match_status='pending'")->fetch_assoc()['c'];
$total_matches = $conn->query("SELECT COUNT(*) as c FROM matches WHERE match_status='approved'")->fetch_assoc()['c'];

// Calculate trending data
$this_month = date('m');
$lost_this_month = $conn->query("SELECT COUNT(*) c FROM lost_items WHERE MONTH(created_at)='$this_month' AND YEAR(created_at)=YEAR(NOW())")->fetch_assoc()['c'];
$found_this_month = $conn->query("SELECT COUNT(*) c FROM found_items WHERE MONTH(created_at)='$this_month' AND YEAR(created_at)=YEAR(NOW())")->fetch_assoc()['c'];
$recovery_rate = $total_lost > 0 ? round(($total_returned / $total_lost) * 100, 1) : 0;

// Recent lost items
$recent_lost = $conn->query("SELECT l.*, u.name as reporter FROM lost_items l JOIN users u ON l.user_id=u.id ORDER BY l.created_at DESC LIMIT 5");
// Recent found items
$recent_found = $conn->query("SELECT f.*, u.name as reporter FROM found_items f JOIN users u ON f.user_id=u.id ORDER BY f.created_at DESC LIMIT 5");
// Monthly data for chart
$monthly = $conn->query("SELECT MONTH(created_at) as m, COUNT(*) as c FROM lost_items WHERE YEAR(created_at)=YEAR(NOW()) GROUP BY MONTH(created_at)");
$monthly_lost = array_fill(1, 12, 0);
while ($row = $monthly->fetch_assoc()) $monthly_lost[$row['m']] = (int)$row['c'];
$monthly_f = $conn->query("SELECT MONTH(created_at) as m, COUNT(*) as c FROM found_items WHERE YEAR(created_at)=YEAR(NOW()) GROUP BY MONTH(created_at)");
$monthly_found = array_fill(1, 12, 0);
while ($row = $monthly_f->fetch_assoc()) $monthly_found[$row['m']] = (int)$row['c'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $page_title ?> - RELINK Admin</title>
<link rel="stylesheet" href="/lostfound_relink/assets/css/style.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
/* ═════════════════════════════════════════════════════════ */
/* 🎨 ADMIN DASHBOARD - ENHANCED STYLES */
/* ═════════════════════════════════════════════════════════ */

.page-content { padding: 24px 28px; background: var(--bg-primary); }

/* STAT CARDS */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 16px;
    margin-bottom: 28px;
    animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}

.stat-card {
    background: var(--white);
    border-radius: 14px;
    padding: 20px 18px;
    border: 1px solid var(--border);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    gap: 14px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    overflow: hidden;
}

.stat-card:hover {
    transform: translateY(-6px);
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.08);
    border-color: currentColor;
}

.stat-card::before {
    content: '';
    position: absolute;
    top: 0; left: 0;
    width: 4px; height: 100%;
    border-radius: 14px 0 0 14px;
    opacity: 0.8;
}

.stat-card::after {
    content: '';
    position: absolute;
    bottom: -25px; right: -25px;
    width: 80px; height: 80px;
    border-radius: 50%;
    opacity: 0.04;
    transition: all 0.3s ease;
}

.stat-card:hover::after { bottom: -15px; right: -15px; opacity: 0.08; }

.stat-card.blue::before { background: #3b82f6; }
.stat-card.blue::after { background: #3b82f6; }
.stat-card.green::before { background: #10b981; }
.stat-card.green::after { background: #10b981; }
.stat-card.yellow::before { background: #f59e0b; }
.stat-card.yellow::after { background: #f59e0b; }
.stat-card.purple::before { background: #8b5cf6; }
.stat-card.purple::after { background: #8b5cf6; }
.stat-card.red::before { background: #ef4444; }
.stat-card.red::after { background: #ef4444; }

.stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    flex-shrink: 0;
}

.stat-icon.blue { background: #dbeafe; }
.stat-icon.green { background: #d1fae5; }
.stat-icon.yellow { background: #fef3c7; }
.stat-icon.purple { background: #ede9fe; }
.stat-icon.red { background: #fee2e2; }

.stat-info {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.value {
    font-size: 28px;
    font-weight: 900;
    color: var(--text);
    line-height: 1;
    letter-spacing: -1px;
    font-variant-numeric: tabular-nums;
}

.label {
    font-size: 11px;
    color: var(--text-muted);
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.8px;
}

/* Quick Insights */
.quick-insights {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 28px;
    animation: fadeInUp 0.7s ease-out 0.1s both;
}

.insight-box {
    background: linear-gradient(135deg, var(--white), var(--bg-secondary));
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 16px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
    transition: all 0.3s ease;
}

.insight-box:hover {
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.06);
    transform: translateY(-3px);
}

.insight-badge {
    display: inline-block;
    background: var(--primary-light);
    color: var(--primary);
    font-size: 10px;
    font-weight: 800;
    padding: 4px 10px;
    border-radius: 20px;
    margin-bottom: 8px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.insight-value {
    font-size: 22px;
    font-weight: 900;
    color: var(--text);
    margin: 6px 0;
}

.insight-desc {
    font-size: 11px;
    color: var(--text-muted);
    line-height: 1.4;
}

/* Cards */
.card {
    background: var(--white);
    border-radius: 14px;
    border: 1px solid var(--border);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    transition: all 0.3s ease;
    animation: fadeInUp 0.6s ease-out forwards;
}

.card:hover {
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.08);
    transform: translateY(-3px);
}

.mb-24:nth-child(2) .card:nth-child(1) { animation-delay: 0.15s; }
.mb-24:nth-child(2) .card:nth-child(2) { animation-delay: 0.2s; }
.mb-24:last-child .card:nth-child(1) { animation-delay: 0.25s; }
.mb-24:last-child .card:nth-child(2) { animation-delay: 0.3s; }

.card-header {
    padding: 20px 24px 16px;
    border-bottom: 1px solid var(--border);
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: linear-gradient(135deg, var(--white) 0%, var(--bg-secondary) 100%);
}

.card-header h3 {
    font-size: 14px;
    font-weight: 800;
    color: var(--text);
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.card-body {
    padding: 24px;
}

.chart-container {
    height: 300px;
    position: relative;
}

.grid-2 {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    margin-bottom: 24px;
}

.table-wrapper table tbody tr:hover {
    background: var(--bg-secondary);
    transition: background 0.2s ease;
}

.table-wrapper table td {
    padding: 12px 14px;
}

.table-wrapper table th {
    padding: 12px 14px;
    font-weight: 700;
    font-size: 11px;
    text-transform: uppercase;
}

/* Dark mode */
body.dark-mode .card-header {
    background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
}

body.dark-mode .insight-box {
    background: linear-gradient(135deg, #0f172a, #1e293b);
}

/* Responsive */
@media(max-width: 1400px) {
    .stats-grid { grid-template-columns: repeat(4, 1fr); }
    .quick-insights { grid-template-columns: repeat(2, 1fr); }
}

@media(max-width: 1100px) {
    .stats-grid { grid-template-columns: repeat(3, 1fr); }
}

@media(max-width: 768px) {
    .stats-grid { grid-template-columns: repeat(2, 1fr); gap: 12px; }
    .quick-insights { grid-template-columns: 1fr; }
    .grid-2 { grid-template-columns: 1fr; }
    .chart-container { height: 250px; }
    .page-content { padding: 16px; }
}

@media(max-width: 480px) {
    .stats-grid { grid-template-columns: 1fr; }
    .value { font-size: 24px; }
}
</style>
</head>
<body>
<div class="layout">
    <?php include '../includes/admin_sidebar.php'; ?>
    <div class="main-content">
        <?php include '../includes/topbar.php'; ?>
        <div class="page-content">
            <!-- STAT CARDS -->
            <div class="stats-grid">
                <div class="stat-card blue">
                    <div class="stat-icon blue">🔍</div>
                    <div class="stat-info">
                        <div class="value counter" data-target="<?= $total_lost ?>">0</div>
                        <div class="label">Total Lost</div>
                    </div>
                </div>
                <div class="stat-card green">
                    <div class="stat-icon green">📦</div>
                    <div class="stat-info">
                        <div class="value counter" data-target="<?= $total_found ?>">0</div>
                        <div class="label">Total Found</div>
                    </div>
                </div>
                <div class="stat-card yellow">
                    <div class="stat-icon yellow">✅</div>
                    <div class="stat-info">
                        <div class="value counter" data-target="<?= $total_returned ?>">0</div>
                        <div class="label">Returned</div>
                    </div>
                </div>
                <div class="stat-card purple">
                    <div class="stat-icon purple">👥</div>
                    <div class="stat-info">
                        <div class="value counter" data-target="<?= $total_users ?>">0</div>
                        <div class="label">Users</div>
                    </div>
                </div>
                <div class="stat-card red">
                    <div class="stat-icon red">🤝</div>
                    <div class="stat-info">
                        <div class="value counter" data-target="<?= $pending_matches ?>">0</div>
                        <div class="label">Pending</div>
                    </div>
                </div>
            </div>

            <!-- QUICK INSIGHTS -->
            <div class="quick-insights">
                <div class="insight-box">
                    <span class="insight-badge" style="background: #10b98133; color: #10b981;">📊 Recovery</span>
                    <div class="insight-value"><?= $recovery_rate ?>%</div>
                    <div class="insight-desc">Of lost items have been successfully recovered</div>
                </div>

                <div class="insight-box">
                    <span class="insight-badge" style="background: #3b82f633; color: #3b82f6;">📈 This Month</span>
                    <div class="insight-value"><?= ($lost_this_month + $found_this_month) ?></div>
                    <div class="insight-desc"><?= $lost_this_month ?> lost, <?= $found_this_month ?> found reports</div>
                </div>

                <div class="insight-box">
                    <span class="insight-badge" style="background: #f59e0b33; color: #f59e0b;">🎯 Matches</span>
                    <div class="insight-value"><?= $total_matches ?></div>
                    <div class="insight-desc">Successful matches made in total</div>
                </div>
            </div>

            <div class="grid-2 mb-24">
                <div class="card">
                    <div class="card-header"><h3>📈 Monthly Trends (<?= date('Y') ?>)</h3></div>
                    <div class="card-body"><div class="chart-container"><canvas id="trendChart"></canvas></div></div>
                </div>
                <div class="card">
                    <div class="card-header"><h3>� Item Status Overview</h3></div>
                    <div class="card-body"><div class="chart-container"><canvas id="statusChart"></canvas></div></div>
                </div>
            </div>

            <div class="grid-2">
                <div class="card">
                    <div class="card-header">
                        <h3>🔍 Recent Lost Items</h3>
                        <a href="/lostfound_relink/admin/lost_items.php" class="btn btn-sm btn-outline">View All</a>
                    </div>
                    <div class="table-wrapper">
                        <table>
                            <thead><tr><th>Item</th><th>Reporter</th><th>Status</th><th>Date</th></tr></thead>
                            <tbody>
                            <?php while($row = $recent_lost->fetch_assoc()): ?>
                            <tr>
                                <td><?= htmlspecialchars($row['item_name']) ?></td>
                                <td><?= htmlspecialchars($row['reporter']) ?></td>
                                <td><span class="badge badge-<?= $row['status'] ?>"><?= $row['status'] ?></span></td>
                                <td><?= date('M d', strtotime($row['created_at'])) ?></td>
                            </tr>
                            <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="card">
                    <div class="card-header">
                        <h3>📦 Recent Found Items</h3>
                        <a href="/lostfound_relink/admin/found_items.php" class="btn btn-sm btn-outline">View All</a>
                    </div>
                    <div class="table-wrapper">
                        <table>
                            <thead><tr><th>Item</th><th>Reporter</th><th>Status</th><th>Date</th></tr></thead>
                            <tbody>
                            <?php while($row = $recent_found->fetch_assoc()): ?>
                            <tr>
                                <td><?= htmlspecialchars($row['item_name']) ?></td>
                                <td><?= htmlspecialchars($row['reporter']) ?></td>
                                <td><span class="badge badge-<?= $row['status'] ?>"><?= $row['status'] ?></span></td>
                                <td><?= date('M d', strtotime($row['created_at'])) ?></td>
                            </tr>
                            <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="/lostfound_relink/assets/js/main.js"></script>
<script>
// ═════════════════════════════════════════════════════════════════════
// 🎯 ANIMATED COUNTER
// ═════════════════════════════════════════════════════════════════════
function animateCounters() {
    const counters = document.querySelectorAll('.counter');
    const isVisible = (el) => {
        const rect = el.getBoundingClientRect();
        return rect.top <= window.innerHeight && rect.bottom >= 0;
    };

    const animate = (counter) => {
        const target = parseInt(counter.getAttribute('data-target'));
        const increment = target / 40;
        let current = 0;

        const timer = setInterval(() => {
            current += increment;
            if (current >= target) {
                counter.textContent = target.toLocaleString();
                clearInterval(timer);
            } else {
                counter.textContent = Math.floor(current).toLocaleString();
            }
        }, 15);
    };

    counters.forEach(counter => {
        if (isVisible(counter) && !counter.classList.contains('animated')) {
            counter.classList.add('animated');
            animate(counter);
        }
    });
}

document.addEventListener('DOMContentLoaded', () => {
    setTimeout(animateCounters, 300);
});

// ═════════════════════════════════════════════════════════════════════
// 📊 CHART CONFIGURATION
// ═════════════════════════════════════════════════════════════════════
const isDark = () => document.body.classList.contains('dark-mode');
const tickColor = () => isDark() ? '#94a3b8' : '#64748b';
const gridColor = () => isDark() ? 'rgba(255,255,255,.08)' : 'rgba(0,0,0,.05)';

const tooltip = {
    backgroundColor: isDark() ? '#0f172a' : '#1e293b',
    titleColor: '#f1f5f9',
    bodyColor: '#cbd5e1',
    borderColor: 'rgba(255,255,255,.12)',
    borderWidth: 2,
    padding: 12,
    cornerRadius: 12,
};

function makeGradient(ctx, color1, color2) {
    const g = ctx.createLinearGradient(0, 0, 0, 300);
    g.addColorStop(0, color1);
    g.addColorStop(1, color2);
    return g;
}

const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
const lostData = <?= json_encode(array_values($monthly_lost)) ?>;
const foundData = <?= json_encode(array_values($monthly_found)) ?>;

const trendCtx = document.getElementById('trendChart').getContext('2d');
new Chart(trendCtx, {
    type: 'line',
    data: {
        labels: months,
        datasets: [
            {
                label: 'Lost',
                data: lostData,
                borderColor: '#ef4444',
                backgroundColor: makeGradient(trendCtx, 'rgba(239,68,68,.25)', 'rgba(239,68,68,.01)'),
                borderWidth: 3,
                pointBackgroundColor: '#ef4444',
                pointBorderColor: '#fff',
                pointBorderWidth: 2,
                pointRadius: 5,
                tension: 0.4,
                fill: true
            },
            {
                label: 'Found',
                data: foundData,
                borderColor: '#10b981',
                backgroundColor: makeGradient(trendCtx, 'rgba(16,185,129,.25)', 'rgba(16,185,129,.01)'),
                borderWidth: 3,
                pointBackgroundColor: '#10b981',
                pointBorderColor: '#fff',
                pointBorderWidth: 2,
                pointRadius: 5,
                tension: 0.4,
                fill: true
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        interaction: { mode: 'index', intersect: false },
        plugins: {
            legend: {
                position: 'top',
                labels: {
                    font: { size: 12, weight: '600' },
                    boxWidth: 14,
                    padding: 16,
                    color: tickColor(),
                    usePointStyle: true,
                    pointStyle: 'circle'
                }
            },
            tooltip: { ...tooltip }
        },
        scales: {
            x: { grid: { display: false }, ticks: { color: tickColor(), font: { size: 11 } }, border: { display: false } },
            y: { beginAtZero: true, grid: { color: gridColor() }, ticks: { color: tickColor(), font: { size: 11 }, precision: 0 }, border: { display: false } }
        }
    }
});

<?php
$s_pending = $conn->query("SELECT COUNT(*) as c FROM lost_items WHERE status='pending'")->fetch_assoc()['c'];
$s_matched = $conn->query("SELECT COUNT(*) as c FROM lost_items WHERE status='matched'")->fetch_assoc()['c'];
$s_returned = $conn->query("SELECT COUNT(*) as c FROM lost_items WHERE status='returned'")->fetch_assoc()['c'];
$s_closed = $conn->query("SELECT COUNT(*) as c FROM lost_items WHERE status='closed'")->fetch_assoc()['c'];
?>
new Chart(document.getElementById('statusChart'), {
    type: 'doughnut',
    data: {
        labels: ['🟨 Pending', '🔵 Matched', '🟢 Returned', '⚫ Closed'],
        datasets: [{
            data: [<?= "$s_pending,$s_matched,$s_returned,$s_closed" ?>],
            backgroundColor: ['#fbbf24', '#60a5fa', '#34d399', '#94a3b8'],
            borderWidth: 3,
            borderColor: isDark() ? '#1e293b' : '#ffffff',
            hoverOffset: 12
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: '68%',
        plugins: {
            legend: {
                position: 'bottom',
                labels: {
                    font: { size: 11, weight: '600' },
                    padding: 12,
                    color: tickColor()
                }
            },
            tooltip: { ...tooltip }
        }
    }
});
</script>
</body>
</html>
