<?php
require_once 'includes/config.php';
requireLogin();
$uid = $_SESSION['user_id'];

// ── AJAX handler ─────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $subId    = (int)($_POST['subject_id'] ?? 0);
        $exam     = sanitize($_POST['exam_name'] ?? '');
        $obtained = (float)($_POST['marks_obtained'] ?? -1);
        $total    = (float)($_POST['total_marks'] ?? 0);
        $date     = $_POST['exam_date'] ?? '';
        $notes    = sanitize($_POST['notes'] ?? '');

        if ($subId <= 0)  jsonResponse(['success'=>false,'message'=>'Please select a subject.']);
        if ($exam === '') jsonResponse(['success'=>false,'message'=>'Please enter the exam name.']);
        if ($obtained < 0 || $total <= 0)
                          jsonResponse(['success'=>false,'message'=>'Please enter valid marks.']);
        if ($obtained > $total)
                          jsonResponse(['success'=>false,'message'=>'Marks obtained cannot exceed total marks.']);
        if ($date === '')  jsonResponse(['success'=>false,'message'=>'Please select the exam date.']);

        // Verify subject belongs to user
        $chk = $pdo->prepare("SELECT id FROM subjects WHERE id=? AND user_id=?");
        $chk->execute([$subId, $uid]);
        if (!$chk->fetch()) jsonResponse(['success'=>false,'message'=>'Invalid subject selected.']);

        $pdo->prepare("INSERT INTO marks (user_id,subject_id,exam_name,marks_obtained,total_marks,exam_date,notes) VALUES (?,?,?,?,?,?,?)")
            ->execute([$uid, $subId, $exam, $obtained, $total, $date, $notes]);

        $pct = round(($obtained/$total)*100, 1);
        jsonResponse(['success'=>true,'message'=>'Result added! Score: '.$pct.'%']);
    }

    if ($action === 'delete') {
        $pdo->prepare("DELETE FROM marks WHERE id=? AND user_id=?")->execute([(int)($_POST['id']??0), $uid]);
        jsonResponse(['success'=>true]);
    }

    jsonResponse(['success'=>false,'message'=>'Unknown action.']);
}

// ── Page data ────────────────────────────────────────────────────────
$filterSub = (int)($_GET['subject'] ?? 0);
$sql    = "SELECT m.*, s.name AS subject_name, s.color
           FROM marks m JOIN subjects s ON m.subject_id = s.id
           WHERE m.user_id = ?";
$params = [$uid];
if ($filterSub) { $sql .= " AND m.subject_id=?"; $params[] = $filterSub; }
$sql .= " ORDER BY m.exam_date DESC, m.created_at DESC";
$marksQ = $pdo->prepare($sql); $marksQ->execute($params); $marks = $marksQ->fetchAll();

$subjectsQ = $pdo->prepare("SELECT id, name, color FROM subjects WHERE user_id=? ORDER BY name");
$subjectsQ->execute([$uid]); $subjectsList = $subjectsQ->fetchAll();

require_once 'includes/header.php';
renderHeader('Marks & Results', 'marks');
?>

<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:22px">
  <div style="overflow-x:auto;-webkit-overflow-scrolling:touch;flex:1;min-width:0;scrollbar-width:none">
    <div style="display:flex;gap:8px;flex-wrap:nowrap;padding-bottom:2px">
      <a href="marks.php" class="btn btn-sm <?= !$filterSub?'btn-primary':'btn-secondary' ?>">All</a>
      <?php foreach ($subjectsList as $sub): ?>
      <a href="marks.php?subject=<?= $sub['id'] ?>" class="btn btn-sm <?= $filterSub==$sub['id']?'btn-primary':'btn-secondary' ?>" style="flex-shrink:0">
        <span class="subject-dot" style="background:<?= htmlspecialchars($sub['color']) ?>"></span>
        <?= htmlspecialchars($sub['name']) ?>
      </a>
      <?php endforeach; ?>
    </div>
  </div>
  <button class="btn btn-primary" style="flex-shrink:0" onclick="openModal('addMarkModal')">+ Add Result</button>
