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

// ── Self-migration ───────────────────────────────────────────────
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS syllabus_templates (
        id INT AUTO_INCREMENT PRIMARY KEY,
        subject_name VARCHAR(150) NOT NULL,
        unit_name VARCHAR(150) DEFAULT 'General',
        topic_name VARCHAR(255) NOT NULL,
        sort_order INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        KEY idx_subject (subject_name)
    ) ENGINE=InnoDB");
} catch (PDOException $e) {}

$success = '';
$error   = '';

// ── ACTIONS ──────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Bulk paste: Subject + Unit + multi-line topics (mirrors syllabus.php's own bulk-add UX)
    if ($action === 'bulk_add') {
        $subject = trim(sanitize($_POST['subject_name'] ?? ''));
        $unit    = trim(sanitize($_POST['unit_name'] ?? '')) ?: 'General';
        $raw     = $_POST['topics'] ?? '';

        $lines = preg_split('/\r\n|\r|\n/', $raw);
        $topics = [];
        foreach ($lines as $line) {
            $line = trim(sanitize($line));
            if ($line !== '') $topics[] = $line;
        }

        if (!$subject || empty($topics)) {
            $error = 'Subject name and at least one topic are required.';
        } else {
            $maxOrder = $pdo->prepare("SELECT COALESCE(MAX(sort_order),0) FROM syllabus_templates WHERE subject_name=?");
            $maxOrder->execute([$subject]);
            $order = (int)$maxOrder->fetchColumn();

            $ins = $pdo->prepare("INSERT INTO syllabus_templates (subject_name,unit_name,topic_name,sort_order) VALUES (?,?,?,?)");
            foreach ($topics as $t) $ins->execute([$subject, $unit, $t, ++$order]);

            $success = count($topics) . ' topic(s) added to ' . htmlspecialchars($subject) . '!';
        }
    }

    if ($action === 'edit') {
        $id   = (int)($_POST['id'] ?? 0);
        $unit = trim(sanitize($_POST['unit_name'] ?? '')) ?: 'General';
        $name = trim(sanitize($_POST['topic_name'] ?? ''));
        if ($id && $name) {
            $pdo->prepare("UPDATE syllabus_templates SET unit_name=?, topic_name=? WHERE id=?")->execute([$unit, $name, $id]);
            $success = 'Topic updated!';
        }
    }

    if ($action === 'delete') {
        $pdo->prepare("DELETE FROM syllabus_templates WHERE id=?")->execute([(int)$_POST['id']]);
        $success = 'Topic deleted!';
    }

    if ($action === 'delete_subject') {
        $pdo->prepare("DELETE FROM syllabus_templates WHERE subject_name=?")->execute([$_POST['subject_name'] ?? '']);
        $success = 'Entire subject syllabus removed!';
    }
}

// ── DATA ─────────────────────────────────────────────────────────
$allRows = $pdo->query("SELECT * FROM syllabus_templates ORDER BY subject_name, sort_order, id")->fetchAll();
$bySubject = [];
foreach ($allRows as $r) $bySubject[$r['subject_name']][] = $r;
ksort($bySubject);

$selectedSubject = $_GET['subject'] ?? (array_key_first($bySubject) ?: '');

require_once 'includes/header.php';
renderAdminHeader('Syllabus Templates', 'syllabus-templates');
?>

<style>
.st-layout { display:grid; grid-template-columns: 260px 1fr; gap:20px; align-items:start; }
@media (max-width:900px) { .st-layout { grid-template-columns: 1fr; } }
.st-subject-list { background:var(--bg-card); border:1px solid var(--border); border-radius:14px; padding:10px; max-height:520px; overflow-y:auto; }
.st-subject-item { display:flex; justify-content:space-between; align-items:center; padding:9px 12px; border-radius:9px; cursor:pointer; font-size:13px; color:var(--text-secondary); margin-bottom:2px; }
.st-subject-item:hover { background:var(--bg-secondary); }
.st-subject-item.active { background:rgba(99,102,241,0.14); color:var(--accent); font-weight:700; }
.st-subject-count { font-size:10px; background:var(--bg-secondary); padding:1px 7px; border-radius:20px; color:var(--text-muted); }
.st-subject-item.active .st-subject-count { background:rgba(99,102,241,0.2); color:var(--accent); }
.st-topic-row { display:flex; align-items:center; gap:10px; padding:9px 12px; border-radius:9px; background:var(--bg-secondary); margin-bottom:6px; }
.st-topic-unit { font-size:10px; font-weight:700; color:var(--accent); background:rgba(99,102,241,0.12); padding:2px 8px; border-radius:20px; flex-shrink:0; min-width:70px; text-align:center; }
.st-topic-name { flex:1; font-size:13px; color:var(--text-primary); }
</style>

<?php if ($success): ?><div class="alert alert-success">✅ <?= $success ?></div><?php endif; ?>
<?php if ($error):   ?><div class="alert alert-error">❌ <?= $error ?></div><?php endif; ?>

