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

// Ensure reviews table exists
$pdo->exec("CREATE TABLE IF NOT EXISTS `reviews` (
  `id` INT AUTO_INCREMENT PRIMARY KEY,
  `user_id` INT NOT NULL,
  `rating` TINYINT NOT NULL,
  `title` VARCHAR(150) NOT NULL,
  `body` TEXT NOT NULL,
  `is_approved` TINYINT(1) DEFAULT 0,
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB;");

// ── AJAX actions ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';
    $id     = (int)($_POST['id'] ?? 0);
    if ($action === 'approve') {
        $pdo->prepare("UPDATE reviews SET is_approved=1 WHERE id=?")->execute([$id]);
        jsonResponse(['success' => true, 'msg' => 'Review approved successfully.']);
    }
    if ($action === 'reject') {
        $pdo->prepare("UPDATE reviews SET is_approved=0 WHERE id=?")->execute([$id]);
        jsonResponse(['success' => true, 'msg' => 'Review unpublished.']);
    }
    if ($action === 'delete') {
        $pdo->prepare("DELETE FROM reviews WHERE id=?")->execute([$id]);
        jsonResponse(['success' => true, 'msg' => 'Review deleted.']);
    }
    if ($action === 'trigger_popup') {
        // Set popup_active = 1 in site_settings
        $pdo->prepare("INSERT INTO site_settings (setting_key,setting_value) VALUES ('review_popup_enabled','1')
                       ON DUPLICATE KEY UPDATE setting_value='1'")->execute();
        jsonResponse(['success' => true, 'msg' => 'Review popup triggered! Users will see it on next page load.']);
    }
    if ($action === 'dismiss_popup') {
        $pdo->prepare("INSERT INTO site_settings (setting_key,setting_value) VALUES ('review_popup_enabled','0')
                       ON DUPLICATE KEY UPDATE setting_value='0'")->execute();
        jsonResponse(['success' => true, 'msg' => 'Review popup disabled.']);
    }
    jsonResponse(['success' => false, 'msg' => 'Unknown action.']);
}

// ── Popup status ──
$popupRow = $pdo->query("SELECT setting_value FROM site_settings WHERE setting_key='review_popup_enabled'")->fetch();
$popupActive = $popupRow ? (int)$popupRow['setting_value'] : 0;

// ── Filters ──
$filter = $_GET['filter'] ?? 'pending'; // pending | approved | all
$search = trim($_GET['search'] ?? '');

$where  = [];
$params = [];
if ($filter === 'pending')  { $where[] = "r.is_approved = 0"; }
if ($filter === 'approved') { $where[] = "r.is_approved = 1"; }
if ($search) {
    $where[] = "(u.name LIKE ? OR r.title LIKE ? OR r.body LIKE ?)";
    $params  = array_merge($params, ["%$search%", "%$search%", "%$search%"]);
}
$whereSQL = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$reviews = $pdo->prepare("
    SELECT r.*, u.name AS uname, u.email AS uemail, u.avatar AS uavatar
    FROM reviews r
    JOIN users u ON u.id = r.user_id
    $whereSQL
    ORDER BY r.is_approved ASC, r.created_at DESC
");
$reviews->execute($params);
$reviews = $reviews->fetchAll();

// Counts
$totalAll      = (int)$pdo->query("SELECT COUNT(*) FROM reviews")->fetchColumn();
$totalPending  = (int)$pdo->query("SELECT COUNT(*) FROM reviews WHERE is_approved=0")->fetchColumn();
$totalApproved = (int)$pdo->query("SELECT COUNT(*) FROM reviews WHERE is_approved=1")->fetchColumn();
$avgRating     = (float)$pdo->query("SELECT AVG(rating) FROM reviews WHERE is_approved=1")->fetchColumn();

require_once 'includes/header.php';
renderAdminHeader('Review Moderation', 'reviews');
?>

<!-- Toast Container -->
<div id="toastContainer" style="position:fixed;top:20px;right:20px;z-index:9999;display:flex;flex-direction:column;gap:10px;pointer-events:none"></div>

<!-- Stats -->
<div class="stats-grid" style="margin-bottom:24px">
  <div class="stat-card">
    <div class="stat-icon" style="background:rgba(245,158,11,0.15)">⏳</div>
    <div class="stat-value"><?= $totalPending ?></div>
    <div class="stat-label">Pending Approval</div>
    <?php if ($totalPending > 0): ?>
    <div class="stat-change" style="color:#f59e0b">Needs review</div>
    <?php endif; ?>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:rgba(16,185,129,0.15)">✅</div>
    <div class="stat-value"><?= $totalApproved ?></div>
    <div class="stat-label">Published Reviews</div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:rgba(99,102,241,0.15)">⭐</div>
    <div class="stat-value"><?= $totalApproved > 0 ? number_format($avgRating, 1) : '–' ?></div>
    <div class="stat-label">Average Rating</div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:rgba(34,211,238,0.15)">💬</div>
    <div class="stat-value"><?= $totalAll ?></div>
    <div class="stat-label">Total Submitted</div>
  </div>
</div>

<!-- Filters + Search -->
<div class="card" style="margin-bottom:20px">
  <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px">
    <!-- Filter tabs -->
    <div style="display:flex;gap:6px;flex-wrap:wrap">
      <?php foreach ([['pending','⏳ Pending','#f59e0b'],['approved','✅ Approved','#10b981'],['all','💬 All',null]] as [$f,$label,$col]): ?>
      <a href="?filter=<?= $f ?>&search=<?= urlencode($search) ?>"
         style="padding:7px 16px;border-radius:8px;font-size:13px;font-weight:600;border:1px solid;text-decoration:none;transition:all .2s;
                <?= $filter===$f ? 'background:rgba('.($f==='pending'?'245,158,11':'10,185,129').', 0.15);color:'.($col??'var(--text-primary)').';border-color:'.($col??'var(--accent)') : 'background:transparent;color:var(--text-muted);border-color:var(--border)' ?>">
        <?= $label ?> <?= $f==='pending'?'('.$totalPending.')':($f==='approved'?'('.$totalApproved.')':'('.$totalAll.')') ?>
      </a>
      <?php endforeach; ?>
    </div>
    <!-- Search -->
    <form method="GET" style="display:flex;gap:8px;min-width:240px">
      <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
      <input type="text" name="search" class="form-control" placeholder="Search reviews…" value="<?= htmlspecialchars($search) ?>" style="flex:1">
      <button type="submit" class="btn btn-primary">Search</button>
    </form>
  </div>
</div>

<!-- Reviews Table -->
<div class="card">
  <div class="card-header">
    <div class="card-title">
      <?= ucfirst($filter) ?> Reviews
      <span style="font-size:13px;font-weight:400;color:var(--text-muted);margin-left:8px"><?= count($reviews) ?> found</span>
    </div>
    <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
      <?php if ($popupActive): ?>
        <span style="display:inline-flex;align-items:center;gap:5px;padding:4px 12px;border-radius:99px;font-size:12px;font-weight:700;background:rgba(16,185,129,.12);color:#10b981;border:1px solid rgba(16,185,129,.2)">🟢 Popup Active</span>
        <button class="btn btn-secondary btn-sm" onclick="dismissPopup()">🔕 Deactivate Popup</button>
      <?php else: ?>
        <span style="display:inline-flex;align-items:center;gap:5px;padding:4px 12px;border-radius:99px;font-size:12px;font-weight:700;background:rgba(100,100,100,.12);color:var(--text-muted);border:1px solid var(--border)">⚫ Popup Inactive</span>
        <button class="btn btn-primary btn-sm" onclick="triggerPopup()" style="background:linear-gradient(135deg,#7c3aed,#4f46e5)!important;border:none!important">🔔 Trigger Review Popup</button>
      <?php endif; ?>
      <?php if ($filter === 'pending' && $totalPending > 0): ?>
      <button class="btn btn-primary btn-sm" onclick="approveAll()">✅ Approve All Pending</button>
      <?php endif; ?>
    </div>
  </div>

  <?php if (empty($reviews)): ?>
  <div class="empty-state">
    <div class="empty-icon"><?= $filter==='pending' ? '🎉' : '💬' ?></div>
    <h3><?= $filter==='pending' ? 'No pending reviews!' : 'No reviews found' ?></h3>
    <p><?= $filter==='pending' ? 'All caught up — nothing to moderate.' : 'Try a different filter or search term.' ?></p>
  </div>
  <?php else: ?>
  <div class="table-wrapper">
    <table>
      <thead>
        <tr>
          <th>Student</th>
          <th>Rating</th>
          <th>Review</th>
          <th>Date</th>
          <th>Status</th>
          <th style="text-align:right">Actions</th>
        </tr>
      </thead>
      <tbody id="reviewsBody">
      <?php foreach ($reviews as $rv): ?>
      <tr id="row-<?= $rv['id'] ?>">
        <!-- Student -->
        <td>
          <div style="display:flex;align-items:center;gap:10px">
            <div style="width:38px;height:38px;border-radius:50%;background:linear-gradient(135deg,var(--accent),#9333ea);display:flex;align-items:center;justify-content:center;font-weight:800;font-size:15px;color:#fff;flex-shrink:0;overflow:hidden">
              <?php if ($rv['uavatar']): ?>
                <img src="<?= htmlspecialchars($rv['uavatar']) ?>" style="width:100%;height:100%;object-fit:cover">
              <?php else: ?>
                <?= strtoupper(substr($rv['uname'],0,1)) ?>
              <?php endif; ?>
            </div>
            <div>
              <div style="font-weight:600;color:var(--text-primary);font-size:14px"><?= htmlspecialchars($rv['uname']) ?></div>
              <div style="font-size:12px;color:var(--text-muted)"><?= htmlspecialchars($rv['uemail']) ?></div>
            </div>
          </div>
        </td>
        <!-- Rating -->
        <td>
          <div style="display:flex;gap:2px;margin-bottom:2px">
            <?php for ($i=1;$i<=5;$i++): ?>
              <span style="font-size:14px;color:<?= $i<=$rv['rating'] ? '#f59e0b' : 'var(--border)' ?>">★</span>
            <?php endfor; ?>
          </div>
          <div style="font-size:12px;color:var(--text-muted)"><?= $rv['rating'] ?>/5</div>
        </td>
        <!-- Review content -->
        <td style="max-width:320px">
          <div style="font-weight:600;color:var(--text-primary);font-size:14px;margin-bottom:4px"><?= htmlspecialchars($rv['title']) ?></div>
          <div style="font-size:13px;color:var(--text-muted);line-height:1.5"><?= htmlspecialchars(substr($rv['body'],0,120)) ?><?= strlen($rv['body'])>120?'…':'' ?></div>
          <?php if (strlen($rv['body']) > 120): ?>
          <button onclick="showFullReview(<?= $rv['id'] ?>)" style="font-size:12px;color:var(--accent);background:none;border:none;cursor:pointer;padding:2px 0;margin-top:4px">Read more ↓</button>
          <?php endif; ?>
          <!-- Hidden full body -->
          <div id="full-<?= $rv['id'] ?>" style="display:none;margin-top:8px;font-size:13px;color:var(--text-muted);line-height:1.6;background:var(--surface);padding:10px 12px;border-radius:8px;border:1px solid var(--border)"><?= nl2br(htmlspecialchars($rv['body'])) ?></div>
        </td>
        <!-- Date -->
        <td style="white-space:nowrap">
          <div style="font-size:13px;color:var(--text-primary)"><?= date('M j, Y', strtotime($rv['created_at'])) ?></div>
          <div style="font-size:11px;color:var(--text-muted)"><?= date('H:i', strtotime($rv['created_at'])) ?></div>
        </td>
        <!-- Status badge -->
        <td>
          <?php if ($rv['is_approved']): ?>
            <span style="display:inline-flex;align-items:center;gap:4px;padding:4px 10px;border-radius:99px;font-size:12px;font-weight:700;background:rgba(16,185,129,.12);color:#10b981;border:1px solid rgba(16,185,129,.2)">✓ Published</span>
          <?php else: ?>
            <span style="display:inline-flex;align-items:center;gap:4px;padding:4px 10px;border-radius:99px;font-size:12px;font-weight:700;background:rgba(245,158,11,.12);color:#f59e0b;border:1px solid rgba(245,158,11,.2)">⏳ Pending</span>
          <?php endif; ?>
        </td>
        <!-- Actions -->
        <td>
          <div style="display:flex;gap:6px;justify-content:flex-end;flex-wrap:wrap">
            <?php if (!$rv['is_approved']): ?>
            <button class="btn btn-success btn-sm" onclick="approveReview(<?= $rv['id'] ?>)">✅ Approve</button>
            <?php else: ?>
            <button class="btn btn-secondary btn-sm" onclick="rejectReview(<?= $rv['id'] ?>)">↩ Unpublish</button>
            <?php endif; ?>
            <button class="btn btn-danger btn-sm btn-icon" onclick="deleteReview(<?= $rv['id'] ?>, '<?= htmlspecialchars(addslashes($rv['uname'])) ?>')" title="Delete">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2"/></svg>
            </button>
          </div>
        </td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</div>

<script>
// ── Toast system ──
function showToast(msg, type='success') {
  const tc = document.getElementById('toastContainer');
  const t  = document.createElement('div');
  const bg = type==='success' ? 'rgba(16,185,129,.95)' : type==='error' ? 'rgba(239,68,68,.95)' : 'rgba(245,158,11,.95)';
  t.style.cssText = `background:${bg};color:#fff;padding:13px 20px;border-radius:10px;font-size:14px;font-weight:600;box-shadow:0 8px 32px rgba(0,0,0,.4);pointer-events:auto;display:flex;align-items:center;gap:10px;min-width:240px;animation:slideInRight .25s ease`;
  t.innerHTML = `<span>${msg}</span><button onclick="this.parentElement.remove()" style="background:none;border:none;color:#fff;cursor:pointer;margin-left:auto;font-size:18px;line-height:1;opacity:.7">×</button>`;
  tc.appendChild(t);
  setTimeout(() => { t.style.animation='slideOutRight .3s ease forwards'; setTimeout(()=>t.remove(),300); }, 3500);
}

// ── AJAX helper ──
function apiCall(action, id, onSuccess) {
  fetch(window.location.href, {
    method: 'POST',
    body: new URLSearchParams({action, id}),
    headers: {'X-Requested-With':'XMLHttpRequest','Content-Type':'application/x-www-form-urlencoded'}
  }).then(r=>r.json()).then(d => {
    if (d.success) { showToast(d.msg, 'success'); if (onSuccess) onSuccess(); }
    else showToast(d.msg || 'Something went wrong', 'error');
  }).catch(()=>showToast('Network error', 'error'));
}

// ── Actions ──
function approveReview(id) {
  apiCall('approve', id, () => {
    const row = document.getElementById('row-'+id);
    const badge = row.querySelector('[style*="Pending"]') || row.querySelector('[style*="f59e0b"]');
    if (badge) { badge.style.background='rgba(16,185,129,.12)'; badge.style.color='#10b981'; badge.style.borderColor='rgba(16,185,129,.2)'; badge.textContent='✓ Published'; }
    const btn = row.querySelector('.btn-success');
    if (btn) { btn.textContent='↩ Unpublish'; btn.className='btn btn-secondary btn-sm'; btn.onclick=()=>rejectReview(id); }
    // Update pending count
    const countEl = document.querySelector('[data-pending-count]');
    if (countEl) countEl.textContent = Math.max(0, parseInt(countEl.textContent)-1);
  });
}

function rejectReview(id) {
  apiCall('reject', id, () => {
    const row = document.getElementById('row-'+id);
    const badge = row.querySelector('[style*="Published"]') || row.querySelector('[style*="10b981"]');
    if (badge) { badge.style.background='rgba(245,158,11,.12)'; badge.style.color='#f59e0b'; badge.style.borderColor='rgba(245,158,11,.2)'; badge.textContent='⏳ Pending'; }
    const btn = row.querySelector('.btn-secondary');
    if (btn && btn.textContent.includes('Unpublish')) { btn.textContent='✅ Approve'; btn.className='btn btn-success btn-sm'; btn.onclick=()=>approveReview(id); }
  });
}

function deleteReview(id, name) {
  if (!confirm('Delete review by ' + name + '? This cannot be undone.')) return;
  apiCall('delete', id, () => {
    const row = document.getElementById('row-'+id);
    row.style.transition='opacity .3s,transform .3s';
    row.style.opacity='0'; row.style.transform='translateX(20px)';
    setTimeout(()=>row.remove(), 320);
  });
}

function approveAll() {
  if (!confirm('Approve ALL pending reviews?')) return;
  document.querySelectorAll('#reviewsBody tr').forEach(row => {
    const badge = row.querySelector('[style*="f59e0b"]');
    if (badge) {
      const id = row.id.replace('row-','');
      approveReview(parseInt(id));
    }
  });
}

function triggerPopup() {
  apiCall('trigger_popup', 0, () => {
    setTimeout(() => location.reload(), 1200);
  });
}

function dismissPopup() {
  apiCall('dismiss_popup', 0, () => {
    setTimeout(() => location.reload(), 1200);
  });
}

function showFullReview(id) {
  const el = document.getElementById('full-'+id);
  el.style.display = el.style.display === 'none' ? 'block' : 'none';
}
</script>

<style>
@keyframes slideInRight  { from{opacity:0;transform:translateX(20px)} to{opacity:1;transform:translateX(0)} }
@keyframes slideOutRight { from{opacity:1;transform:translateX(0)} to{opacity:0;transform:translateX(20px)} }
.btn-success { background:rgba(16,185,129,.15)!important; color:#10b981!important; border:1px solid rgba(16,185,129,.3)!important; }
.btn-success:hover { background:rgba(16,185,129,.28)!important; }
</style>

<?php require_once 'includes/footer.php'; renderAdminFooter(); ?>