<?php

if (session_status() === PHP_SESSION_NONE) session_start();

if (!isset($_SESSION['user_id'])) { header('Location: index.php'); exit; }

require_once 'config.php';

requireModule('subjects');

$conn = getDBConnection();

$allowed = ['admin','headteacher','director','registrar','supervisor'];

if (!in_array($_SESSION['role'] ?? '', $allowed)) {

    header('Location: dashboard.php?error=access_denied'); exit;

}

// Ensure active column exists (graceful upgrade for older installs)

if ($conn instanceof mysqli) {

    $conn->query("ALTER TABLE subjects ADD COLUMN IF NOT EXISTS active TINYINT(1) NOT NULL DEFAULT 1");

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Subject 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('subjects.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">Subject 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">Subjects</li>

            </ol>

          </nav>

        </div>

      </div>

      <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#subjectModal" onclick="openAdd()">

        <i class="fas fa-plus me-1"></i> Add Subject

      </button>

    </header>



    <main class="content">

      <?php if (isset($_GET['error'])): ?>

      <div class="alert alert-warning"><?= htmlspecialchars($_GET['error']) ?></div>

      <?php endif; ?>



      <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-5">

              <div class="input-group">

                <span class="input-group-text"><i class="fas fa-search"></i></span>

                <input type="text" id="liveSearch" class="form-control" placeholder="Search subjects...">

              </div>

            </div>

            <div class="col-auto">

              <select id="filterStatus" class="form-select">

                <option value="all">All Subjects</option>

                <option value="active">Active Only</option>

                <option value="inactive">Inactive Only</option>

              </select>

            </div>

            <div class="col-auto ms-auto text-muted small" id="countBadge"></div>

          </div>



          <div class="table-responsive">

            <table id="subjectsTable" class="table table-hover align-middle">

              <thead class="table-light">

                <tr>

                  <th>#</th>

                  <th>Subject Name</th>

                  <th>Code</th>

                  <th>Used in Classes</th>

                  <th>Status</th>

                  <th>Actions</th>

                </tr>

              </thead>

              <tbody id="subjectsBody">

                <tr><td colspan="6" 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="subjectModal" tabindex="-1">

  <div class="modal-dialog">

    <div class="modal-content">

      <form id="subjectForm">

        <div class="modal-header">

          <h5 class="modal-title" id="modalTitle">Add Subject</h5>

          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>

        </div>

        <div class="modal-body">

          <input type="hidden" id="subjectId" name="id" value="0">

          <input type="hidden" name="action" value="save">

          <div class="mb-3">

            <label class="form-label fw-semibold">Subject Name <span class="text-danger">*</span></label>

            <input type="text" id="subjectName" name="subject_name" class="form-control"

                   placeholder="e.g. Mathematics" required>

          </div>

          <div class="mb-3">

            <label class="form-label fw-semibold">Subject Code <span class="text-danger">*</span></label>

            <input type="text" id="subjectCode" name="subject_code" class="form-control"

                   placeholder="e.g. MATH" maxlength="20" required

                   style="text-transform:uppercase">

            <div class="form-text">Auto-uppercased. Must be unique (e.g. ENG, SCI, ICT).</div>

          </div>

          <div class="mb-3">

            <label class="form-label fw-semibold">Assign to Classes</label>

            <select id="subjectClasses" name="classes[]" class="form-select" multiple size="5">

              <option disabled value="">Loading classes…</option>

            </select>

            <input type="hidden" name="classes_submitted" value="1">

            <div class="form-text">Hold <kbd>Ctrl</kbd> / <kbd>Cmd</kbd> to select multiple. De-selecting a class with recorded scores will be skipped.</div>

          </div>

          <div class="form-check">

            <input type="checkbox" id="subjectActive" name="active" class="form-check-input" checked>

            <label class="form-check-label" for="subjectActive">Active</label>

          </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="saveBtn">

            <i class="fas fa-save me-1"></i> Save Subject

          </button>

        </div>

      </form>

    </div>

  </div>

</div>



<!-- Delete Confirm Modal -->

<div class="modal fade" id="deleteModal" tabindex="-1">

  <div class="modal-dialog modal-sm">

    <div class="modal-content">

      <div class="modal-header"><h6 class="modal-title text-danger"><i class="fas fa-trash me-1"></i>Delete Subject</h6><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>

      <div class="modal-body"><p>Delete <strong id="deleteSubjectName"></strong>? This cannot be undone.</p></div>

      <div class="modal-footer">

        <button class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>

        <button class="btn btn-danger btn-sm" id="confirmDeleteBtn">Delete</button>

      </div>

    </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="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>

<script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap5.min.js"></script>

<script src="js/main.js"></script>

<script>

let subjects = [], deleteId = 0, allClasses = [];

const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]));