<div class="card" style="margin-bottom:20px">
  <div class="card-header"><div class="card-title">➕ Bulk Add Topics</div></div>
  <p style="font-size:12px;color:var(--text-muted);margin:-8px 0 14px">
    Subject name must match exactly what students see in the subject dropdown (e.g. <code>Combined Mathematics</code>, <code>Physics</code>, <code>Information &amp; Communication Technology (ICT)</code>).
    Paste real content from the official <a href="https://www.nie.lk" target="_blank" style="color:var(--accent)">NIE syllabus</a> — one topic per line.
  </p>
  <form method="POST">
    <input type="hidden" name="action" value="bulk_add">
    <div class="grid-2" style="gap:14px;margin-bottom:12px">
      <div class="form-group" style="margin:0">
        <label class="form-label">Subject Name *</label>
        <input type="text" name="subject_name" class="form-control" list="stSubjectSuggest" placeholder="e.g. Combined Mathematics" required value="<?= htmlspecialchars($selectedSubject) ?>">
        <datalist id="stSubjectSuggest">
          <?php foreach (array_keys($bySubject) as $s): ?><option value="<?= htmlspecialchars($s) ?>"><?php endforeach; ?>
        </datalist>
      </div>
      <div class="form-group" style="margin:0">
        <label class="form-label">Unit / Chapter Name</label>
        <input type="text" name="unit_name" class="form-control" placeholder="e.g. Algebra (defaults to General)">
      </div>
    </div>
    <div class="form-group">
      <label class="form-label">Topics (one per line) *</label>
      <textarea name="topics" class="form-control" rows="5" placeholder="Indices and logarithms&#10;Quadratic equations&#10;Binomial theorem" required></textarea>
    </div>
    <button type="submit" class="btn btn-primary">➕ Add Topics</button>
  </form>
</div>

<div class="st-layout">
  <!-- Subject list -->
  <div class="st-subject-list">
    <?php if (empty($bySubject)): ?>
      <div style="padding:16px;text-align:center;font-size:12px;color:var(--text-muted)">No syllabus templates yet — add topics using the form above.</div>
    <?php else: foreach ($bySubject as $subj => $rows): ?>
      <div class="st-subject-item <?= $subj===$selectedSubject?'active':'' ?>" onclick="location.href='?subject=<?= urlencode($subj) ?>'">
        <span><?= htmlspecialchars($subj) ?></span>
        <span class="st-subject-count"><?= count($rows) ?></span>
      </div>
    <?php endforeach; endif; ?>
  </div>

  <!-- Topics for selected subject -->
  <div class="card">
    <?php if (!$selectedSubject || empty($bySubject[$selectedSubject])): ?>
      <div class="empty-state" style="padding:40px">
        <div class="empty-icon">📘</div>
        <h3>No subject selected</h3>
        <p>Add topics for a subject using the form above, or pick one from the list.</p>
      </div>
    <?php else: ?>
      <div class="card-header" style="display:flex;justify-content:space-between;align-items:center">
        <div class="card-title">📘 <?= htmlspecialchars($selectedSubject) ?> <span style="color:var(--text-muted);font-weight:400">(<?= count($bySubject[$selectedSubject]) ?> topics)</span></div>
        <form method="POST" onsubmit="return confirm('Delete the ENTIRE syllabus for this subject?')">
          <input type="hidden" name="action" value="delete_subject">
          <input type="hidden" name="subject_name" value="<?= htmlspecialchars($selectedSubject) ?>">
          <button class="btn btn-danger btn-sm">🗑 Delete Whole Subject</button>
        </form>
      </div>
      <div style="padding:14px">
        <?php foreach ($bySubject[$selectedSubject] as $t): ?>
        <div class="st-topic-row">
          <span class="st-topic-unit"><?= htmlspecialchars($t['unit_name']) ?></span>
          <span class="st-topic-name"><?= htmlspecialchars($t['topic_name']) ?></span>
          <button class="btn btn-secondary btn-sm" style="flex-shrink:0"
                  onclick="stEdit(<?= (int)$t['id'] ?>,'<?= htmlspecialchars(addslashes($t['unit_name'])) ?>','<?= htmlspecialchars(addslashes($t['topic_name'])) ?>')">✏️</button>
          <form method="POST" style="flex-shrink:0" onsubmit="return confirm('Delete this topic?')">
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" value="<?= (int)$t['id'] ?>">
            <button class="btn btn-danger btn-sm">🗑</button>
          </form>
        </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</div>

<!-- Edit Modal -->
<div class="modal-overlay" id="stEditModal">
  <div class="modal" style="max-width:440px">
    <div class="modal-header">
      <span class="modal-title">✏️ Edit Topic</span>
      <button class="modal-close" onclick="document.getElementById('stEditModal').classList.remove('active')">✕</button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="id" id="stEId">
      <div class="form-group">
        <label class="form-label">Unit Name</label>
        <input type="text" name="unit_name" id="stEUnit" class="form-control">
      </div>
      <div class="form-group">
        <label class="form-label">Topic Name</label>
        <input type="text" name="topic_name" id="stEName" class="form-control" required>
      </div>
      <button type="submit" class="btn btn-primary btn-full">💾 Save Changes</button>
    </form>
  </div>
</div>

<?php require_once 'includes/footer.php'; renderAdminFooter(); ?>
<script>
function stEdit(id, unit, name) {
  document.getElementById('stEId').value = id;
  document.getElementById('stEUnit').value = unit;
  document.getElementById('stEName').value = name;
  document.getElementById('stEditModal').classList.add('active');
}
</script>
