<?php

declare(strict_types=1);

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

require_once __DIR__ . '/../config.php';

if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['success' => false, 'message' => 'Unauthorized']); exit; }



header('Content-Type: application/json');

$conn   = getDBConnection();

$action = trim((string) ($_POST['action'] ?? $_GET['action'] ?? ''));



if (!$conn instanceof mysqli) {

    echo json_encode(['success' => false, 'message' => 'Database unavailable']); exit;

}



switch ($action) {



    // ── GET ALL ────────────────────────────────────────────────────────

    case 'get_all':

        $filter = trim((string) ($_GET['filter'] ?? 'all'));

        $where  = '';

        if ($filter === 'active')   $where = 'WHERE s.active = 1';

        if ($filter === 'inactive') $where = 'WHERE s.active = 0';



        $sql = "SELECT s.id, s.subject_name, s.subject_code,

                       COALESCE(s.active, 1) as active,

                       GROUP_CONCAT(DISTINCT cs.class_name ORDER BY cs.class_name SEPARATOR ', ') AS classes,

                       (SELECT COUNT(*) FROM scores sc WHERE sc.subject_id = s.id) AS score_count

                FROM subjects s

                LEFT JOIN class_subjects cs ON cs.subject_id = s.id

                {$where}

                GROUP BY s.id

                ORDER BY s.subject_name";

        $result = $conn->query($sql);

        $rows = [];

        if ($result) {

            while ($row = $result->fetch_assoc()) {

                $row['classes_array'] = $row['classes']

                    ? array_filter(array_map('trim', explode(',', $row['classes'])))

                    : [];

                $rows[] = $row;

            }

        }

        echo json_encode($rows);

        break;



    // ── SAVE (insert or update) ────────────────────────────────────────

    case 'save':

        $id           = (int) ($_POST['id'] ?? 0);

        $subject_name = trim((string) ($_POST['subject_name'] ?? ''));

        $subject_code = strtoupper(trim((string) ($_POST['subject_code'] ?? '')));

        $active       = isset($_POST['active']) ? 1 : 0;



        if ($subject_name === '' || $subject_code === '') {

            echo json_encode(['success' => false, 'message' => 'Subject name and code are required']); exit;

        }



        // Uniqueness check

        $check = $conn->prepare(

            "SELECT id FROM subjects WHERE (subject_name = ? OR subject_code = ?) AND id != ?"

        );

        $check->bind_param('ssi', $subject_name, $subject_code, $id);

        $check->execute();

        $dup = $check->get_result()->fetch_assoc();

        $check->close();

        if ($dup) {

            echo json_encode(['success' => false, 'message' => 'A subject with that name or code already exists']); exit;

        }



        if ($id === 0) {

            // Check if active column exists; if not, insert without it

            $colCheck = $conn->query("SHOW COLUMNS FROM subjects LIKE 'active'");

            $hasActive = $colCheck && $colCheck->num_rows > 0;



            if ($hasActive) {

                $stmt = $conn->prepare("INSERT INTO subjects (subject_name, subject_code, active) VALUES (?, ?, ?)");

                $stmt->bind_param('ssi', $subject_name, $subject_code, $active);

            } else {

                $stmt = $conn->prepare("INSERT INTO subjects (subject_name, subject_code) VALUES (?, ?)");

                $stmt->bind_param('ss', $subject_name, $subject_code);

            }

        } else {

            $colCheck = $conn->query("SHOW COLUMNS FROM subjects LIKE 'active'");

            $hasActive = $colCheck && $colCheck->num_rows > 0;



            if ($hasActive) {

                $stmt = $conn->prepare("UPDATE subjects SET subject_name = ?, subject_code = ?, active = ? WHERE id = ?");

                $stmt->bind_param('ssii', $subject_name, $subject_code, $active, $id);

            } else {

                $stmt = $conn->prepare("UPDATE subjects SET subject_name = ?, subject_code = ? WHERE id = ?");

                $stmt->bind_param('ssi', $subject_name, $subject_code, $id);

            }

        }

        $stmt->execute();

        $new_id = $id === 0 ? (int) $conn->insert_id : $id;

        $stmt->close();



        // Sync class assignments when the modal submitted the classes field

        $extra_msg = '';

        if (isset($_POST['classes_submitted'])) {

            $submitted = array_values(array_filter(array_map('trim', (array)($_POST['classes'] ?? []))));



            // Current assignments for this subject

            $cur = $conn->prepare("SELECT class_name FROM class_subjects WHERE subject_id = ?");

            $cur->bind_param('i', $new_id);

            $cur->execute();

            $existing = array_column($cur->get_result()->fetch_all(MYSQLI_ASSOC), 'class_name');

            $cur->close();



            // Add new assignments (INSERT IGNORE — defaults: 30/70, max 100/100)

            foreach (array_diff($submitted, $existing) as $cls) {

                $ins = $conn->prepare(

                    "INSERT IGNORE INTO class_subjects

                        (class_name, subject_id, class_score_percent, exam_score_percent,

                         max_class_score, max_exam_score)

                     VALUES (?, ?, 30, 70, 100, 100)"

                );

                $ins->bind_param('si', $cls, $new_id);

                $ins->execute();

                $ins->close();

            }



            // Remove de-selected assignments — guard: skip if scores exist for this subject

            $skipped = [];

            foreach (array_diff($existing, $submitted) as $cls) {

                $sc = $conn->prepare(

                    "SELECT COUNT(*) AS n FROM scores

                      WHERE subject_id = ?

                        AND student_id IN (SELECT id FROM students WHERE class = ?)"

                );

                $sc->bind_param('is', $new_id, $cls);

                $sc->execute();

                $cnt = (int)($sc->get_result()->fetch_assoc()['n'] ?? 0);

                $sc->close();

                if ($cnt > 0) {

                    $skipped[] = $cls;

                } else {

                    $del = $conn->prepare("DELETE FROM class_subjects WHERE subject_id = ? AND class_name = ?");

                    $del->bind_param('is', $new_id, $cls);

                    $del->execute();

                    $del->close();

                }

            }



            if (!empty($skipped)) {

                $extra_msg = ' Note: ' . implode(', ', $skipped)

                    . ' could not be unassigned — recorded scores exist.';

            }

        }



        echo json_encode(['success' => true, 'message' => 'Subject saved.' . $extra_msg, 'id' => $new_id]);

        break;



    // ── GET CLASSES LIST (for modal multi-select) ─────────────────────

    case 'get_classes':

        $r = $conn->query(

            "SELECT DISTINCT class_name FROM (

                SELECT DISTINCT class AS class_name FROM students

                 WHERE status = 'active' AND class IS NOT NULL AND class <> ''

                UNION

                SELECT DISTINCT class_name FROM class_subjects

                 WHERE class_name IS NOT NULL AND class_name <> ''

             ) t

             ORDER BY class_name"

        );

        $cls = [];

        if ($r) while ($row = $r->fetch_assoc()) $cls[] = $row['class_name'];

        echo json_encode($cls);

        break;



    // ── TOGGLE ACTIVE ──────────────────────────────────────────────────

    case 'toggle_active':

        $id = (int) ($_POST['id'] ?? 0);

        // Ensure active column exists

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

        $stmt = $conn->prepare("UPDATE subjects SET active = IF(active=1, 0, 1) WHERE id = ?");

        $stmt->bind_param('i', $id);

        $stmt->execute();

        $stmt->close();

        $r = $conn->query("SELECT COALESCE(active, 1) as active FROM subjects WHERE id = {$id} LIMIT 1");

        $new_status = (int) ($r ? $r->fetch_assoc()['active'] : 1);

        echo json_encode(['success' => true, 'new_status' => $new_status]);

        break;



    // ── DELETE ─────────────────────────────────────────────────────────

    case 'delete':

        $id = (int) ($_POST['id'] ?? 0);



        // Block if subject has recorded scores

        $c1 = $conn->query("SELECT COUNT(*) as n FROM scores WHERE subject_id = {$id}");

        $score_count = (int) ($c1 ? $c1->fetch_assoc()['n'] : 0);



        // Block if subject is assigned to any class

        $c2 = $conn->query("SELECT COUNT(*) as n FROM class_subjects WHERE subject_id = {$id}");

        $cs_count = (int) ($c2 ? $c2->fetch_assoc()['n'] : 0);



        // Block if subject has exam questions

        $c3 = $conn->query("SELECT COUNT(*) as n FROM exam_questions WHERE subject_id = {$id}");

        $eq_count = (int) ($c3 ? $c3->fetch_assoc()['n'] : 0);



        if ($score_count > 0 || $cs_count > 0 || $eq_count > 0) {

            $parts = [];

            if ($score_count > 0) $parts[] = "{$score_count} recorded score(s)";

            if ($cs_count > 0)    $parts[] = "assigned to {$cs_count} class(es)";

            if ($eq_count > 0)    $parts[] = "{$eq_count} exam question(s)";

            echo json_encode(['success' => false, 'message' => 'Cannot delete — subject has ' . implode(', ', $parts)]);

            exit;

        }



        $stmt = $conn->prepare("DELETE FROM subjects WHERE id = ?");

        $stmt->bind_param('i', $id);

        $stmt->execute();

        $stmt->close();

        echo json_encode(['success' => true, 'message' => 'Subject deleted']);

        break;



    default:

        echo json_encode(['success' => false, 'message' => 'Unknown action']);

}

