<?php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: index.php'); exit; }
require_once 'config.php';
requireModule('classes');
$conn = getDBConnection();
$allowed = ['admin','headteacher','director','registrar','supervisor'];
if (!in_array($_SESSION['role'] ?? '', $allowed)) {
    header('Location: dashboard.php?error=access_denied'); exit;
}

// Fetch staff for class teacher dropdown
$staff_list = [];
if ($conn instanceof mysqli) {
    $r = $conn->query("SELECT id, full_name FROM staff WHERE status='active' ORDER BY full_name");
    if ($r) while ($row = $r->fetch_assoc()) $staff_list[] = $row;
}
$current_year = getAcademicYear();
$levels = ['','KG','Lower Primary','Upper Primary','JHS','SHS','Other'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Class Management — EduTrack</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div class="wrapper">
  <nav id="sidebar" class="sidebar">
    <?php if (!defined('EDUTRACK_MODULES')) require_once __DIR__ . '/module_definitions.php'; echo buildSidebar('classes.php'); ?>
  </nav>
  <div class="main-content">
    <header class="header d-flex align-items-center justify-content-between">
      <div class="d-flex align-items-center gap-3">
        <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>
        <div>
          <h4 class="mb-0">Class Management</h4>
          <nav aria-label="breadcrumb" class="d-none d-md-block">
            <ol class="breadcrumb mb-0 small">
              <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
              <li class="breadcrumb-item active">Classes</li>
            </ol>
          </nav>
        </div>
      </div>
      <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#classModal" onclick="openAdd()">
        <i class="fas fa-plus me-1"></i> Add Class
      </button>
    </header>

    <main class="content">
      <div class="card shadow-sm border-0 mb-4">
        <div class="card-body">
          <div class="row g-2 align-items-center mb-3">
            <div class="col-md-4">
              <select id="yearFilter" class="form-select">
                <option value="">All Academic Years</option>
              </select>
            </div>
            <div class="col-auto">
              <select id="activeFilter" class="form-select">
                <option value="all">All Classes</option>
                <option value="1" selected>Active Only</option>
                <option value="0">Inactive</option>
              </select>
            </div>
            <div class="col-auto ms-auto text-muted small" id="countBadge"></div>
          </div>

          <div class="table-responsive">
            <table id="classesTable" class="table table-hover align-middle">
              <thead class="table-light">
                <tr>
                  <th>#</th>
                  <th>Class Name</th>
                  <th>Level</th>
                  <th>Class Teacher</th>
                  <th>Students</th>
                  <th>Subjects</th>
                  <th>Capacity</th>
                  <th>Status</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody id="classesBody">
                <tr><td colspan="9" class="text-center text-muted py-4">Loading...</td></tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </main>
  </div>
</div>

<!-- Add / Edit Modal -->
<div class="modal fade" id="classModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="classForm">
        <div class="modal-header">
          <h5 class="modal-title" id="classModalTitle">Add Class</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" id="classId" name="id" value="0">
          <input type="hidden" name="action" value="save">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label fw-semibold">Class Name <span class="text-danger">*</span></label>
              <input type="text" id="className" name="class_name" class="form-control"
                     placeholder="e.g. JHS 1, Basic 6, Form 2" required>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-semibold">Class Level</label>
              <select id="classLevel" name="class_level" class="form-select">
                <?php foreach ($levels as $lv): ?>
                  <option value="<?= htmlspecialchars($lv) ?>"><?= $lv === '' ? '— Select Level —' : htmlspecialchars($lv) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-semibold">Class Teacher</label>
              <select id="classTeacher" name="class_teacher_id" class="form-select">
                <option value="0">— Not Assigned —</option>
                <?php foreach ($staff_list as $st): ?>
                  <option value="<?= (int) $st['id'] ?>"><?= htmlspecialchars($st['full_name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-semibold">Capacity</label>
              <input type="number" id="classCapacity" name="capacity" class="form-control"
                     placeholder="Max students (optional)" min="0">
            </div>
            <div class="col-md-6">
              <label class="form-label fw-semibold">Academic Year</label>
              <input type="text" id="classYear" name="academic_year" class="form-control"
                     value="<?= htmlspecialchars($current_year) ?>" required>
            </div>
            <div class="col-md-6 d-flex align-items-end">
              <div class="form-check mb-2">
                <input type="checkbox" id="classActive" name="is_active" class="form-check-input" checked>
                <label class="form-check-label fw-semibold" for="classActive">Active</label>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary" id="saveClassBtn">
            <i class="fas fa-save me-1"></i> Save Class
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="js/main.js"></script>
<script>
let classes = [];
const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]));

