<?php

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

allow_roles(['admin']);

$school_id = $_SESSION['school_id'];

/*
|--------------------------------------------------------------------------
| FETCH TEACHERS
|--------------------------------------------------------------------------
*/

if (
    isset($_GET['action'])
    &&
    $_GET['action'] === 'get_teachers'
) {

    $stmt = $pdo->prepare("
        SELECT
            id,
            name
        FROM teachers
        WHERE school_id = ?
        AND status = 'Active'
        ORDER BY name ASC
    ");

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

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

    echo json_encode(
        $stmt->fetchAll(PDO::FETCH_ASSOC)
    );

    exit;
}

/*
|--------------------------------------------------------------------------
| FETCH SUBJECTS
|--------------------------------------------------------------------------
*/

if (
    isset($_GET['action'])
    &&
    $_GET['action'] === 'get_subjects'
) {

    $stmt = $pdo->prepare("
        SELECT
            id,
            name
        FROM subjects
        WHERE school_id = ?
        ORDER BY name ASC
    ");

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

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

    echo json_encode(
        $stmt->fetchAll(PDO::FETCH_ASSOC)
    );

    exit;
}

/*
|--------------------------------------------------------------------------
| FETCH ASSIGNMENTS
|--------------------------------------------------------------------------
*/

if (
    isset($_GET['action'])
    &&
    $_GET['action'] === 'get_assignments'
) {

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

    if ($class_id <= 0) {

        echo json_encode([]);

        exit;
    }

    $stmt = $pdo->prepare("
        SELECT *
        FROM class_subject_teachers
        WHERE class_id = ?
        AND school_id = ?
    ");

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

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

    echo json_encode(
        $stmt->fetchAll(PDO::FETCH_ASSOC)
    );

    exit;
}