function populateClassSelect(selectedClasses = []) {

    const sel = document.getElementById('subjectClasses');

    sel.innerHTML = allClasses.length === 0

        ? '<option disabled value="">No classes found</option>'

        : allClasses.map(c =>

            `<option value="${esc(c)}" ${selectedClasses.includes(c) ? 'selected' : ''}>${esc(c)}</option>`

          ).join('');

}



async function loadSubjects() {

    const filter = document.getElementById('filterStatus').value;

    const res = await fetch('ajax/subjects.php?action=get_all&filter=' + filter + '&_=' + Date.now());

    subjects = await res.json();

    renderTable(subjects);

}



function renderTable(rows) {

    const q = document.getElementById('liveSearch').value.trim().toLowerCase();

    const filtered = q ? rows.filter(r =>

        (r.subject_name + ' ' + r.subject_code + ' ' + (r.classes || '')).toLowerCase().includes(q)

    ) : rows;

    document.getElementById('countBadge').textContent = filtered.length + ' subject(s)';

    document.getElementById('subjectsBody').innerHTML = filtered.length === 0

        ? '<tr><td colspan="6" class="text-center text-muted py-4">No subjects found.</td></tr>'

        : filtered.map((s, i) => `

          <tr>

            <td>${i + 1}</td>

            <td><strong>${esc(s.subject_name)}</strong></td>

            <td><code class="text-primary">${esc(s.subject_code)}</code></td>

            <td><span class="text-muted small">${esc(s.classes || '—')}</span></td>

            <td>

              ${parseInt(s.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(${s.id})">

                <i class="fas fa-edit"></i> Edit

              </button>

              <button class="btn btn-sm btn-outline-secondary me-1" onclick="toggleActive(${s.id}, '${esc(s.subject_name)}')">

                ${parseInt(s.active) === 1 ? '<i class="fas fa-toggle-off"></i> Deactivate' : '<i class="fas fa-toggle-on"></i> Activate'}

              </button>

              <button class="btn btn-sm btn-outline-danger" onclick="confirmDelete(${s.id}, '${esc(s.subject_name)}')">

                <i class="fas fa-trash"></i>

              </button>

            </td>

          </tr>`).join('');

}



function openAdd() {

    document.getElementById('modalTitle').textContent = 'Add Subject';

    document.getElementById('subjectForm').reset();

    document.getElementById('subjectId').value = '0';

    document.getElementById('subjectActive').checked = true;

    populateClassSelect([]);

}



function openEdit(id) {

    const s = subjects.find(x => parseInt(x.id) === id);

    if (!s) return;

    document.getElementById('modalTitle').textContent = 'Edit Subject';

    document.getElementById('subjectId').value   = s.id;

    document.getElementById('subjectName').value = s.subject_name;

    document.getElementById('subjectCode').value = s.subject_code;

    document.getElementById('subjectActive').checked = parseInt(s.active) === 1;

    populateClassSelect(Array.isArray(s.classes_array) ? s.classes_array : []);

    new bootstrap.Modal(document.getElementById('subjectModal')).show();

}



async function toggleActive(id, name) {

    if (!confirm(`${parseInt(subjects.find(s => parseInt(s.id) === id)?.active) === 1 ? 'Deactivate' : 'Activate'} "${name}"?`)) return;

    const res = await fetch('ajax/subjects.php', { method: 'POST', body: new URLSearchParams({ action: 'toggle_active', id }) });

    const data = await res.json();

    if (data.success) {

        document.getElementById('filterStatus').value = 'all';

        loadSubjects();

    } else alert(data.message);

}



function confirmDelete(id, name) {

    deleteId = id;

    document.getElementById('deleteSubjectName').textContent = name;

    new bootstrap.Modal(document.getElementById('deleteModal')).show();

}



document.getElementById('confirmDeleteBtn').addEventListener('click', async () => {

    const res = await fetch('ajax/subjects.php', { method: 'POST', body: new URLSearchParams({ action: 'delete', id: deleteId }) });

    const data = await res.json();

    bootstrap.Modal.getInstance(document.getElementById('deleteModal'))?.hide();

    if (data.success) { loadSubjects(); }

    else { alert(data.message); }

});



document.getElementById('subjectForm').addEventListener('submit', async e => {

    e.preventDefault();

    const btn = document.getElementById('saveBtn');

    btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving...';

    const res = await fetch('ajax/subjects.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 Subject';

    if (data.success) {

        bootstrap.Modal.getInstance(document.getElementById('subjectModal'))?.hide();

        loadSubjects();

    } else { alert(data.message); }

});



document.getElementById('subjectCode').addEventListener('input', e => { e.target.value = e.target.value.toUpperCase(); });

document.getElementById('liveSearch').addEventListener('input', () => renderTable(subjects));

document.getElementById('filterStatus').addEventListener('change', loadSubjects);



async function loadClasses() {

    const res = await fetch('ajax/subjects.php?action=get_classes&_=' + Date.now());

    allClasses = await res.json().catch(() => []);

    populateClassSelect([]);

}



loadClasses();

loadSubjects();

</script>

</body>

</html>