</div>

<?php if (!$subjectsList): ?>
<div class="alert alert-warning">⚠️ You need to <a href="subjects.php" style="color:var(--accent);font-weight:600">add subjects</a> before recording results.</div>
<?php endif; ?>

<?php if ($marks):
  $avg  = round(array_sum(array_map(fn($m)=>($m['marks_obtained']/$m['total_marks'])*100, $marks)) / count($marks), 1);
  $best = max(array_map(fn($m)=>round(($m['marks_obtained']/$m['total_marks'])*100,1), $marks));
?>
<div class="stats-grid" style="grid-template-columns:repeat(3,1fr);margin-bottom:20px">
  <div class="stat-card"><div class="stat-icon" style="background:rgba(99,102,241,0.15)">📝</div><div class="stat-value"><?= count($marks) ?></div><div class="stat-label">Total Exams</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(6,182,212,0.15)">📊</div><div class="stat-value"><?= $avg ?>%</div><div class="stat-label">Average Score</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(16,185,129,0.15)">🏆</div><div class="stat-value"><?= $best ?>%</div><div class="stat-label">Best Score</div></div>
</div>
<?php endif; ?>

<div class="card">
  <div class="card-header"><div class="card-title">📝 Exam Results</div></div>
  <?php if ($marks): ?>
  <div class="table-wrapper"><table>
    <thead><tr><th>Date</th><th>Exam</th><th>Subject</th><th>Marks</th><th>Grade</th><th></th></tr></thead>
    <tbody>
    <?php foreach ($marks as $m):
      $pct   = round(($m['marks_obtained']/$m['total_marks'])*100, 1);
      $grade = $pct>=75?'A':($pct>=65?'B':($pct>=55?'C':($pct>=40?'S':'F')));
      $cls   = $pct>=75?'green':($pct>=55?'yellow':'red');
    ?>
    <tr>
      <td><?= date('M j, Y', strtotime($m['exam_date'])) ?></td>
      <td style="font-weight:500;color:var(--text-primary)"><?= htmlspecialchars($m['exam_name']) ?></td>
      <td><span class="subject-dot" style="background:<?= htmlspecialchars($m['color']) ?>"></span><?= htmlspecialchars($m['subject_name']) ?></td>
      <td><?= $m['marks_obtained'] ?>/<?= $m['total_marks'] ?></td>
      <td><span class="badge badge-<?= $cls ?>"><?= $grade ?> (<?= $pct ?>%)</span></td>
      <td><button class="btn btn-danger btn-sm btn-icon" onclick="deleteMark(<?= $m['id'] ?>)">🗑️</button></td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table></div>
  <?php else: ?>
  <div class="empty-state">
    <div class="empty-icon">📝</div>
    <h3>No results yet</h3>
    <p>Click "+ Add Result" to record your first exam score</p>
  </div>
  <?php endif; ?>
</div>

