<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dashboard Overview | CMS Admin SMK Teratai Putih 3</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
  <link rel="stylesheet" href="/css/admin.css">
  <style>
    /* Toast Notification Styles */
    #toastContainer {
      position: fixed;
      bottom: 2rem;
      right: 2rem;
      z-index: 9999;
      display: flex;
      flex-direction: column;
      gap: 1rem;
    }
    .ppdb-toast {
      background: #fff;
      border-left: 5px solid #22c55e;
      border-radius: var(--radius-sm);
      box-shadow: 0 10px 25px rgba(0,0,0,0.1);
      padding: 1.25rem;
      width: 350px;
      transform: translateX(120%);
      transition: transform 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
    }
    .ppdb-toast.show {
      transform: translateX(0);
    }
    .ppdb-toast-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0.5rem;
    }
    .ppdb-toast-header h4 {
      margin: 0;
      color: #1e293b;
      font-size: 1rem;
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }
    .ppdb-toast-body {
      color: #64748b;
      font-size: 0.9rem;
      margin-bottom: 1rem;
    }
    .btn-close-toast {
      background: none;
      border: none;
      color: #94a3b8;
      cursor: pointer;
    }
  </style>
</head>
<body>

  <div class="admin-wrapper">
    <%- include('partials/admin-sidebar') %>

    <div class="admin-content">
      <%- include('partials/admin-header', { title: 'Dashboard Overview' }) %>

      <main class="admin-main">
        
        <!-- STATS GRID -->
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-icon bg-blue">
              <i class="fa-solid fa-file-pdf"></i>
            </div>
            <div class="stat-info">
              <span class="stat-label">Brosur PPDB Aktif</span>
              <h3 class="stat-value"><%= stats.brosur.filename ? 'Tersedia' : 'Kosong' %></h3>
              <span class="stat-desc">Ukuran: <%= stats.brosur.fileSize || '0 MB' %></span>
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-icon bg-green">
              <i class="fa-solid fa-newspaper"></i>
            </div>
            <div class="stat-info">
              <span class="stat-label">Total Berita & Pengumuman</span>
              <h3 class="stat-value"><%= stats.totalNews %> Artikel</h3>
              <span class="stat-desc">Konten Berita Aktif</span>
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-icon bg-amber">
              <i class="fa-brands fa-google"></i>
            </div>
            <div class="stat-info">
              <span class="stat-label">Ulasan Google Maps</span>
              <h3 class="stat-value"><%= stats.totalReviews %> Ulasan</h3>
              <span class="stat-desc">Terhubung Langsung</span>
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-icon bg-purple">
              <i class="fa-solid fa-users"></i>
            </div>
            <div class="stat-info">
              <span class="stat-label">Pendaftar PPDB Online</span>
              <h3 class="stat-value"><%= stats.totalLeads %> Calon Siswa</h3>
              <span class="stat-desc">Formulir Terisi</span>
            </div>
          </div>
        </div>

        <!-- QUICK ACTIONS & BROCHURE STATUS -->
        <div class="grid-2col" style="margin-top: 2rem;">
          
          <div class="card">
            <div class="card-header">
              <h3><i class="fa-solid fa-file-pdf text-red"></i> Kelola Brosur PPDB Sekolah</h3>
              <a href="/admin/brosur" class="btn-sm btn-primary">Buka Manajer Brosur</a>
            </div>
            <div class="card-body">
              <div class="brosur-preview-box">
                <div class="pdf-icon-large"><i class="fa-solid fa-file-pdf"></i></div>
                <div class="brosur-details">
                  <h4><%= stats.brosur.title || 'Brosur PPDB SMK Teratai Putih Global 3' %></h4>
                  <p>File: <code><%= stats.brosur.filename || 'brosur.pdf' %></code> | Ukuran: <%= stats.brosur.fileSize || '2.4 MB' %></p>
                  <p class="text-muted">Terakhir Diperbarui: <%= stats.brosur.lastUpdated || 'Baru Saja' %></p>
                </div>
              </div>
              <div style="margin-top: 1rem; display: flex; gap: 0.5rem;">
                <a href="/uploads/brosur.pdf" target="_blank" class="btn btn-outline-secondary">
                  <i class="fa-solid fa-eye"></i> Pratinjau Brosur Saat Ini
                </a>
                <a href="/download/brosur" class="btn btn-outline-primary">
                  <i class="fa-solid fa-download"></i> Tes Unduh Brosur
                </a>
              </div>
            </div>
          </div>

          <div class="card">
            <div class="card-header">
              <h3><i class="fa-solid fa-bolt text-gold"></i> Akses Cepat CMS Admin</h3>
            </div>
            <div class="card-body">
              <div class="quick-links-grid">
                <a href="/admin/brosur" class="quick-link-item">
                  <div class="ql-icon"><i class="fa-solid fa-upload"></i></div>
                  <div class="ql-text">
                    <strong>Ganti Brosur PPDB</strong>
                    <span>Upload PDF Brosur Terbaru</span>
                  </div>
                </a>

                <a href="/admin/berita" class="quick-link-item">
                  <div class="ql-icon"><i class="fa-solid fa-plus-circle"></i></div>
                  <div class="ql-text">
                    <strong>Tambah Berita Baru</strong>
                    <span>Publikasi Pengumuman / Kegiatan</span>
                  </div>
                </a>

                <a href="/admin/ulasan" class="quick-link-item">
                  <div class="ql-icon"><i class="fa-brands fa-google"></i></div>
                  <div class="ql-text">
                    <strong>Kelola Ulasan Google Maps</strong>
                    <span>Tambah & Edit Kartu Ulasan</span>
                  </div>
                </a>

                <a href="/admin/ppdb-leads" class="quick-link-item">
                  <div class="ql-icon"><i class="fa-solid fa-file-excel"></i></div>
                  <div class="ql-text">
                    <strong>Export Data PPDB</strong>
                    <span>Unduh CSV Pendaftar Online</span>
                  </div>
                </a>
              </div>
            </div>
          </div>

        </div>

        <!-- RECENT PPDB LEADS TABLE -->
        <div class="card" style="margin-top: 2rem;">
          <div class="card-header">
            <h3><i class="fa-solid fa-clock-rotate-left"></i> Pendaftar PPDB Terbaru</h3>
            <a href="/admin/ppdb-leads" class="btn-sm btn-outline-secondary">Lihat Semua Data (<%= stats.totalLeads %>)</a>
          </div>
          <div class="card-body p-0">
            <% if (recentLeads && recentLeads.length > 0) { %>
              <div class="table-responsive">
                <table class="admin-table">
                  <thead>
                    <tr>
                      <th>Waktu</th>
                      <th>Nama Lengkap</th>
                      <th>SMP Asal</th>
                      <th>Jurusan Pilihan</th>
                      <th>No WhatsApp</th>
                    </tr>
                  </thead>
                  <tbody>
                    <% recentLeads.forEach(lead => { 
                      const nama = lead.fullname || lead.nama || '-';
                      const sekolah = lead.school_origin || lead.asalSekolah || '-';
                      const jurusan = lead.major || lead.pilihanJurusan || '-';
                      const tanggal = lead.date || lead.registeredAt || 'Terbaru';
                      const wa = lead.whatsapp || '';
                    %>
                      <tr>
                        <td><%= tanggal %></td>
                        <td><strong><%= nama %></strong></td>
                        <td><%= sekolah %></td>
                        <td><span class="badge badge-major"><%= jurusan %></span></td>
                        <td><a href="https://wa.me/<%= wa.replace(/^0/, '62') %>" target="_blank" class="text-success"><i class="fa-brands fa-whatsapp"></i> <%= wa %></a></td>
                      </tr>
                    <% }); %>
                  </tbody>
                </table>
              </div>
            <% } else { %>
              <p class="p-3 text-muted text-center">Belum ada data pendaftar baru.</p>
            <% } %>
          </div>
        </div>

      </main>
    </div>
  </div>
  
  <div id="toastContainer"></div>

  <script>
    document.addEventListener('DOMContentLoaded', () => {
      let lastKnownId = null;

      // Initial check to set the baseline
      fetch('/api/ppdb/latest-count')
        .then(res => res.json())
        .then(data => {
          if (data.latestId) {
            lastKnownId = data.latestId;
          }
        })
        .catch(err => console.error('Error fetching initial PPDB count:', err));

      // Poll every 10 seconds
      setInterval(() => {
        fetch('/api/ppdb/latest-count')
          .then(res => res.json())
          .then(data => {
            if (data.latestId && lastKnownId && data.latestId !== lastKnownId) {
              // We have a new lead!
              lastKnownId = data.latestId;
              showToast(data);
              
              // Optionally refresh the dashboard page automatically or update table
              // location.reload(); 
            } else if (data.latestId && !lastKnownId) {
              lastKnownId = data.latestId;
            }
          })
          .catch(err => console.error('Error polling PPDB:', err));
      }, 10000);

      function showToast(data) {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = 'ppdb-toast';
        
        // Buat waNotifyLink dinamis (jika admin ingin forward info pendaftar ke pimpinan/nomor lain)
        // Atau ini murni notifikasi untuk admin itu sendiri.
        const dateStr = encodeURIComponent(data.latestTime);
        const nameStr = encodeURIComponent(data.latestName);
        const waText = `[NOTIFIKASI SISTEM]%0A%0AAdmin, ada pendaftar PPDB BARU di website!%0A%0ANama: ${nameStr}%0AWaktu: ${dateStr}%0A%0ASilakan cek Dashboard Admin untuk detailnya.`;
        const adminWa = "6281234567890"; // Kita ambil dummy dulu jika tidak dipass dari server
        const notifyLink = `https://wa.me/${adminWa}?text=${waText}`;

        toast.innerHTML = `
          <div class="ppdb-toast-header">
            <h4><i class="fa-solid fa-bell text-green"></i> Pendaftar Baru!</h4>
            <button class="btn-close-toast" onclick="this.parentElement.parentElement.remove()"><i class="fa-solid fa-xmark"></i></button>
          </div>
          <div class="ppdb-toast-body">
            Calon siswa <strong>${data.latestName}</strong> baru saja mendaftar PPDB Online.
          </div>
          <div>
            <a href="/admin/ppdb-leads" class="btn-sm btn-primary" style="display: block; text-align: center; margin-bottom: 0.5rem;">Lihat Detail di CMS</a>
          </div>
        `;
        
        container.appendChild(toast);
        
        // Trigger animation
        setTimeout(() => toast.classList.add('show'), 100);
        
        // Auto hide after 30 seconds
        setTimeout(() => {
          toast.classList.remove('show');
          setTimeout(() => toast.remove(), 400);
        }, 30000);
      }
    });
  </script>
</body>
</html>
