<?php
require_once __DIR__ . '/../library/auth.php';

$school_id = $_SESSION['school_id'];
allow_roles(['admin', 'teacher']);


$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'add':
        addClass();
        break;

    case 'edit':
        editClass();
        break;

    case 'delete':
        deleteClass();
        break;

    default:
        header("Location: index.php");
        exit;
}

function addClass()
{
    global $pdo, $school_id;

    $class_name = trim($_POST['class_name'] ?? '');
    $section    = trim($_POST['section'] ?? '');
    $house      = trim($_POST['house'] ?? '');

    if ($class_name === '') {
        header("Location: add.php?msg=Class name is required");
        exit;
    }

    // ✅ school_id added
    $stmt = $pdo->prepare("
        INSERT INTO classes
        (school_id, class_name, section, house, created_at, updated_at)
        VALUES
        (?, ?, ?, ?, NOW(), NOW())
    ");

    $stmt->execute([
        $school_id,
        $class_name,
        $section !== '' ? $section : null,
        $house !== '' ? $house : null
    ]);

    header("Location: index.php?msg=Class added successfully");
    exit;
}

function editClass()
{
    global $pdo, $school_id;

    $class_id   = (int)($_POST['class_id'] ?? 0);
    $class_name = trim($_POST['class_name'] ?? '');
    $section    = trim($_POST['section'] ?? '');
    $house      = trim($_POST['house'] ?? '');

    if ($class_id === 0 || $class_name === '') {
        header("Location: index.php?msg=Invalid input");
        exit;
    }

    // ✅ school_id condition added
    $stmt = $pdo->prepare("
        UPDATE classes SET
            class_name = ?,
            section = ?,
            house = ?,
            updated_at = NOW()
        WHERE id = ? AND school_id = ?
    ");

    $stmt->execute([
        $class_name,
        $section !== '' ? $section : null,
        $house !== '' ? $house : null,
        $class_id,
        $school_id
    ]);

    header("Location: index.php?msg=Class updated successfully");
    exit;
}

function deleteClass()
{
    global $pdo, $school_id;

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

    if ($class_id === 0) {
        header("Location: index.php?msg=Invalid class id");
        exit;
    }

    // ✅ school_id condition added
    $stmt = $pdo->prepare("
        DELETE FROM classes
        WHERE id = ? AND school_id = ?
    ");

    $stmt->execute([$class_id, $school_id]);

    header("Location: index.php?msg=Class deleted successfully");
    exit;
}