<?php
session_start();
require_once 'config.php';

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

if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$school_id = $_POST['school_id'] ?? 0;
$teacher_id = $_POST['teacher_id'] ?? 0;

if ($school_id == 0 || $teacher_id == 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit;
}

try {
    $sql = "SELECT DISTINCT 
                s.subject_id,
                s.subject_name
            FROM class_subject_teachers cst
            INNER JOIN subjects s ON cst.subject_id = s.subject_id
            WHERE cst.school_id = ? AND cst.teacher_user_id = ?
            ORDER BY s.subject_name";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $school_id, $teacher_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $subjects = [];
    while ($row = $result->fetch_assoc()) {
        $subjects[] = $row;
    }
    
    echo json_encode(['success' => true, 'subjects' => $subjects]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>