<!-- ── Add Mark Modal ─────────────────────────────────────────────── -->
<div class="modal-overlay" id="addMarkModal">
  <div class="modal">
    <div class="modal-header">
      <div class="modal-title">➕ Add Exam Result</div>
      <button class="modal-close" onclick="closeModal('addMarkModal')">✕</button>
    </div>
    <div id="markMsgBox" style="display:none" class="alert"></div>

    <?php if (!$subjectsList): ?>
    <div class="alert alert-warning">⚠️ Please <a href="subjects.php" style="color:var(--accent)">add subjects</a> first.</div>
    <?php else: ?>
    <div class="form-group">
      <label class="form-label">Subject *</label>
      <select id="mark_subject" class="form-control">
        <option value="">— Select subject —</option>
        <?php foreach ($subjectsList as $sub): ?>
        <option value="<?= $sub['id'] ?>"><?= htmlspecialchars($sub['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="form-group">
      <label class="form-label">Exam Name *</label>
      <input type="text" id="mark_exam" class="form-control" placeholder="e.g. Term Test 1, Mock Exam, Past Paper">
    </div>
    <div class="grid-2">
      <div class="form-group">
        <label class="form-label">Marks Obtained *</label>
        <input type="number" id="mark_obtained" class="form-control" min="0" step="0.5" placeholder="e.g. 78">
      </div>
      <div class="form-group">
        <label class="form-label">Total Marks *</label>
        <input type="number" id="mark_total" class="form-control" min="1" step="0.5" value="100">
      </div>
    </div>
    <div class="form-group">
      <label class="form-label">Exam Date *</label>
      <input type="date" id="mark_date" class="form-control" value="<?= date('Y-m-d') ?>" max="<?= date('Y-m-d') ?>">
    </div>
    <div class="form-group">
      <label class="form-label">Notes (optional)</label>
      <textarea id="mark_notes" class="form-control" rows="2" placeholder="Any notes about this exam..."></textarea>
    </div>
    <button id="markSaveBtn" class="btn btn-primary btn-full" onclick="saveMark()">Save Result</button>
    <?php endif; ?>
  </div>
</div>

<script>
function showMarkMsg(msg, type) {
  const el = document.getElementById('markMsgBox');
  el.className = 'alert alert-' + type;
  el.innerHTML = (type==='error' ? '⚠️ ' : '✅ ') + msg;
  el.style.display = 'flex';
}

async function saveMark() {
  const subId    = document.getElementById('mark_subject')?.value || '';
  const exam     = document.getElementById('mark_exam')?.value.trim() || '';
  const obtained = document.getElementById('mark_obtained')?.value || '';
  const total    = document.getElementById('mark_total')?.value || '';
  const date     = document.getElementById('mark_date')?.value || '';

  if (!subId)    { showMarkMsg('Please select a subject.', 'error'); return; }
  if (!exam)     { showMarkMsg('Please enter the exam name.', 'error'); return; }
  if (obtained === '') { showMarkMsg('Please enter marks obtained.', 'error'); return; }
  if (parseFloat(obtained) > parseFloat(total)) { showMarkMsg('Marks obtained cannot exceed total marks.', 'error'); return; }

  const btn = document.getElementById('markSaveBtn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner"></span>&nbsp; Saving...';

  try {
    const fd = new FormData();
    fd.append('action',         'add');
    fd.append('subject_id',     subId);
    fd.append('exam_name',      exam);
    fd.append('marks_obtained', obtained);
    fd.append('total_marks',    total);
    fd.append('exam_date',      date);
    fd.append('notes',          document.getElementById('mark_notes')?.value || '');

    const res  = await fetch(window.location.href, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
    const ct   = res.headers.get('content-type') || '';
    if (!ct.includes('application/json')) throw new Error('Server error ' + res.status);
    const data = await res.json();

    if (data.success) {
      showMarkMsg(data.message, 'success');
      setTimeout(() => { closeModal('addMarkModal'); location.reload(); }, 900);
    } else {
      showMarkMsg(data.message, 'error');
      btn.disabled = false;
      btn.innerHTML = 'Save Result';
    }
  } catch(err) {
    console.error(err);
    showMarkMsg('Connection error. Please try again.', 'error');
    btn.disabled = false;
    btn.innerHTML = 'Save Result';
  }
}

async function deleteMark(id) {
  if (!(await stConfirm('Delete this result?'))) return;
  try {
    const fd = new FormData();
    fd.append('action', 'delete');
    fd.append('id', id);
    const res  = await fetch(window.location.href, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
    const ct   = res.headers.get('content-type') || '';
    if (!ct.includes('application/json')) throw new Error('Server error ' + res.status);
    const data = await res.json();
    if (data.success) location.reload();
  } catch(err) { console.error(err); alert('Error. Please try again.'); }
}
</script>

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