async function loadYears() {
    const res = await fetch('ajax/classes.php?action=get_years');
    const years = await res.json();
    const sel = document.getElementById('yearFilter');
    years.forEach(y => {
        const o = document.createElement('option');
        o.value = y; o.textContent = y;
        if (y === '<?= htmlspecialchars($current_year) ?>') o.selected = true;
        sel.appendChild(o);
    });
}

async function loadClasses() {
    const year   = document.getElementById('yearFilter').value;
    const active = document.getElementById('activeFilter').value;
    const res = await fetch(`ajax/classes.php?action=get_all&year=${encodeURIComponent(year)}&active=${active}`);
    classes = await res.json();
    renderTable(classes);
}

function renderTable(rows) {
    document.getElementById('countBadge').textContent = rows.length + ' class(es)';
    if (rows.length === 0) {
        document.getElementById('classesBody').innerHTML = '<tr><td colspan="9" class="text-center text-muted py-4">No classes found. Click "Add Class" to get started.</td></tr>';
        return;
    }
    document.getElementById('classesBody').innerHTML = rows.map((c, i) => `
      <tr>
        <td>${i + 1}</td>
        <td><strong>${esc(c.class_name)}</strong></td>
        <td><span class="badge bg-light text-dark">${esc(c.class_level || '—')}</span></td>
        <td>${esc(c.teacher_name || '—')}</td>
        <td>
          <a href="students.php?class=${encodeURIComponent(c.class_name)}" class="text-decoration-none">
            <span class="badge bg-primary-subtle text-primary">${c.student_count}</span>
          </a>
        </td>
        <td><span class="badge bg-info-subtle text-info">${c.subject_count}</span></td>
        <td>${c.capacity ? c.capacity : '<span class="text-muted">—</span>'}</td>
        <td>${parseInt(c.is_active) === 1
            ? '<span class="badge bg-success-subtle text-success">Active</span>'
            : '<span class="badge bg-secondary-subtle text-secondary">Inactive</span>'}</td>
        <td>
          <button class="btn btn-sm btn-outline-primary me-1" onclick="openEdit(${c.id})">
            <i class="fas fa-edit"></i>
          </button>
          <a href="students.php?class=${encodeURIComponent(c.class_name)}"
             class="btn btn-sm btn-outline-info me-1" title="View Students">
            <i class="fas fa-users"></i>
          </a>
          <a href="modules/timetable/index.php?class=${encodeURIComponent(c.class_name)}"
             class="btn btn-sm btn-outline-secondary me-1" title="View Timetable">
            <i class="fas fa-calendar-alt"></i>
          </a>
          <button class="btn btn-sm btn-outline-danger" onclick="deleteClass(${c.id}, '${esc(c.class_name)}')">
            <i class="fas fa-trash"></i>
          </button>
        </td>
      </tr>`).join('');
}

function openAdd() {
    document.getElementById('classModalTitle').textContent = 'Add Class';
    document.getElementById('classForm').reset();
    document.getElementById('classId').value = '0';
    document.getElementById('classYear').value = '<?= htmlspecialchars($current_year) ?>';
    document.getElementById('classActive').checked = true;
}

function openEdit(id) {
    const c = classes.find(x => parseInt(x.id) === id);
    if (!c) return;
    document.getElementById('classModalTitle').textContent = 'Edit Class';
    document.getElementById('classId').value             = c.id;
    document.getElementById('className').value           = c.class_name;
    document.getElementById('classLevel').value          = c.class_level || '';
    document.getElementById('classTeacher').value        = c.class_teacher_id || 0;
    document.getElementById('classCapacity').value       = c.capacity || '';
    document.getElementById('classYear').value           = c.academic_year || '<?= htmlspecialchars($current_year) ?>';
    document.getElementById('classActive').checked       = parseInt(c.is_active) === 1;
    new bootstrap.Modal(document.getElementById('classModal')).show();
}

async function deleteClass(id, name) {
    if (!confirm(`Delete class "${name}"? This cannot be undone.`)) return;
    const res = await fetch('ajax/classes.php', { method: 'POST', body: new URLSearchParams({ action: 'delete', id }) });
    const data = await res.json();
    if (data.success) loadClasses();
    else alert(data.message);
}

document.getElementById('classForm').addEventListener('submit', async e => {
    e.preventDefault();
    const btn = document.getElementById('saveClassBtn');
    btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving...';
    const res = await fetch('ajax/classes.php', { method: 'POST', body: new URLSearchParams(new FormData(e.target)) });
    const data = await res.json();
    btn.disabled = false; btn.innerHTML = '<i class="fas fa-save me-1"></i> Save Class';
    if (data.success) {
        bootstrap.Modal.getInstance(document.getElementById('classModal'))?.hide();
        loadClasses();
    } else alert(data.message);
});

document.getElementById('yearFilter').addEventListener('change', loadClasses);
document.getElementById('activeFilter').addEventListener('change', loadClasses);

loadYears().then(() => loadClasses());
</script>
</body>
</html>
