<?php
// Output buffering prevents any whitespace/BOM before headers
ob_start();
require_once 'includes/config.php';

// ── Ensure tables exist ──
try {
    $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;");

    $pdo->exec("CREATE TABLE IF NOT EXISTS `app_settings` (
      `key` VARCHAR(100) PRIMARY KEY,
      `value` TEXT NOT NULL,
      `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB;");
} catch (Exception $e) {
    // Table creation errors are non-fatal for display, only fatal for AJAX
}

$loggedIn = isset($_SESSION['user_id']);
$userId   = $loggedIn ? (int)$_SESSION['user_id'] : 0;

// ── ALL AJAX handlers (before any HTML output) ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    // Clean any buffered output so JSON is pure
    ob_clean();
    header('Content-Type: application/json; charset=utf-8');

    $act = $_POST['action'] ?? '';

    // Popup dismiss
    if ($act === 'dismiss_review_popup' || $act === 'dismiss_my_popup') {
        if ($loggedIn) {
            $_SESSION['review_popup_dismissed'] = time();
        }
        echo json_encode(['success' => true]);
        exit;
    }

    // Review submit
    if (!$loggedIn) {
        echo json_encode(['success' => false, 'msg' => 'Please log in first.']);
        exit;
    }
    $rating = (int)($_POST['rating'] ?? 0);
    $title  = trim($_POST['title'] ?? '');
    $body   = trim($_POST['body'] ?? '');
    if ($rating < 1 || $rating > 5) { echo json_encode(['success'=>false,'msg'=>'Please select a star rating.']); exit; }
    if (strlen($title) < 3)         { echo json_encode(['success'=>false,'msg'=>'Please enter a short review title.']); exit; }
    if (strlen($body) < 10)         { echo json_encode(['success'=>false,'msg'=>'Please write a bit more in your review.']); exit; }

    try {
        $exists = $pdo->prepare("SELECT id FROM reviews WHERE user_id=?");
        $exists->execute([$userId]);
        if ($exists->fetch()) {
            $pdo->prepare("UPDATE reviews SET rating=?,title=?,body=?,is_approved=0,created_at=NOW() WHERE user_id=?")
                ->execute([$rating, htmlspecialchars($title), htmlspecialchars($body), $userId]);
            echo json_encode(['success'=>true,'msg'=>'Your review has been updated and is pending approval ✓']);
        } else {
            $pdo->prepare("INSERT INTO reviews (user_id,rating,title,body) VALUES (?,?,?,?)")
                ->execute([$userId, $rating, htmlspecialchars($title), htmlspecialchars($body)]);
            echo json_encode(['success'=>true,'msg'=>'Thank you! Your review is pending approval ✓']);
        }
    } catch (Exception $e) {
        echo json_encode(['success'=>false,'msg'=>'Database error: ' . $e->getMessage()]);
    }
    exit;
}

// ── Check if admin has triggered the popup ──
$showPopup = false;
if ($loggedIn) {
    try {
        $popupRow = $pdo->query("SELECT `value`,`updated_at` FROM app_settings WHERE `key`='review_popup_active'")->fetch();
        $popupActive = $popupRow ? (int)$popupRow['value'] : 0;
        if ($popupActive) {
            $triggeredAt = $popupRow ? strtotime($popupRow['updated_at']) : 0;
            $dismissedAt = $_SESSION['review_popup_dismissed'] ?? 0;
            if ($dismissedAt < $triggeredAt) {
                $showPopup = true;
            }
        }
    } catch (Exception $e) {
        $showPopup = false;
    }
}

$page    = max(1,(int)($_GET['page']??1));
$perPage = 9;
$offset  = ($page-1)*$perPage;
$total   = (int)$pdo->query("SELECT COUNT(*) FROM reviews WHERE is_approved=1")->fetchColumn();
$pages   = max(1,ceil($total/$perPage));
$stmt    = $pdo->prepare("SELECT r.*,u.name AS uname,u.avatar AS uavatar FROM reviews r JOIN users u ON u.id=r.user_id WHERE r.is_approved=1 ORDER BY r.created_at DESC LIMIT ? OFFSET ?");
$stmt->execute([$perPage,$offset]);
$reviews = $stmt->fetchAll();
$avgRating   = (float)$pdo->query("SELECT AVG(rating) FROM reviews WHERE is_approved=1")->fetchColumn();
$ratingCount = (int)$pdo->query("SELECT COUNT(*) FROM reviews WHERE is_approved=1")->fetchColumn();
$breakdown   = [];
for ($i=5;$i>=1;$i--) { $s=$pdo->prepare("SELECT COUNT(*) FROM reviews WHERE is_approved=1 AND rating=?"); $s->execute([$i]); $breakdown[$i]=(int)$s->fetchColumn(); }
$myReview = null;
if ($loggedIn) { $s=$pdo->prepare("SELECT * FROM reviews WHERE user_id=?"); $s->execute([$userId]); $myReview=$s->fetch(); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Reviews — StudyTrack</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=Nunito:wght@700;800;900&family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="<?= SITE_URL ?>/assets/css/style.css">
<link rel="icon" type="image/png" href="https://studytrack.edurx.icu/studytrack/images/studytrack.png">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
html{scroll-behavior:smooth}
body{background:#08080f;color:#e2e8f0;font-family:'Poppins',sans-serif;overflow-x:hidden;line-height:1.6}
a{text-decoration:none;color:inherit}
img{display:block;max-width:100%}
:root{--ink:#e2e8f0;--ink-dim:#94a3b8;--ink-ghost:#475569;--surface:#0f0f1a;--card:#13131f;--card2:#1a1a2e;--border:rgba(255,255,255,.07);--border2:rgba(255,255,255,.12);--vi:#7c6af0;--vi2:#a78bfa;--cy:#22d3ee;--glow-vi:rgba(124,106,240,.35);--r:14px;--r2:20px}
.container{max-width:1140px;margin:0 auto;padding:0 24px}
body::before{content:'';position:fixed;inset:0;z-index:0;pointer-events:none;opacity:.4;background-image:url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='0.04'/%3E%3C/svg%3E")}

/* NAV */
.nav{position:fixed;top:0;left:0;right:0;z-index:999;padding:0 24px;transition:background .3s}
.nav.scrolled{background:rgba(8,8,15,.92);backdrop-filter:blur(20px);border-bottom:1px solid var(--border)}
.nav-inner{max-width:1140px;margin:0 auto;display:flex;align-items:center;justify-content:space-between;height:68px}
.nav-logo{display:flex;align-items:center;gap:10px}
.nav-logo img{width:34px;height:34px;border-radius:9px}
.nav-logo-text{font-family:'Nunito',sans-serif;font-size:18px;font-weight:800;background:linear-gradient(135deg,#fff 30%,var(--vi2));-webkit-background-clip:text;-webkit-text-fill-color:transparent}
.nav-links{display:flex;align-items:center;gap:4px}
.nav-links a{padding:7px 14px;border-radius:9px;font-size:14px;font-weight:500;color:var(--ink-dim);transition:color .2s,background .2s}
.nav-links a:hover{color:var(--ink);background:rgba(255,255,255,.05)}
.nav-pill{background:linear-gradient(135deg,var(--vi),#9333ea)!important;color:#fff!important;padding:8px 22px!important;box-shadow:0 0 24px var(--glow-vi);font-weight:600!important}
.nav-active{color:var(--vi2)!important}

/* MOBILE BOTTOM NAV */
.mob-nav{display:none;position:fixed;bottom:0;left:0;right:0;z-index:998;
  background:rgba(10,10,18,.97);backdrop-filter:blur(24px);
  border-top:1px solid var(--border);
  padding:6px 0 max(6px,env(safe-area-inset-bottom));
  justify-content:space-around;align-items:stretch}
.mn-item{display:flex;flex-direction:column;align-items:center;gap:3px;padding:7px 10px;
  border-radius:10px;color:var(--ink-ghost);font-size:10px;font-weight:600;
  text-align:center;transition:all .2s;text-decoration:none;border:none;background:none;cursor:pointer;flex:1}
.mn-item .mni{font-size:21px;line-height:1;margin-bottom:1px}
.mn-item.active,.mn-item:hover{color:var(--vi2)}
.mn-item.active .mni{filter:drop-shadow(0 0 8px var(--vi))}
@media(max-width:768px){.mob-nav{display:flex}.nav-links{display:none}.mob-pad{padding-bottom:74px}}

/* PAGE HEADER */
.page-header{padding:112px 0 52px;text-align:center;position:relative;z-index:1}
.ph-mesh{position:absolute;inset:0;pointer-events:none;background:radial-gradient(ellipse 60% 70% at 50% 0%,rgba(124,106,240,.15) 0%,transparent 55%)}
.page-header h1{font-family:'Nunito',sans-serif;font-size:clamp(30px,5vw,52px);font-weight:800;letter-spacing:-.5px;margin-bottom:10px}
.page-header h1 span{background:linear-gradient(110deg,var(--vi2),var(--cy));-webkit-background-clip:text;-webkit-text-fill-color:transparent}
.page-header p{font-size:16px;color:var(--ink-dim);max-width:460px;margin:0 auto}
.ph-tag{display:inline-flex;align-items:center;gap:6px;background:rgba(124,106,240,.1);border:1px solid rgba(124,106,240,.25);border-radius:100px;padding:5px 16px;font-size:12px;font-weight:700;color:var(--vi2);letter-spacing:.5px;text-transform:uppercase;margin-bottom:18px}

/* SUMMARY */
.summary-card{background:var(--card);border:1px solid var(--border2);border-radius:var(--r2);padding:36px 44px;display:flex;gap:44px;align-items:center;flex-wrap:wrap;margin-bottom:28px}
.s-avg{font-family:'Nunito',sans-serif;font-size:68px;font-weight:900;line-height:1;background:linear-gradient(135deg,var(--vi2),var(--cy));-webkit-background-clip:text;-webkit-text-fill-color:transparent}
.s-stars{display:flex;gap:3px;justify-content:center;margin:7px 0 5px}
.s-count{font-size:13px;color:var(--ink-ghost)}
.br-row{display:flex;align-items:center;gap:10px;margin-bottom:8px}
.br-lbl{font-size:13px;color:var(--ink-dim);width:30px;flex-shrink:0}
.br-track{flex:1;height:6px;background:rgba(255,255,255,.07);border-radius:99px;overflow:hidden}
.br-fill{height:100%;border-radius:99px;background:linear-gradient(90deg,var(--vi),var(--cy));width:0;transition:width 1s ease .1s}
.br-cnt{font-size:12px;color:var(--ink-ghost);width:22px;text-align:right}

/* WRITE CARD */
.write-card{background:var(--card);border:1px solid var(--border2);border-radius:var(--r2);padding:36px 44px;margin-bottom:28px}
.write-card h2{font-family:'Nunito',sans-serif;font-size:22px;font-weight:800;margin-bottom:5px}
.wc-sub{font-size:14px;color:var(--ink-dim);margin-bottom:26px}
.login-prompt{text-align:center;padding:28px;background:rgba(124,106,240,.07);border:1px dashed rgba(124,106,240,.25);border-radius:var(--r);color:var(--ink-dim);font-size:15px}
.login-prompt a{color:var(--vi2);font-weight:600}
.my-note{background:rgba(124,106,240,.08);border:1px solid rgba(124,106,240,.2);border-radius:var(--r);padding:12px 16px;font-size:13px;color:var(--ink-dim);margin-bottom:18px}
.my-note strong{color:var(--vi2)}
.form-grp{margin-bottom:16px}
.f-label{display:block;font-size:12px;font-weight:700;color:var(--ink-ghost);margin-bottom:7px;text-transform:uppercase;letter-spacing:.6px}
.f-input,.f-textarea{width:100%;background:var(--card2);border:1px solid var(--border2);border-radius:var(--r);padding:13px 16px;color:var(--ink);font-family:'Poppins',sans-serif;font-size:15px;outline:none;transition:border-color .2s}
.f-input:focus,.f-textarea:focus{border-color:var(--vi)}
.f-textarea{resize:vertical;min-height:108px}

/* Star picker */
.star-pick{display:flex;gap:4px;margin-bottom:22px;flex-direction:row-reverse;justify-content:flex-end}
.star-pick input{display:none}
.star-pick label{font-size:34px;cursor:pointer;color:var(--ink-ghost);transition:color .15s,transform .15s;line-height:1}
.star-pick label:hover,.star-pick label:hover~label,.star-pick input:checked~label{color:#f59e0b}
.star-pick label:hover{transform:scale(1.2)}

.btn-sub{display:inline-flex;align-items:center;gap:9px;background:linear-gradient(135deg,var(--vi),#9333ea);color:#fff;padding:13px 32px;border-radius:var(--r);font-size:15px;font-weight:700;border:none;cursor:pointer;box-shadow:0 6px 28px var(--glow-vi);transition:all .25s}
.btn-sub:hover{transform:translateY(-2px);box-shadow:0 10px 36px var(--glow-vi)}
.btn-sub:disabled{opacity:.6;cursor:not-allowed;transform:none}

/* REVIEWS GRID */
.rev-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:22px;flex-wrap:wrap;gap:10px}
.rev-header h2{font-family:'Nunito',sans-serif;font-size:22px;font-weight:800}
.cnt-badge{background:rgba(124,106,240,.12);border:1px solid rgba(124,106,240,.25);color:var(--vi2);font-size:13px;font-weight:700;padding:4px 14px;border-radius:99px}
.rev-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:18px;margin-bottom:28px}
.rev-card{background:var(--card);border:1px solid var(--border);border-radius:var(--r2);padding:22px;transition:border-color .25s,transform .25s}
.rev-card:hover{border-color:var(--border2);transform:translateY(-4px)}
.rc-stars{display:flex;gap:2px;margin-bottom:12px}
.rc-s{font-size:14px}.rc-s.on{color:#f59e0b}.rc-s.off{color:var(--ink-ghost)}
.rc-title{font-size:15px;font-weight:700;color:var(--ink);margin-bottom:7px}
.rc-body{font-size:13px;color:var(--ink-dim);line-height:1.7;margin-bottom:16px}
.rc-user{display:flex;align-items:center;gap:9px;border-top:1px solid var(--border);padding-top:14px}
.rc-av{width:36px;height:36px;border-radius:50%;background:linear-gradient(135deg,var(--vi),#9333ea);display:flex;align-items:center;justify-content:center;font-weight:800;font-size:14px;color:#fff;overflow:hidden;flex-shrink:0}
.rc-av img{width:100%;height:100%;object-fit:cover}
.rc-name{font-size:13px;font-weight:600;color:var(--ink)}
.rc-date{font-size:11px;color:var(--ink-ghost)}
.no-revs{text-align:center;padding:60px 20px;color:var(--ink-ghost)}

/* PAGINATION */
.pag{display:flex;gap:6px;justify-content:center;margin-top:8px}
.pg-a{padding:8px 16px;border-radius:var(--r);font-size:13px;font-weight:600;background:var(--card);border:1px solid var(--border2);color:var(--ink-dim);transition:all .2s;text-decoration:none}
.pg-a:hover,.pg-a.on{background:var(--vi);border-color:var(--vi);color:#fff}
.pg-a.off{opacity:.35;pointer-events:none}

/* TOAST */
#toastBox{position:fixed;top:80px;right:20px;z-index:9999;display:flex;flex-direction:column;gap:8px;pointer-events:none}
.toast{padding:13px 18px;border-radius:12px;font-size:14px;font-weight:600;box-shadow:0 8px 32px rgba(0,0,0,.45);pointer-events:auto;display:flex;align-items:center;gap:10px;min-width:260px;max-width:340px;animation:tin .25s ease}
.t-ok{background:rgba(16,185,129,.95);color:#fff}
.t-err{background:rgba(239,68,68,.92);color:#fff}
.t-x{background:none;border:none;color:inherit;cursor:pointer;margin-left:auto;font-size:20px;line-height:1;opacity:.7;padding:0}
@keyframes tin{from{opacity:0;transform:translateX(20px)}to{opacity:1;transform:translateX(0)}}
@keyframes tout{from{opacity:1;transform:translateX(0)}to{opacity:0;transform:translateX(20px)}}

/* FOOTER */
.footer{background:var(--surface);border-top:1px solid var(--border);padding:52px 24px 28px;margin-top:60px}
.ft-grid{display:grid;grid-template-columns:2fr 1fr 1fr 1fr;gap:44px;margin-bottom:36px}
.ft-desc{font-size:13px;color:var(--ink-ghost);line-height:1.7;margin-top:10px}
.ft-col h5{font-size:12px;font-weight:700;color:var(--ink);margin-bottom:12px;text-transform:uppercase;letter-spacing:.5px}
.ft-col a{display:block;font-size:13px;color:var(--ink-ghost);margin-bottom:8px;transition:color .2s}
.ft-col a:hover{color:var(--vi2)}
.ft-bot{border-top:1px solid var(--border);padding-top:20px;display:flex;align-items:center;justify-content:space-between;font-size:12px;color:var(--ink-ghost);flex-wrap:wrap;gap:8px}

@media(max-width:900px){.rev-grid{grid-template-columns:repeat(2,1fr)}}
@media(max-width:640px){.rev-grid{grid-template-columns:1fr}.summary-card,.write-card{padding:24px 20px}.ft-grid{grid-template-columns:1fr 1fr}}
@media(max-width:480px){.ft-grid{grid-template-columns:1fr}}
</style>
</head>
<body class="mob-pad">

<div id="toastBox"></div>

<!-- NAV -->
<nav class="nav" id="nav">
  <div class="nav-inner">
    <a href="<?= SITE_URL ?>/home" class="nav-logo">
      <img src="https://studytrack.edurx.icu/studytrack/images/studytrack.png" alt="">
      <span class="nav-logo-text">StudyTrack</span>
    </a>
    <div class="nav-links">
      <a href="<?= SITE_URL ?>/home">Home</a>
      <a href="<?= SITE_URL ?>/home#features">Features</a>
      <a href="<?= SITE_URL ?>/reviews" class="nav-active">Reviews</a>
      <?php if ($loggedIn): ?>
        <a href="<?= SITE_URL ?>/dashboard" class="nav-pill">Dashboard</a>
      <?php else: ?>
        <a href="<?= SITE_URL ?>/login">Login</a>
        <a href="<?= SITE_URL ?>/register" class="nav-pill">Get Started</a>
      <?php endif; ?>
    </div>
  </div>
</nav>

<!-- MOBILE BOTTOM NAV 
<nav class="mob-nav">
  <a href="<?= SITE_URL ?>/home" class="mn-item"><span class="mni">🏠</span>Home</a>
  <a href="<?= SITE_URL ?>/home#features" class="mn-item"><span class="mni">✨</span>Features</a>
  <a href="<?= SITE_URL ?>/reviews" class="mn-item active"><span class="mni">⭐</span>Reviews</a>
  <?php if ($loggedIn): ?>
    <a href="<?= SITE_URL ?>/dashboard" class="mn-item"><span class="mni">📊</span>Dashboard</a>
  <?php else: ?>
    <a href="<?= SITE_URL ?>/register" class="mn-item"><span class="mni">🚀</span>Sign Up</a>
    <a href="<?= SITE_URL ?>/login" class="mn-item"><span class="mni">👤</span>Login</a>
  <?php endif; ?>
</nav> -->

<!-- PAGE HEADER -->
<div class="page-header">
  <div class="ph-mesh"></div>
  <div class="container" style="position:relative;z-index:1">
    <div class="ph-tag">⭐ Student Reviews</div>
    <h1>What Students <span>Are Saying</span></h1>
    <p>Real reviews from Sri Lankan A/L students using StudyTrack every day.</p>
  </div>
</div>

<div style="position:relative;z-index:1">
<div class="container">

  <!-- SUMMARY -->
  <div class="summary-card">
    <div style="text-align:center;min-width:130px">
      <div class="s-avg"><?= $ratingCount>0 ? number_format($avgRating,1) : '–' ?></div>
      <div class="s-stars">
        <?php for($i=1;$i<=5;$i++): ?><span style="font-size:20px;color:<?= $i<=round($avgRating)?'#f59e0b':'var(--ink-ghost)' ?>">★</span><?php endfor; ?>
      </div>
      <div class="s-count"><?= $ratingCount ?> review<?= $ratingCount!==1?'s':'' ?></div>
    </div>
    <div style="flex:1;min-width:200px">
      <?php for($i=5;$i>=1;$i--): $pct=$ratingCount>0?round(($breakdown[$i]/$ratingCount)*100):0; ?>
      <div class="br-row">
        <div class="br-lbl"><?=$i?>★</div>
        <div class="br-track"><div class="br-fill" data-w="<?=$pct?>"></div></div>
        <div class="br-cnt"><?=$breakdown[$i]?></div>
      </div>
      <?php endfor; ?>
    </div>
  </div>

  <!-- WRITE REVIEW -->
  <div class="write-card">
    <h2>Write a Review</h2>
    <p class="wc-sub">Share your experience to help other students.</p>
    <?php if (!$loggedIn): ?>
      <div class="login-prompt">Please <a href="<?= SITE_URL ?>/login">log in</a> or <a href="<?= SITE_URL ?>/register">create a free account</a> to leave a review.</div>
    <?php else: ?>
      <?php if ($myReview): ?>
        <div class="my-note">You already left a review — editing will reset it for re-approval. <strong>Status: <?= $myReview['is_approved']?'✓ Published':'⏳ Pending' ?></strong></div>
      <?php endif; ?>
      <form id="revForm">
        <div class="form-grp">
          <label class="f-label">Your Rating</label>
          <div class="star-pick">
            <?php for($i=5;$i>=1;$i--): $c=$myReview&&$myReview['rating']==$i?'checked':''; ?>
              <input type="radio" name="rating" id="s<?=$i?>" value="<?=$i?>" <?=$c?>>
              <label for="s<?=$i?>">★</label>
            <?php endfor; ?>
          </div>
        </div>
        <div class="form-grp">
          <label class="f-label" for="rtitle">Review Title</label>
          <input type="text" id="rtitle" name="title" class="f-input" placeholder="e.g. Best study app for A/Ls!" maxlength="150" value="<?= $myReview?htmlspecialchars($myReview['title']):'' ?>">
        </div>
        <div class="form-grp">
          <label class="f-label" for="rbody">Your Experience</label>
          <textarea id="rbody" name="body" class="f-textarea" placeholder="Tell us what you love about StudyTrack…" maxlength="1000"><?= $myReview?htmlspecialchars($myReview['body']):'' ?></textarea>
        </div>
        <button type="submit" class="btn-sub" id="subBtn">
          <svg width="15" height="15" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>
          <span id="subLbl"><?= $myReview?'Update My Review':'Submit Review' ?></span>
        </button>
      </form>
    <?php endif; ?>
  </div>

  <!-- REVIEWS GRID -->
  <div class="rev-header">
    <h2>All Reviews</h2>
    <?php if($total>0): ?><span class="cnt-badge"><?=$total?> review<?=$total!==1?'s':''?></span><?php endif; ?>
  </div>
  <?php if(empty($reviews)): ?>
    <div class="no-revs"><div style="font-size:48px;margin-bottom:14px">💬</div><p>No approved reviews yet. Be the first!</p></div>
  <?php else: ?>
    <div class="rev-grid">
      <?php foreach($reviews as $r): $ini=strtoupper(substr($r['uname'],0,1)); ?>
      <div class="rev-card">
        <div class="rc-stars"><?php for($i=1;$i<=5;$i++): ?><span class="rc-s <?=$i<=$r['rating']?'on':'off'?>">★</span><?php endfor; ?></div>
        <div class="rc-title"><?=htmlspecialchars($r['title'])?></div>
        <div class="rc-body"><?=nl2br(htmlspecialchars($r['body']))?></div>
        <div class="rc-user">
          <div class="rc-av"><?php if($r['uavatar']): ?><img src="<?=htmlspecialchars($r['uavatar'])?>" alt=""><?php else: echo $ini; endif; ?></div>
          <div><div class="rc-name"><?=htmlspecialchars($r['uname'])?></div><div class="rc-date"><?=date('M j, Y',strtotime($r['created_at']))?></div></div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php if($pages>1): ?>
    <div class="pag">
      <a href="?page=<?=max(1,$page-1)?>" class="pg-a <?=$page<=1?'off':''?>">← Prev</a>
      <?php for($i=1;$i<=$pages;$i++): ?><a href="?page=<?=$i?>" class="pg-a <?=$i===$page?'on':''?>"><?=$i?></a><?php endfor; ?>
      <a href="?page=<?=min($pages,$page+1)?>" class="pg-a <?=$page>=$pages?'off':''?>">Next →</a>
    </div>
    <?php endif; ?>
  <?php endif; ?>

</div>
</div>

<!-- FOOTER -->
<footer class="footer">
  <div class="container">
    <div class="ft-grid">
      <div class="ft-col">
        <div style="font-family:'Nunito',sans-serif;font-size:18px;font-weight:800;background:linear-gradient(135deg,#fff 30%,var(--vi2));-webkit-background-clip:text;-webkit-text-fill-color:transparent">StudyTrack</div>
        <p class="ft-desc">A free study tracking platform for Sri Lankan A/L students. Track smarter, study better, score higher.</p>
      </div>
      <div class="ft-col"><h5>Product</h5><a href="<?=SITE_URL?>/home#features">Features</a><a href="<?=SITE_URL?>/home#how-it-works">How it Works</a><a href="<?=SITE_URL?>/reviews">Reviews</a></div>
      <div class="ft-col"><h5>Account</h5><a href="<?=SITE_URL?>/login">Login</a><a href="<?=SITE_URL?>/register">Register</a><a href="<?=SITE_URL?>/dashboard">Dashboard</a></div>
      <div class="ft-col"><h5>Legal</h5><a href="<?=SITE_URL?>/privacy">Privacy</a><a href="<?=SITE_URL?>/terms">Terms</a><a href="<?=SITE_URL?>/contact">Contact</a></div>
    </div>
    <div class="ft-bot">
      <span>© <?=date('Y')?> StudyTrack by EduRx. All rights reserved.</span>
      <span>Made with ❤️ for Sri Lankan Students</span>
    </div>
  </div>
</footer>

<script>
// Scroll nav
window.addEventListener('scroll',()=>document.getElementById('nav').classList.toggle('scrolled',scrollY>20));

// Animate bars
window.addEventListener('load',()=>{
  document.querySelectorAll('.br-fill[data-w]').forEach(el=>{
    setTimeout(()=>{el.style.width=el.dataset.w+'%'},200);
  });
});

// Toast
function toast(msg,type='ok'){
  const box=document.getElementById('toastBox');
  const t=document.createElement('div');
  t.className='toast t-'+type;
  t.innerHTML=`<span>${msg}</span><button class="t-x" onclick="closeToast(this)">×</button>`;
  box.appendChild(t);
  setTimeout(()=>closeToast(t.querySelector('.t-x')),4200);
}
function closeToast(btn){
  const t=btn.closest?btn.closest('.toast'):btn.parentElement;
  if(!t)return;
  t.style.animation='tout .3s ease forwards';
  setTimeout(()=>t.remove(),300);
}

// AJAX form
const form=document.getElementById('revForm');
if(form){
  form.addEventListener('submit',async e=>{
    e.preventDefault();
    const btn=document.getElementById('subBtn');
    const lbl=document.getElementById('subLbl');
    btn.disabled=true; lbl.textContent='Submitting…';
    try{
      const r=await fetch(window.location.href,{
        method:'POST',
        body:new URLSearchParams(new FormData(form)),
        headers:{'X-Requested-With':'XMLHttpRequest','Content-Type':'application/x-www-form-urlencoded'}
      });
      const text = await r.text();
      let j;
      try { j = JSON.parse(text); }
      catch(parseErr) {
        console.error('Server response (not JSON):', text);
        toast('Server error — please try again.','err');
        return;
      }
      toast(j.msg, j.success?'ok':'err');
      if(j.success){
        document.getElementById('rtitle').value='';
        document.getElementById('rbody').value='';
        form.querySelectorAll('input[name=rating]').forEach(i=>i.checked=false);
        lbl.textContent='Update My Review';
      }
    }catch(netErr){
      console.error('Network error:', netErr);
      toast('Connection error — check your internet and try again.','err');
    }
    finally{btn.disabled=false; if(!lbl.textContent.includes('Update'))lbl.textContent='Submit Review';}
  });
}
</script>


</body>
</html>