<?php
// fetch_class_streams.php
session_start(); // Start session to access $_SESSION variables
require_once 'config.php'; // Include your database configuration

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

$response = ['success' => false, 'message' => '', 'data' => []];

if (isset($_GET['class_id']) && !empty($_GET['class_id'])) {
    // Ensure school_id is available in the session for security
    if (!isset($_SESSION["school_id"])) {
        $response['message'] = "School ID not found in session. Please log in again.";
        echo json_encode($response);
        exit;
    }
    $current_user_school_id = $_SESSION["school_id"];

    $class_id = intval($_GET['class_id']);

    if (!isset($conn) || !$conn instanceof mysqli) {
        $response['message'] = "Database connection not available.";
        echo json_encode($response);
        exit;
    }

    // Fetch streams for the given class_id AND school_id from the 'streams' table
    // Now selecting both stream_id and stream_name
    $sql = "SELECT stream_id, stream_name FROM streams WHERE class_id = ? AND school_id = ? ORDER BY stream_name ASC";

    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("ii", $class_id, $current_user_school_id); // Bind both class_id and school_id
        if ($stmt->execute()) {
            $result = $stmt->get_result();
            $streams = [];
            while ($row = $result->fetch_assoc()) {
                // Return both stream_id and stream_name as an associative array
                $streams[] = [
                    'stream_id' => htmlspecialchars($row['stream_id']),
                    'stream_name' => htmlspecialchars($row['stream_name'])
                ];
            }
            $response['success'] = true;
            $response['data'] = $streams;
        } else {
            $response['message'] = "Error executing query: " . $stmt->error;
        }
        $stmt->close();
    } else {
        $response['message'] = "Error preparing query: " . $conn->error;
    }
    $conn->close();
} else {
    $response['message'] = "Class ID not provided.";
}

echo json_encode($response);
?>