<?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;
}

// Ensure classes table exists
$conn->query("CREATE TABLE IF NOT EXISTS classes (
  id INT AUTO_INCREMENT PRIMARY KEY,
  class_name VARCHAR(100) NOT NULL,
  class_level VARCHAR(50) DEFAULT NULL,
  class_teacher_id INT DEFAULT NULL,
  capacity INT DEFAULT NULL,
  academic_year VARCHAR(20) DEFAULT NULL,
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY unique_class_year (class_name, academic_year)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

switch ($action) {

    // ── GET ALL ────────────────────────────────────────────────────────
    case 'get_all':
        $year   = trim((string) ($_GET['year'] ?? ''));
        $active = trim((string) ($_GET['active'] ?? 'all'));
        $where  = ['1=1'];
        $params = [];
        $types  = '';
        if ($year !== '') { $where[] = 'c.academic_year = ?'; $params[] = $year; $types .= 's'; }
        if ($active === '1') { $where[] = 'c.is_active = 1'; }
        if ($active === '0') { $where[] = 'c.is_active = 0'; }
        $w = implode(' AND ', $where);

        $sql = "SELECT c.*,
                       CONCAT(COALESCE(st.full_name,'')) AS teacher_name,
                       (SELECT COUNT(*) FROM students s WHERE s.class = c.class_name
                        AND s.status = 'active') AS student_count,
                       (SELECT COUNT(*) FROM class_subjects cs
                        WHERE cs.class_name = c.class_name) AS subject_count
                FROM classes c
                LEFT JOIN staff st ON st.id = c.class_teacher_id
                WHERE {$w}
                ORDER BY c.class_name";

        $stmt = $conn->prepare($sql);
        if ($types !== '') { $stmt->bind_param($types, ...$params); }
        $stmt->execute();
        $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        echo json_encode($rows);
        break;

    // ── GET YEARS ─────────────────────────────────────────────────────
    case 'get_years':
        $r = $conn->query("SELECT DISTINCT academic_year FROM classes WHERE academic_year IS NOT NULL ORDER BY academic_year DESC");
        $years = [];
        if ($r) while ($row = $r->fetch_assoc()) $years[] = $row['academic_year'];
        echo json_encode($years);
        break;

    // ── SAVE ──────────────────────────────────────────────────────────
    case 'save':
        $id              = (int) ($_POST['id'] ?? 0);
        $class_name      = strip_tags(trim((string) ($_POST['class_name']    ?? '')));
        $class_level     = strip_tags(trim((string) ($_POST['class_level']   ?? '')));
        $class_teacher_id= (int) ($_POST['class_teacher_id'] ?? 0) ?: null;
        $capacity        = (int) ($_POST['capacity'] ?? 0) ?: null;
        $academic_year   = strip_tags(trim((string) ($_POST['academic_year'] ?? getAcademicYear())));
        $is_active       = isset($_POST['is_active']) ? 1 : 0;

        if ($class_name === '') {
            echo json_encode(['success' => false, 'message' => 'Class name is required']); exit;
        }

        // Uniqueness check per academic year
        $check = $conn->prepare("SELECT id FROM classes WHERE class_name = ? AND academic_year = ? AND id != ?");
        $check->bind_param('ssi', $class_name, $academic_year, $id);
        $check->execute();
        if ($check->get_result()->fetch_assoc()) {
            echo json_encode(['success' => false, 'message' => "Class '{$class_name}' already exists for {$academic_year}"]); exit;
        }
        $check->close();

        if ($id === 0) {
            $stmt = $conn->prepare(
                "INSERT INTO classes (class_name, class_level, class_teacher_id, capacity, academic_year, is_active)
                 VALUES (?, ?, ?, ?, ?, ?)"
            );
            $stmt->bind_param('ssiisi', $class_name, $class_level, $class_teacher_id, $capacity, $academic_year, $is_active);
        } else {
            $stmt = $conn->prepare(
                "UPDATE classes SET class_name=?, class_level=?, class_teacher_id=?,
                 capacity=?, academic_year=?, is_active=? WHERE id=?"
            );
            $stmt->bind_param('ssiisii', $class_name, $class_level, $class_teacher_id, $capacity, $academic_year, $is_active, $id);
        }
        $stmt->execute();
        $new_id = $id === 0 ? (int) $conn->insert_id : $id;
        $stmt->close();
        echo json_encode(['success' => true, 'message' => 'Class saved', 'id' => $new_id]);
        break;

    // ── DELETE ─────────────────────────────────────────────────────────
    case 'delete':
        $id = (int) ($_POST['id'] ?? 0);
        $r  = $conn->query("SELECT class_name FROM classes WHERE id = {$id} LIMIT 1");
        $row = $r ? $r->fetch_assoc() : null;
        if (!$row) { echo json_encode(['success' => false, 'message' => 'Class not found']); exit; }
        $cn = $row['class_name'];

        // Block if students are in this class
        $c = $conn->query("SELECT COUNT(*) as n FROM students WHERE class = '" . $conn->real_escape_string($cn) . "' AND status='active'");
        $count = (int) ($c ? $c->fetch_assoc()['n'] : 0);
        if ($count > 0) {
            echo json_encode(['success' => false, 'message' => "Cannot delete — {$count} active student(s) are enrolled in {$cn}"]); exit;
        }

        $stmt = $conn->prepare("DELETE FROM classes WHERE id = ?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $stmt->close();
        echo json_encode(['success' => true, 'message' => 'Class deleted']);
        break;

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