<?php
session_start();
require_once 'config.php'; // Pastikan file config.php sudah ada
date_default_timezone_set('Asia/Jakarta');

// Cek login
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

// Koneksi ke database
try {
    $db = new PDO('mysql:host=localhost;dbname=erniinrk_solo', 'erniinrk_solo', 'Kelentit123@');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Query untuk mengambil data market
$marketsQuery = "SELECT * FROM markets WHERE status = 1 ORDER BY display_order ASC, market_name ASC";
$marketsStmt = $db->prepare($marketsQuery);
$marketsStmt->execute();
$markets = $marketsStmt->fetchAll(PDO::FETCH_ASSOC);

// Query untuk mengambil data hasil lotere terbaru
$resultsQuery = "SELECT lr.market, lr.draw_number, lr.first_prize, lr.draw_date, lr.created_at 
                 FROM lottery_results lr 
                 INNER JOIN (
                     SELECT market, MAX(created_at) as latest_date 
                     FROM lottery_results 
                     GROUP BY market
                 ) latest ON lr.market = latest.market AND lr.created_at = latest.latest_date";
$resultsStmt = $db->prepare($resultsQuery);
$resultsStmt->execute();
$latestResults = $resultsStmt->fetchAll(PDO::FETCH_ASSOC);

// Hitung statistik
$totalMarkets = count($markets);
$activeMarkets = $totalMarkets; // Karena kita hanya mengambil yang status=1
$totalResults = 0;
$today = date('Y-m-d');
$todayResults = 0;

// Query untuk menghitung total results
$countResultsQuery = "SELECT COUNT(*) as total FROM lottery_results";
$countResultsStmt = $db->prepare($countResultsQuery);
$countResultsStmt->execute();
$totalResults = $countResultsStmt->fetch(PDO::FETCH_ASSOC)['total'];

// Query untuk menghitung results hari ini
$todayResultsQuery = "SELECT COUNT(*) as today_total FROM lottery_results WHERE DATE(created_at) = :today";
$todayResultsStmt = $db->prepare($todayResultsQuery);
$todayResultsStmt->execute([':today' => $today]);
$todayResults = $todayResultsStmt->fetch(PDO::FETCH_ASSOC)['today_total'];

// Gabungkan data market dengan hasil terbaru
$marketData = [];
foreach ($markets as $market) {
    $marketName = $market['market_name'];
    $latestResult = null;
    
    // Cari hasil terbaru untuk market ini
    foreach ($latestResults as $result) {
        if ($result['market'] === $marketName) {
            $latestResult = $result;
            break;
        }
    }
    
    $marketData[] = [
        'id' => $market['id'],
        'name' => $marketName,
        'display_name' => $market['display_name'] ?? $market['market_name'],
        'status' => $market['status'],
        'result_time' => $market['result_time'] ?? '14:30:00',
        'lastDraw' => $latestResult['draw_number'] ?? '0000',
        'firstPrize' => $latestResult['first_prize'] ?? '-',
        'lastResultDate' => $latestResult['draw_date'] ?? '-',
        'lastActivity' => $latestResult['created_at'] ?? null,
        'resultsCount' => 0 // Bisa ditambahkan query khusus untuk menghitung per market
    ];
}

// Query untuk menghitung jumlah results per market
foreach ($marketData as &$market) {
    $countQuery = "SELECT COUNT(*) as count FROM lottery_results WHERE market = :market";
    $countStmt = $db->prepare($countQuery);
    $countStmt->execute([':market' => $market['name']]);
    $result = $countStmt->fetch(PDO::FETCH_ASSOC);
    $market['resultsCount'] = $result['count'];
}
unset($market); // Unset reference

// Aktivitas terbaru (dari log atau tabel tertentu)
$activitiesQuery = "SELECT 'Result baru ditambahkan' as action, market, admin_name, created_at as time 
                    FROM lottery_results 
                    ORDER BY created_at DESC 
                    LIMIT 5";
$activitiesStmt = $db->prepare($activitiesQuery);
$activitiesStmt->execute();
$recentActivities = $activitiesStmt->fetchAll(PDO::FETCH_ASSOC);

// Jika tidak ada kolom admin_name, kita bisa gunakan session username sebagai fallback
foreach ($recentActivities as &$activity) {
    if (empty($activity['admin_name'])) {
        $activity['admin_name'] = $_SESSION['username'];
    }
    
    // Konversi waktu ke zona Indonesia
    $activityTime = new DateTime($activity['time'], new DateTimeZone('UTC'));
    $activityTime->setTimezone(new DateTimeZone('Asia/Jakarta'));
    $activity['time'] = $activityTime->format('Y-m-d H:i:s');
}
unset($activity); // Unset reference
?>

<!DOCTYPE html>
<html>
<head>
  <title>SOLO POOLS Admin</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css" rel="stylesheet">
  <style>
    body {
      display: flex;
      background-color: #f8f9fa;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    #sidebar {
      width: 250px;
      background: linear-gradient(to bottom, #343a40, #2c3136);
      color: white;
      min-height: 100vh;
      padding-top: 1rem;
      transition: all 0.3s;
      box-shadow: 2px 0 10px rgba(0,0,0,0.1);
    }

    #sidebar a {
      color: rgba(255,255,255,0.8);
      display: block;
      padding: 12px 20px;
      text-decoration: none;
      transition: all 0.3s;
      border-left: 3px solid transparent;
    }

    #sidebar a:hover {
      background: rgba(255,255,255,0.05);
      color: white;
      border-left: 3px solid #007bff;
    }

    #sidebar a.active {
      background: rgba(255,255,255,0.1);
      color: white;
      border-left: 3px solid #007bff;
    }

    #content {
      flex-grow: 1;
      padding: 20px;
      overflow-x: auto;
    }

    #sidebarToggle {
      background: none;
      border: none;
      color: white;
      font-size: 1.5rem;
      margin-left: 10px;
      cursor: pointer;
    }

    .stat-card {
      border-radius: 12px;
      box-shadow: 0 5px 15px rgba(0,0,0,0.08);
      transition: transform 0.3s, box-shadow 0.3s;
      border: none;
      overflow: hidden;
    }
    
    .stat-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 25px rgba(0,0,0,0.12);
    }
    
    .stat-card .card-body {
      padding: 1.5rem;
    }
    
    .market-table {
      font-size: 0.9rem;
      border-collapse: separate;
      border-spacing: 0;
    }
    
    .market-table th {
      background-color: #f8f9fa;
      font-weight: 600;
      padding: 12px 15px;
    }
    
    .market-table td {
      padding: 12px 15px;
      vertical-align: middle;
    }
    
    .market-table tr:hover {
      background-color: rgba(0,123,255,0.03);
    }
    
    .last-update {
      font-size: 0.8rem;
      color: #6c757d;
    }
    
    .dashboard-header {
      background: linear-gradient(45deg, #343a40, #2c3136);
      color: white;
      padding: 1.5rem;
      border-radius: 10px;
      margin-bottom: 2rem;
      box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }
    
    .activity-item {
      border-left: 3px solid #007bff;
      padding: 10px 15px;
      margin-bottom: 15px;
      background: white;
      border-radius: 5px;
      box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    }
    
    .activity-item.system {
      border-left-color: #28a745;
    }
    
    .activity-item.warning {
      border-left-color: #ffc107;
    }
    
    .activity-item.danger {
      border-left-color: #dc3545;
    }
    
    .market-status {
      display: inline-block;
      width: 10px;
      height: 10px;
      border-radius: 50%;
      margin-right: 5px;
    }
    
    .status-active {
      background-color: #28a745;
    }
    
    .status-inactive {
      background-color: #dc3545;
    }
    
    .status-pending {
      background-color: #ffc107;
    }
    
    .prize-badge {
      font-size: 0.85rem;
      font-weight: bold;
      letter-spacing: 1px;
    }
    
    .refresh-btn {
      cursor: pointer;
      transition: transform 0.5s;
    }
    
    .refresh-btn:hover {
      transform: rotate(180deg);
    }
    
    .loading-spinner {
      display: inline-block;
      width: 1rem;
      height: 1rem;
      border: 2px solid #f3f3f3;
      border-top: 2px solid #3498db;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
    
    .chart-container {
      position: relative;
      height: 250px;
    }
  </style>
</head>
<body>
<?php include 'navbar.php'; ?>


  <!-- Content -->
  <div id="content">
    <div class="dashboard-header">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <h2 class="mb-1">Dashboard Admin</h2>
          <p class="mb-0">Selamat datang, <?= htmlspecialchars($_SESSION['username']) ?> - Pantau semua aktivitas pasaran Anda di sini</p>
        </div>
        <div>
          <span class="last-update mr-2" id="last-update-time">
            <i class="fas fa-clock mr-1"></i>Diperbarui: <?= date('d F Y H:i') ?>
          </span>
          <span class="refresh-btn" onclick="location.reload()" title="Refresh Data">
            <i class="fas fa-sync-alt"></i>
          </span>
        </div>
      </div>
    </div>
    
    <!-- Statistics Cards -->
    <div class="row mb-4">
      <div class="col-md-3 mb-3">
        <div class="card stat-card bg-primary text-white">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <h6 class="card-title">Total Pasaran</h6>
                <h3 id="total-markets"><?= $totalMarkets ?></h3>
                <small><span id="market-trend">+0</span> dari bulan lalu</small>
              </div>
              <i class="fas fa-store fa-2x opacity-50"></i>
            </div>
          </div>
        </div>
      </div>
      
      <div class="col-md-3 mb-3">
        <div class="card stat-card bg-success text-white">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <h6 class="card-title">Pasaran Aktif</h6>
                <h3 id="active-markets"><?= $activeMarkets ?></h3>
                <small><span id="active-percent"><?= $totalMarkets > 0 ? round(($activeMarkets / $totalMarkets) * 100) : 0 ?>%</span> dari total</small>
              </div>
              <i class="fas fa-check-circle fa-2x opacity-50"></i>
            </div>
          </div>
        </div>
      </div>
      
      <div class="col-md-3 mb-3">
        <div class="card stat-card bg-warning text-dark">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <h6 class="card-title">Total Result</h6>
                <h3 id="total-results"><?= $totalResults ?></h3>
                <small><span id="result-avg"><?= $totalMarkets > 0 ? round($totalResults / $totalMarkets) : 0 ?></span> rata-rata per pasaran</small>
              </div>
              <i class="fas fa-chart-bar fa-2x opacity-50"></i>
            </div>
          </div>
        </div>
      </div>
      
      <div class="col-md-3 mb-3">
        <div class="card stat-card bg-info text-white">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <h6 class="card-title">Result Hari Ini</h6>
                <h3 id="today-results"><?= $todayResults ?></h3>
                <small><span id="today-time-remaining">
                  <?php
                  $hours = date('H');
                  if ($hours < 12) {
                      echo 'Pagi hari';
                  } else if ($hours < 15) {
                      echo 'Siang hari';
                  } else if ($hours < 18) {
                      echo 'Sore hari';
                  } else {
                      echo 'Malam hari';
                  }
                  ?>
                </span></small>
              </div>
              <i class="fas fa-calendar-day fa-2x opacity-50"></i>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="row">
      <!-- Market List -->
      <div class="col-lg-8 mb-4">
        <div class="card">
          <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-list mr-2"></i>Daftar Pasaran Aktif</h5>
            <div>
              <span class="badge badge-light mr-2" id="filter-active">Aktif: <?= $activeMarkets ?></span>
              <span class="badge badge-secondary" id="filter-total">Total: <?= $totalMarkets ?></span>
            </div>
          </div>
          <div class="card-body p-0">
            <div class="table-responsive">
              <table class="table table-hover market-table mb-0">
                <thead>
                  <tr>
                    <th>Nama Pasaran</th>
                    <th>Status</th>
                    <th>Waktu Result</th>
                    <th>Draw Terakhir</th>
                    <th>Result Terakhir</th>
                    <th>Total Result</th>
                    <th>Aksi</th>
                  </tr>
                </thead>
                <tbody id="market-data">
                  <?php if (count($marketData) > 0): ?>
                    <?php foreach ($marketData as $market): ?>
                      <tr>
                        <td>
                          <strong><?= htmlspecialchars($market['display_name']) ?></strong>
                        </td>
                        <td>
                          <span class="market-status status-active"></span>Aktif
                        </td>
                        <td><?= substr($market['result_time'], 0, 5) ?></td>
                        <td>#<?= htmlspecialchars($market['lastDraw']) ?></td>
                        <td>
                          <span class="badge badge-primary prize-badge"><?= htmlspecialchars($market['firstPrize']) ?></span>
                        </td>
                        <td>
                          <span class="badge badge-info"><?= $market['resultsCount'] ?></span>
                        </td>
                        <td>
                            <button class="btn btn-sm btn-info" title="Detail" onclick="viewMarket(<?= $market['id'] ?>)">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-sm btn-warning ml-1" title="Edit Market" onclick="editMarket(<?= $market['id'] ?>)">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-primary ml-1" title="Edit Display Name" onclick="editDisplayName(<?= $market['id'] ?>)">
                                <i class="fas fa-tag"></i>
                            </button>
                        </td>
                      </tr>
                    <?php endforeach; ?>
                  <?php else: ?>
                    <tr>
                      <td colspan="7" class="text-center py-4">
                        <i class="fas fa-inbox fa-2x mb-2 text-muted"></i>
                        <p class="text-muted">Tidak ada data pasaran</p>
                      </td>
                    </tr>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
      
      <!-- Recent Activity & Stats -->
      <div class="col-lg-4 mb-4">
        <!-- Recent Activity -->
        <div class="card mb-4">
          <div class="card-header bg-dark text-white">
            <h5 class="mb-0"><i class="fas fa-history mr-2"></i>Aktivitas Terbaru</h5>
          </div>
          <div class="card-body" style="max-height: 300px; overflow-y: auto;">
        <div id="recent-activity">
          <?php if (count($recentActivities) > 0): ?>
            <?php foreach ($recentActivities as $activity): ?>
              <div class="activity-item">
                <div class="d-flex justify-content-between">
                  <div class="font-weight-bold"><?= htmlspecialchars($activity['action']) ?></div>
                  <span class="text-muted">
                    <?php
                    $activityTime = new DateTime($activity['time']);
                    $now = new DateTime();
                    $interval = $now->diff($activityTime);
                    
                    if ($interval->d > 0) {
                        echo $interval->d . ' hari lalu';
                    } else if ($interval->h > 0) {
                        echo $interval->h . ' jam lalu';
                    } else if ($interval->i > 0) {
                        echo $interval->i . ' menit lalu';
                    } else {
                        echo 'Baru saja';
                    }
                    ?>
                  </span>
                </div>
                <div class="text-muted small">
                  Untuk pasaran <strong><?= htmlspecialchars($activity['market']) ?></strong>
                  oleh <strong><?= htmlspecialchars($activity['admin_name']) ?></strong>
                </div>
              </div>
            <?php endforeach; ?>
          <?php else: ?>
            <div class="text-center text-muted py-3">
              <i class="fas fa-inbox fa-2x mb-2"></i>
              <p>Tidak ada aktivitas terbaru</p>
            </div>
              <?php endif; ?>
            </div>
          </div>
        </div>
        
        <!-- Quick Stats -->
        <div class="card">
          <div class="card-header bg-dark text-white">
            <h5 class="mb-0"><i class="fas fa-chart-pie mr-2"></i>Statistik Cepat</h5>
          </div>
          <div class="card-body">
            <canvas id="quickStatsChart" height="200"></canvas>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  
  <script>
    // Function to toggle sidebar
    function toggleSidebar() {
      const sidebar = document.getElementById("sidebar");
      const isHidden = sidebar.style.display === "none";
      sidebar.style.display = isHidden ? "block" : "none";
      document.getElementById("sidebarToggle").innerHTML = isHidden ? 
        '<i class="fas fa-times"></i>' : '<i class="fas fa-bars"></i>';
    }

    // Function to view market details
    function viewMarket(marketId) {
      alert('Lihat detail market ID: ' + marketId);
      // window.location.href = 'market_detail.php?id=' + marketId;
    }

    // Function to edit market
    function editMarket(marketId) {
      alert('Edit market ID: ' + marketId);
      // window.location.href = 'edit_market.php?id=' + marketId;
    }
    
    function editDisplayName(marketId) {
        window.location.href = 'edit_market_display.php?id=' + marketId;
    }

    // Initialize chart
    document.addEventListener('DOMContentLoaded', function() {
      const ctx = document.getElementById('quickStatsChart').getContext('2d');
      
      // Data for chart
      const activeMarkets = <?= $activeMarkets ?>;
      const totalMarkets = <?= $totalMarkets ?>;
      
      const chart = new Chart(ctx, {
        type: 'doughnut',
        data: {
          labels: ['Aktif', 'Nonaktif'],
          datasets: [{
            data: [activeMarkets, totalMarkets - activeMarkets],
            backgroundColor: [
              'rgba(40, 167, 69, 0.8)',
              'rgba(220, 53, 69, 0.8)'
            ],
            borderColor: [
              'rgba(40, 167, 69, 1)',
              'rgba(220, 53, 69, 1)'
            ],
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              position: 'bottom'
            }
          },
          cutout: '70%'
        }
      });
    });

    // Auto refresh every 2 minutes
    setInterval(function() {
      // Optionally refresh only specific parts of the page
      console.log('Auto refresh at: ' + new Date().toLocaleTimeString());
    }, 120000);
  </script>
</body>
</html>