<?php
// student_dashboard.php
session_start();
require_once 'config.php';
if (empty($_SESSION['student_id'])) {
    header('Location: student_login.php');
    exit;
}

$student_id = (int)$_SESSION['student_id'];
$student_name = $_SESSION['student_name'] ?? 'Student';
$student_class_id = (int)($_SESSION['student_class_id'] ?? 0);

// fetch student's class name
$stmt = $dbh->prepare("SELECT name FROM classes WHERE id = :cid LIMIT 1");
$stmt->execute([':cid'=>$student_class_id]);
$class = $stmt->fetchColumn() ?: 'Class';

// get current timestamp
$now = date('Y-m-d H:i:s');

// Available exams for this student's class, current session & term logic simplified:
// show exams where class_id = student_class_id and status = 'published' and start_time <= now and (end_time IS NULL OR end_time >= now)
// Also exclude exams already submitted by this student (unless exam allows multiple attempts — we'll assume exams.status column might include 'published' + 'allow_multiple_attempts' stored somewhere; absent that, we check exam_attempts)
// We'll implement: if there's an exam_attempts record with status='submitted' and exam_attempts.attempts_allowed != 1 then hide it.
// For simplicity below we only hide if there's a submitted attempt (no retake), assuming teacher toggles multiple attempts elsewhere.


$stmt = $dbh->prepare("
    SELECT e.*,
      (SELECT COUNT(*) FROM exam_attempts ea WHERE ea.exam_id = e.id AND ea.student_id = :sid AND ea.status = 'submitted') as submitted_count
    FROM exams e
    WHERE e.class_id = :class_id
      AND e.status = 'published'
      AND e.start_time <= :now
      AND (e.end_time IS NULL OR e.end_time >= :now)
    ORDER BY e.start_time ASC
");
$stmt->execute([':class_id'=>$student_class_id, ':now'=>$now, ':sid'=>$student_id]);
$exams = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Also fetch past attempts (submitted)
$pastStmt = $dbh->prepare("
   SELECT ea.*, ex.title, ex.subject_id, s.name as subject_name
   FROM exam_attempts ea
   JOIN exams ex ON ex.id = ea.exam_id
   LEFT JOIN Subjects s ON s.id = ex.subject_id
   WHERE ea.student_id = :sid AND ea.status = 'submitted'
   ORDER BY ea.submitted_at DESC
");
$pastStmt->execute([':sid'=>$student_id]);
$past = $pastStmt->fetchAll(PDO::FETCH_ASSOC);

function shortDate($dt){ if(!$dt) return ''; return date('M j, Y H:i', strtotime($dt)); }
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Student Dashboard</title>
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <style>
    :root{--bg:#f3f7fb;--card:#fff;--muted:#6b7280;--accent:#0ea5a4;--danger:#ef4444;}
    body{font-family:Inter,system-ui,Segoe UI,Roboto,Arial;margin:0;background:var(--bg);color:#0f172a;}
    .app{display:flex;min-height:100vh;}
    aside{width:260px;background:#0f172a;color:#fff;padding:20px;}
    main{flex:1;padding:22px;}
    .brand{font-weight:700;font-size:18px;margin-bottom:18px;}
    .sidebar-item{padding:10px;border-radius:8px;margin-bottom:8px;display:flex;justify-content:space-between;align-items:center;cursor:pointer;}
    .card{background:var(--card);border-radius:12px;padding:18px;margin-bottom:16px;box-shadow:0 6px 18px rgba(16,24,40,0.05);}
    .btn{padding:8px 12px;border-radius:8px;background:var(--accent);color:#fff;border:none;cursor:pointer;}
    .muted{color:var(--muted);font-size:14px;}
    .exam-row{display:flex;justify-content:space-between;align-items:center;padding:12px;border-radius:10px;border:1px solid #eef2f6;margin-bottom:8px;}
    .link{color:var(--accent);text-decoration:none;font-weight:600;}
    .small{font-size:13px;color:var(--muted);}
  </style>
</head>
<body>
  <div class="app">
    <aside>
      <div class="brand">Student Exam</div>
      <div style="margin-bottom:14px">
        <div style="font-weight:600"><?=htmlspecialchars($student_name)?></div>
        <div class="small"><?=htmlspecialchars($class)?> • Admission: <span class="muted"><?=htmlspecialchars($_SESSION['admission'] ?? '')?></span></div>
      </div>

      <div style="margin-top:10px">
        <div class="sidebar-item" onclick="location.href='student_dashboard.php'">Available Exams</div>
        <div class="sidebar-item" onclick="location.href='student_dashboard.php?view=past'">My Results</div>
        <div class="sidebar-item" ><a href='logout.php' style='color: white; ' > Logout</a></div>
      </div>
    </aside>

    <main>
      <h1 style="margin-top:0">Welcome, <?=htmlspecialchars($student_name)?></h1>
      <p class="muted">Available exams for <?=htmlspecialchars($class)?> (live exams will appear here)</p>

      <div class="card">
        <div style="display:flex;justify-content:space-between;align-items:center">
          <strong>Available Exams</strong>
          <div>
            <button class="btn" onclick="location.reload()">Refresh</button>
          </div>
        </div>
        <div style="margin-top:12px">
          <?php if(empty($exams)): ?>
            <div class="muted">No available exams at the moment.</div>
          <?php else: ?>
            <?php foreach($exams as $ex): 
                // hide if already submitted
                if($ex['submitted_count'] > 0){
                    // skip — already taken
                    continue;
                }
                // compute duration label
                $duration = (int)$ex['duration_minutes'];
            ?>
              <div class="exam-row">
                <div>
                  <div style="font-weight:600"><?=htmlspecialchars($ex['title'])?></div>
                  <div class="small"><?=htmlspecialchars(shortDate($ex['start_time']))?><?php if($ex['end_time']) echo ' — '.shortDate($ex['end_time']); ?></div>
                </div>
                <div style="text-align:right">
                  <div class="small">Duration: <?=$duration?> min</div>
                  <div style="margin-top:8px">
                    <a class="btn" href="take_exam.php?exam_id=<?=urlencode($ex['id'])?>">Take Exam</a>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
      </div>

      <div class="card">
        <strong>Past Results</strong>
        <div style="margin-top:12px">
          <?php if(empty($past)): ?>
            <div class="muted">No past results yet.</div>
          <?php else: ?>
            <?php foreach($past as $p): ?>
              <div style="display:flex;justify-content:space-between;align-items:center;padding:10px;border-bottom:1px dashed #f1f5f9">
                <div>
                  <div style="font-weight:600"><?=htmlspecialchars($p['title'])?></div>
                  <div class="small"><?=htmlspecialchars($p['subject_name'] ?? '')?> • <?=shortDate($p['submitted_at'])?></div>
                </div>
                <div style="text-align:right">
                  <div style="font-weight:700">score : <?=number_format($p['score'],2)?> </div>
                  <div style="margin-top:6px">
                    <a class="link" href="view_result.php?attempt_id=<?=urlencode($p['id'])?>">View</a>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
      </div>
    </main>
  </div>

<script>
function logout(){
  fetch('logout.php', {method:'POST', headers:{'Content-Type':'application/json'}}).then(()=>location.href='student_login.php');
}
</script>
</body>
</html>
