<?php
session_start();
require_once __DIR__ . '/includes/config.php';

// Admin authentication check
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php"); 
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin Dashboard - Main</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1"></script>

<style>
  /* ================= SIMPLE & MINIMAL THEME ================= */
  :root { 
    --bg: #f3f4f6;           /* Light gray background */
    --sidebar: #111827;      /* Dark slate sidebar */
    --card: #ffffff;         /* Pure white cards */
    --text-main: #1f2937;    /* Dark gray text */
    --text-muted: #6b7280;   /* Muted gray text */
    --border: #e5e7eb;       /* Very light border */
    --accent: #374151;       /* Dark gray for active states */
  }
  
  * { box-sizing: border-box; } 
  
  body { 
    margin: 0; 
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; 
    background: var(--bg); 
    color: var(--text-main); 
    min-height: 100vh; 
    display: flex; 
  }
  
  .svg-icon { 
    width: 18px; height: 18px; vertical-align: middle; margin-right: 8px; 
    fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; 
  }
  
  /* SIDEBAR */
  .sidebar { 
    width: 250px; background: var(--sidebar); color: #fff; height: 100vh; 
    position: fixed; left: 0; top: 0; padding: 20px; overflow-y: auto; 
  }
  .logo { 
    font-weight: 700; color: #fff; margin-bottom: 30px; display: flex; align-items: center; font-size: 18px; letter-spacing: 0.5px;
  }
  .logo .svg-icon { width: 22px; height: 22px; margin-right: 10px; }
  
  .nav a { 
    display: flex; align-items: center; padding: 12px 14px; border-radius: 6px; 
    text-decoration: none; color: #9ca3af; margin-bottom: 5px; font-weight: 500; font-size: 15px;
    transition: background 0.2s, color 0.2s;
  }
  .nav a:hover, .nav a.active { 
    background: var(--accent); color: #ffffff; 
  }
  .nav a .svg-icon { margin-right: 12px; width: 20px; height: 20px; }
  
  /* MAIN CONTENT */
  .main { margin-left: 250px; padding: 30px; flex: 1; }
  
  .topbar { display: flex; align-items: center; justify-content: space-between; margin-bottom: 25px; }
  .title { font-size: 22px; font-weight: 700; color: var(--text-main); }
  .chip { background: var(--card); border: 1px solid var(--border); padding: 8px 16px; border-radius: 6px; font-weight: 600; font-size: 14px;}
  
  /* KPI CARDS */
  .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; margin-bottom: 25px; }
  .card { background: var(--card); padding: 20px; border-radius: 8px; border: 1px solid var(--border); box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
  .card h4 { margin: 0; color: var(--text-muted); font-weight: 600; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px; }
  .card .big { margin-top: 10px; font-size: 26px; font-weight: 700; color: var(--text-main); }
  
  /* Simple Loading Pulse */
  .card .big.loading { color: var(--text-muted); font-size: 18px; font-weight: 400; animation: pulse 1.5s infinite; }
  @keyframes pulse { 0% { opacity: 0.5; } 50% { opacity: 1; } 100% { opacity: 0.5; } }
  
  /* GRIDS & PANELS */
  .grid { display: grid; grid-template-columns: 1fr; gap: 20px; }
  @media(min-width: 1024px) { .grid { grid-template-columns: 2fr 1fr; } } 
  
  .panel { background: var(--card); border-radius: 8px; border: 1px solid var(--border); padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
  .panel h3 { margin: 0 0 20px; color: var(--text-main); font-size: 16px; font-weight: 600; border-bottom: 1px solid var(--border); padding-bottom: 12px; }
  
  /* LEADERBOARD */
  .leader { list-style: none; margin: 0; padding: 0; }
  .leader li { display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid var(--border); font-size: 14px; }
  .leader li:last-child { border: none; padding-bottom: 0; }
  
  /* QUICK ACTIONS */
  .quick { display: flex; flex-direction: column; gap: 10px; }
  .quick a { 
    display: block; text-align: center; padding: 10px; border-radius: 6px; text-decoration: none; 
    font-weight: 600; color: var(--text-main); font-size: 14px; border: none; cursor: pointer;
    background: #f9fafb; border: 1px solid var(--border); transition: background 0.2s;
  }
  .quick a:hover { background: #e5e7eb; }
</style>
</head>
<body>

<div class="sidebar">
  <div class="logo">
      <svg class="svg-icon" viewBox="0 0 24 24"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"></path></svg>
      COSCO ADMIN
  </div>
  <nav class="nav">
    <a class="active" href="dashboard.php">Dashboard</a> 
    <a href="users.php">Users</a>
    <a href="deposits.php">Deposits</a>
    <a href="withdraw.php">Withdrawals</a>
    <a href="products.php">Products</a>
    <a href="daily_income.php">Daily Income</a>
    <a href="notice.php">Notices</a>
    <a href="reports.php">Backup Dashboard</a> 
    <a href="deletebank.php">Delete Bank</a>
    <a href="topay-check_status.php">TopPay Checker</a>
    <a href="mannullywithdraw.php">Manual Withdraw</a>
    <a href="logout.php" style="margin-top: 20px; color: #fca5a5;">Logout</a>
  </nav>
</div>

<div class="main">
  <div class="topbar">
    <div class="title">Dashboard Overview <span style="font-size:13px; font-weight:normal; color:var(--text-muted); margin-left:10px;">(Auto-Updates every 5s)</span></div>
    <div class="chip">
        Admin: <?=htmlspecialchars($_SESSION['admin_username'] ?? 'Super Admin')?>
    </div>
  </div>

  <div class="cards">
    <div class="card"><h4>Total Users</h4><div class="big loading" id="kpi_users">...</div></div>
    <div class="card"><h4>Total Deposits</h4><div class="big loading" id="kpi_deposits">...</div></div>
    <div class="card"><h4>Total Withdrawals</h4><div class="big loading" id="kpi_withdrawals">...</div></div>
    <div class="card"><h4>Pending Withdrawals</h4><div class="big loading" id="kpi_pending">...</div></div>
    <div class="card"><h4>Today Income</h4><div class="big loading" id="kpi_income">...</div></div>
    <div class="card"><h4>Today Gateway Dep.</h4><div class="big loading" id="kpi_today_gdep">...</div></div>
    <div class="card"><h4>Today Manual Dep.</h4><div class="big loading" id="kpi_today_mdep">...</div></div>
    <div class="card"><h4>Today Withdrawals</h4><div class="big loading" id="kpi_today_wd">...</div></div>
  </div>

  <div class="grid">
    <div class="panel">
      <h3>Deposits vs Withdrawals</h3>
      <canvas id="dwChart" height="90"></canvas>
      
      <h3 style="margin-top:30px">User Registrations (Last 7 Days)</h3>
      <canvas id="userChart" height="70"></canvas>
      
      <h3 style="margin-top:30px">Income Distributed</h3>
      <canvas id="incomeChart" height="70"></canvas>
    </div>

    <div class="panel">
      <h3>Top 5 Users (Real Deposit)</h3>
      <ul class="leader" id="leaderboard_list">
          <li style="text-align:center; color:var(--text-muted);">Loading leaderboard...</li>
      </ul>

      <h3 style="margin-top:30px">Quick Actions</h3>
      <div class="quick">
        <a href="withdraw.php?filter=pending">View Pending Withdrawals</a>
        <a href="deposits.php?filter=pending">View Pending Deposits</a>
        <a href="products.php">Manage Products</a>
        <a href="users.php">Manage Users</a>
      </div>
    </div>
  </div>
</div>

<script>
let dwChart, userChart, incomeChart;

function initCharts() {
    const commonOptions = {
        responsive: true,
        plugins: { legend: { labels: { color: '#4b5563' } } },
        scales: { 
            y: { beginAtZero: true, grid: { color: '#f3f4f6' }, ticks: { color: '#6b7280' } }, 
            x: { grid: { display: false }, ticks: { color: '#6b7280' } } 
        }
    };

    dwChart = new Chart(document.getElementById('dwChart'), {
        type: 'bar',
        data: { labels: [], datasets: [
            { label: 'Deposits', data: [], backgroundColor: '#4b5563' }, 
            { label: 'Withdrawals', data: [], backgroundColor: '#d1d5db' } 
        ]},
        options: commonOptions
    });

    userChart = new Chart(document.getElementById('userChart'), {
        type: 'line',
        data: { labels: [], datasets: [
            { label: 'New Registrations', data: [], tension: 0.2, fill: true, backgroundColor: 'rgba(55, 65, 81, 0.1)', borderColor: '#374151', borderWidth: 2 }
        ]},
        options: commonOptions
    });

    incomeChart = new Chart(document.getElementById('incomeChart'), {
        type: 'line',
        data: { labels: [], datasets: [
            { label: 'Income Distributed', data: [], tension: 0.2, fill: false, borderColor: '#9ca3af', borderWidth: 2 }
        ]},
        options: commonOptions
    });
}

function fetchData() {
    // ⚠️ IMPORTANT: Ensure get_dashboard_data.php exists on your server!
    fetch('get_dashboard_data.php')
    .then(response => response.json())
    .then(data => {
        updateKPI('kpi_users', data.total_users, false);
        updateKPI('kpi_deposits', data.total_deposits, true);
        updateKPI('kpi_withdrawals', data.total_withdrawals, true);
        updateKPI('kpi_pending', data.pending_withdrawals, false);
        updateKPI('kpi_income', data.today_income, true);
        updateKPI('kpi_today_gdep', data.today_gateway_deposits, true);
        updateKPI('kpi_today_mdep', data.today_manual_deposits, true);
        updateKPI('kpi_today_wd', data.today_withdrawals, true);

        updateChartData(dwChart, data.charts.labels, [data.charts.deposits, data.charts.withdrawals]);
        updateChartData(userChart, data.charts.labels, [data.charts.new_users]);
        updateChartData(incomeChart, data.charts.labels, [data.charts.income]);

        let leaderHTML = '';
        if(data.leaderboard && data.leaderboard.length > 0) {
            data.leaderboard.forEach(u => {
                leaderHTML += `
                    <li>
                        <span>
                            <svg class="svg-icon" style="color:var(--text-muted); width:16px;" viewBox="0 0 24 24"><rect x="5" y="2" width="14" height="20" rx="2" ry="2"></rect><line x1="12" y1="18" x2="12.01" y2="18"></line></svg>
                            ${u.mobile}
                        </span>
                        <span style="font-weight:700; color:var(--text-main);">₹${parseFloat(u.total).toFixed(2)}</span>
                    </li>`;
            });
        } else {
            leaderHTML = '<li style="text-align:center; padding:10px;">No data found</li>';
        }
        document.getElementById('leaderboard_list').innerHTML = leaderHTML;
    })
    .catch(error => {
        console.error('Error fetching data:', error);
        // Optional: Show error silently in console, don't break the UI
    });
}

function updateKPI(id, value, isMoney) {
    const el = document.getElementById(id);
    if (!el) return;
    el.classList.remove('loading');
    
    // Fallback if value is missing
    let safeValue = value || 0; 
    let formatted = safeValue;
    
    if(isMoney) {
        formatted = '₹' + new Intl.NumberFormat('en-IN').format(safeValue);
    } else {
        formatted = new Intl.NumberFormat('en-IN').format(safeValue);
    }
    el.innerText = formatted;
}

function updateChartData(chart, labels, dataArrays) {
    if (!labels) return; // Prevent crash if data is empty
    chart.data.labels = labels;
    dataArrays.forEach((datasetData, index) => {
        chart.data.datasets[index].data = datasetData || [];
    });
    chart.update('none'); 
}

// Initialize on page load
document.addEventListener("DOMContentLoaded", function() {
    initCharts();
    fetchData(); // Load immediately
    setInterval(fetchData, 5000); // Refresh every 5s
});
</script>
</body>
</html>