<!DOCTYPE html>
<html>
<head>
  <title>SOLOPOOLS 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: 12px 15px;
      margin-bottom: 15px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.06);
      transition: transform 0.2s;
    }
    
    .activity-item:hover {
      transform: translateX(5px);
    }
    
    .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;
    }
    
    .admin-badge {
      font-size: 0.75rem;
      background: linear-gradient(45deg, #6c757d, #495057);
      color: white;
      padding: 4px 8px;
      border-radius: 12px;
      margin-left: 8px;
      font-weight: 600;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    
    .activity-time {
      font-size: 0.75rem;
      color: #6c757d;
      font-weight: 500;
    }
    
    .activity-market {
      font-weight: 600;
      color: #495057;
    }
    
    .activity-admin {
      display: flex;
      align-items: center;
      margin-top: 5px;
      font-size: 0.8rem;
    }
    
    .admin-icon {
      margin-right: 5px;
      color: #6c757d;
    }
  </style>
</head>
<body>
  <!-- Sidebar -->
  <div id="sidebar">
    <div class="d-flex justify-content-between align-items-center px-3 py-3">
      <h4 class="mt-2">☘ SOLOPOOLS</h4>
      <button id="sidebarToggle" onclick="toggleSidebar()"><i class="fas fa-times"></i></button>
    </div>
    <a href="index.php" class="active"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
    <a href="add_result.php"><i class="fas fa-store"></i> Result</a>
    <a href="manage_admin.php"><i class="fas fa-user-shield"></i> Kelola Admin</a>
    <a href="result_time_setting.php"><i class="fas fa-list"></i> Kelola Pasaran</a>
    <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
  </div>

  <!-- 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">Memuat...</span>
          <span class="refresh-btn" onclick="loadMarketData()" 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">0</h3>
                <small><span id="market-trend"></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">0</h3>
                <small><span id="active-percent">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">0</h3>
                <small><span id="result-avg">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">0</h3>
                <small><span id="today-time-remaining"></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: 0</span>
              <span class="badge badge-secondary" id="filter-total">Total: 0</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>Last Activity</th>
                    <th>Aksi</th>
                  </tr>
                </thead>
                <tbody id="market-data">
                  <tr>
                    <td colspan="7" class="text-center py-4">
                      <div class="loading-spinner mr-2"></div>
                      Memuat data pasaran...
                    </td>
                  </tr>
                </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 d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-history mr-2"></i>Aktivitas Terbaru</h5>
            <span class="badge badge-light" id="activity-count">5 aktivitas</span>
          </div>
          <div class="card-body" style="max-height: 300px; overflow-y: auto;">
            <div id="recent-activity">
              <div class="activity-item">
                <div class="d-flex justify-content-between align-items-start">
                  <div class="font-weight-bold">Memuat aktivitas...</div>
                  <span class="activity-time">--</span>
                </div>
                <div class="text-muted small">Sistem sedang memuat data aktivitas</div>
              </div>
            </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>
    // Global variables
    let marketData = [];
    let chartInstances = {};
    let adminUsers = [];
    
    // 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 update the last updated time
    function updateLastUpdateTime() {
      const now = new Date();
      const formattedTime = now.toLocaleString('id-ID', {
        day: '2-digit',
        month: 'long',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
      document.getElementById('last-update-time').innerHTML = 
        `<i class="fas fa-clock mr-1"></i>Diperbarui: ${formattedTime}`;
    }
    
    // Function to format time ago
    function timeAgo(timestamp) {
      if (!timestamp) return '-';
      
      const date = new Date(timestamp);
      const now = new Date();
      const seconds = Math.floor((now - date) / 1000);
      
      if (seconds < 60) return 'Baru saja';
      
      const intervals = {
        tahun: 31536000,
        bulan: 2592000,
        minggu: 604800,
        hari: 86400,
        jam: 3600,
        menit: 60
      };
      
      for (const [unit, secondsInUnit] of Object.entries(intervals)) {
        const interval = Math.floor(seconds / secondsInUnit);
        if (interval >= 1) {
          return `${interval} ${unit} yang lalu`;
        }
      }
      
      return 'Baru saja';
    }
    
    // Function to validate admin name for activities
    function validateAdminName(adminName) {
      // Basic validation - check if admin name exists and is not empty
      if (!adminName || adminName.trim() === '') {
        return 'System';
      }
      
      // Check if admin exists in our admin list
      const adminExists = adminUsers.some(admin => admin.username === adminName.trim());
      
      // If admin doesn't exist, return 'System'
      if (!adminExists) {
        console.warn(`Admin '${adminName}' tidak ditemukan dalam database, menggunakan 'System' sebagai fallback`);
        return 'System';
      }
      
      // Return the validated admin name
      return adminName.trim();
    }
    
    // Function to load admin users from database
    function loadAdminUsers() {
      // In a real implementation, this would be an AJAX call to your backend
      // For demo purposes, we'll use sample data based on your database structure
      adminUsers = [
        { id: 1, username: 'admin' },
        { id: 2, username: 'admin2' },
        { id: 5, username: 'adminlivedraw' }
      ];
    }
    
    // Function to load market data
    function loadMarketData() {
      // Show loading state
      document.getElementById('market-data').innerHTML = `
        <tr>
          <td colspan="7" class="text-center py-4">
            <div class="loading-spinner mr-2"></div>
            Memuat data pasaran...
          </td>
        </tr>
      `;
      
      // Load admin users first
      loadAdminUsers();
      
      // Simulate API call with sample data
      setTimeout(() => {
        // Sample data - in real implementation, this would come from your backend
        marketData = [
          {
            id: 1,
            name: "SYDNEY",
            status: "active",
            resultTime: "13:50 WIB",
            lastDraw: "7854",
            firstPrize: "1234",
            lastResultDate: "2023-11-15",
            resultsCount: 42,
            lastActivity: new Date(Date.now() - 5 * 60000).toISOString() // 5 minutes ago
          },
          {
            id: 2,
            name: "SINGAPORE",
            status: "active",
            resultTime: "17:20 WIB",
            lastDraw: "9856",
            firstPrize: "5678",
            lastResultDate: "2023-11-15",
            resultsCount: 38,
            lastActivity: new Date(Date.now() - 30 * 60000).toISOString() // 30 minutes ago
          },
          {
            id: 3,
            name: "HONGKONG",
            status: "active",
            resultTime: "22:30 WIB",
            lastDraw: "3421",
            firstPrize: "9012",
            lastResultDate: "2023-11-15",
            resultsCount: 45,
            lastActivity: new Date(Date.now() - 2 * 3600000).toISOString() // 2 hours ago
          },
          {
            id: 4,
            name: "MACAU",
            status: "inactive",
            resultTime: "14:00 WIB",
            lastDraw: "0000",
            firstPrize: "-",
            lastResultDate: "2023-11-10",
            resultsCount: 28,
            lastActivity: new Date(Date.now() - 24 * 3600000).toISOString() // 1 day ago
          }
        ];
        
        // Update statistics
        updateStatistics(marketData);
        
        // Update market table
        updateMarketTable(marketData);
        
        // Update recent activity with admin validation
        updateRecentActivity(marketData);
        
        // Update charts
        updateCharts(marketData);
        
        // Update last update time
        updateLastUpdateTime();
      }, 1500);
    }
    
    // Function to update statistics
    function updateStatistics(data) {
      const totalMarkets = data.length;
      const activeMarkets = data.filter(m => m.status === 'active').length;
      const totalResults = data.reduce((acc, market) => acc + market.resultsCount, 0);
      const todayResults = Math.floor(Math.random() * 10) + 1; // Random for demo
      
      document.getElementById('total-markets').textContent = totalMarkets;
      document.getElementById('active-markets').textContent = activeMarkets;
      document.getElementById('total-results').textContent = totalResults.toLocaleString();
      document.getElementById('today-results').textContent = todayResults;
      
      // Additional stats
      document.getElementById('market-trend').textContent = '+2';
      document.getElementById('active-percent').textContent = 
        Math.round((activeMarkets / totalMarkets) * 100) + '%';
      document.getElementById('result-avg').textContent = 
        Math.round(totalResults / totalMarkets);
      
      // Update filter badges
      document.getElementById('filter-active').textContent = `Aktif: ${activeMarkets}`;
      document.getElementById('filter-total').textContent = `Total: ${totalMarkets}`;
      
      // Calculate time remaining for today's results
      const now = new Date();
      const hours = now.getHours();
      let timeRemaining = '';
      
      if (hours < 12) {
        timeRemaining = 'Siang hari';
      } else if (hours < 15) {
        timeRemaining = 'Sore hari';
      } else {
        timeRemaining = 'Malam hari';
      }
      
      document.getElementById('today-time-remaining').textContent = timeRemaining;
    }
    
    // Function to update market table
    function updateMarketTable(data) {
      const marketTableBody = document.getElementById('market-data');
      marketTableBody.innerHTML = '';
      
      if (data.length === 0) {
        marketTableBody.innerHTML = `
          <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>
        `;
        return;
      }
      
      data.forEach(market => {
        const statusClass = market.status === 'active' ? 'status-active' : 
                           market.status === 'inactive' ? 'status-inactive' : 'status-pending';
        const statusText = market.status === 'active' ? 'Aktif' : 
                          market.status === 'inactive' ? 'Nonaktif' : 'Tunda';
        
        const row = document.createElement('tr');
        row.innerHTML = `
          <td>
            <strong>${market.name}</strong>
          </td>
          <td>
            <span class="market-status ${statusClass}"></span>${statusText}
          </td>
          <td>${market.resultTime}</td>
          <td>#${market.lastDraw}</td>
          <td>
            <span class="badge badge-primary prize-badge">${market.firstPrize}</span>
          </td>
          <td>
            <small class="text-muted">${timeAgo(market.lastActivity)}</small>
          </td>
          <td>
            <button class="btn btn-sm btn-info" title="Detail">
              <i class="fas fa-eye"></i>
            </button>
            <button class="btn btn-sm btn-warning ml-1" title="Edit">
              <i class="fas fa-edit"></i>
            </button>
          </td>
        `;
        marketTableBody.appendChild(row);
      });
    }
    
    // Function to update recent activity with admin validation
    function updateRecentActivity(data) {
      // Get current admin name from session (in a real app, this would come from your backend)
      const currentAdmin = validateAdminName("<?= htmlspecialchars($_SESSION['username'] ?? 'System') ?>");
      
      const activities = [
        { 
          action: 'Result baru ditambahkan', 
          market: 'SYDNEY', 
          admin: currentAdmin,
          time: new Date(Date.now() - 5 * 60000).toISOString(),
          type: 'system'
        },
        { 
          action: 'Result diperbarui', 
          market: 'SINGAPORE', 
          admin: currentAdmin,
          time: new Date(Date.now() - 12 * 60000).toISOString(),
          type: 'system'
        },
        { 
          action: 'Pasaran dimodifikasi', 
          market: 'HONGKONG', 
          admin: validateAdminName("admin2"), // Valid admin from database
          time: new Date(Date.now() - 30 * 60000).toISOString(),
          type: 'warning'
        },
        { 
          action: 'Admin login', 
          market: null, 
          admin: currentAdmin,
          time: new Date(Date.now() - 60 * 60000).toISOString(),
          type: 'system'
        },
        { 
          action: 'Pasaran dinonaktifkan', 
          market: 'MACAU', 
          admin: validateAdminName("invalid_admin"), // Invalid admin name (will fallback to System)
          time: new Date(Date.now() - 24 * 3600000).toISOString(),
          type: 'danger'
        }
      ];
      
      const activityContainer = document.getElementById('recent-activity');
      activityContainer.innerHTML = '';
      
      // Update activity count
      document.getElementById('activity-count').textContent = `${activities.length} aktivitas`;
      
      if (activities.length === 0) {
        activityContainer.innerHTML = `
          <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>
        `;
        return;
      }
      
      activities.forEach(activity => {
        const activityItem = document.createElement('div');
        activityItem.className = `activity-item ${activity.type || ''}`;
        
        activityItem.innerHTML = `
          <div class="d-flex justify-content-between align-items-start mb-2">
            <div class="font-weight-bold text-dark">${activity.action}</div>
            <span class="activity-time">${timeAgo(activity.time)}</span>
          </div>
          <div class="d-flex justify-content-between align-items-end">
            <div>
              ${activity.market ? 
                `<span class="activity-market">${activity.market}</span>` : 
                `<span class="text-muted">Sistem</span>`
              }
              <div class="activity-admin">
                <i class="fas fa-user-circle admin-icon"></i>
                <span class="text-muted">Oleh: </span>
                <span class="admin-badge">${activity.admin}</span>
              </div>
            </div>
          </div>
        `;
        
        activityContainer.appendChild(activityItem);
      });
    }
    
    // Function to update charts
    function updateCharts(data) {
      updateQuickStatsChart(data);
    }
    
    // Function to update quick stats chart
    function updateQuickStatsChart(data) {
      const ctx = document.getElementById('quickStatsChart').getContext('2d');
      
      // Destroy previous chart if exists
      if (chartInstances.quickStats) {
        chartInstances.quickStats.destroy();
      }
      
      const activeCount = data.filter(m => m.status === 'active').length;
      const inactiveCount = data.filter(m => m.status === 'inactive').length;
      
      chartInstances.quickStats = new Chart(ctx, {
        type: 'doughnut',
        data: {
          labels: ['Aktif', 'Nonaktif'],
          datasets: [{
            data: [activeCount, inactiveCount],
            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%'
        }
      });
    }
    
    // Load data when page is ready
    $(document).ready(function() {
      loadMarketData();
      
      // Refresh data every 2 minutes
      setInterval(loadMarketData, 120000);
    });
  </script>
</body>
</html>