<?php
session_start();
// Use require_once to prevent "Constant already defined" warnings
require_once 'config.php'; 
// As per config.php, define roles here (or ensure they are defined ONLY in config.php)
// If admin_assign_teachers.php already has define statements for roles, REMOVE THEM HERE.
// Example:
/*
if (!defined('ROLE_SUPER_ADMIN')) {
    define('ROLE_SUPER_ADMIN', 0);
}
// ... do the same for other roles if they are *not* defined in config.php initially
*/
// The best approach is to ensure config.php is the *only* place they are defined,
// and then use require_once everywhere.

// Check database connection after including config.php
if ($conn->connect_error) { 
    error_log("Database connection failed in admin_assign_teachers.php: " . $conn->connect_error);
    // Redirect or show a user-friendly error
    header("Location: error_page.php?msg=db_connect_failed");
    exit();
}

// Ensure user is logged in and is an Admin or Super Admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || ($_SESSION["role"] != ROLE_ADMIN && $_SESSION["role"] != ROLE_SUPER_ADMIN)) {
    header("location: login.php");
    exit;
}

$current_user_school_id = $_SESSION['school_id'] ?? null;

// Handle GET request to fetch assignments for a specific stream/class and subject
if (isset($_GET['stream_id']) && isset($_GET['subject_id']) && isset($_GET['academic_year']) && isset($_GET['term'])) {
    $stream_id = (int)$_GET['stream_id'];
    $subject_id = (int)$_GET['subject_id'];
    $academic_year = trim($_GET['academic_year']);
    $term = trim($_GET['term']);

    // This query fetches the currently assigned teacher for a specific stream, subject, academic year, and term.
    // It assumes teacher_stream_subject_assignments is your table.
    // We are selecting teacher_user_id and username for the teacher.
    $sql_fetch_assignment = "SELECT tssa.teacher_user_id, u.username AS teacher_name 
                             FROM teacher_stream_subject_assignments tssa
                             JOIN users u ON tssa.teacher_user_id = u.id
                             WHERE tssa.stream_id = ? 
                               AND tssa.subject_id = ? 
                               AND tssa.academic_year = ? 
                               AND tssa.term = ? 
                               AND tssa.school_id = ?";

    if ($stmt_fetch = $conn->prepare($sql_fetch_assignment)) {
        $stmt_fetch->bind_param("iisssi", $stream_id, $subject_id, $academic_year, $term, $current_user_school_id); // 'i' for stream_id and subject_id, 's' for year/term, 'i' for school_id
        if ($stmt_fetch->execute()) {
            $result_fetch = $stmt_fetch->get_result();
            $assigned_teacher = $result_fetch->fetch_assoc(); // Assuming one teacher per assignment, or you'll need to fetch all and iterate

            // Return JSON response for AJAX (or display directly if not AJAX)
            header('Content-Type: application/json');
            echo json_encode([
                'success' => true,
                'data' => $assigned_teacher // Will be null if no teacher assigned
            ]);
            $stmt_fetch->close();
            $conn->close();
            exit();
        } else {
            error_log("Error fetching teacher assignment: " . $stmt_fetch->error);
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Error fetching assignment.']);
            $stmt_fetch->close();
            $conn->close();
            exit();
        }
    } else {
        error_log("Database error (prepare fetch assignment): " . $conn->error);
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Database error.']);
        $conn->close();
        exit();
    }
}


// Handle POST request for assigning/updating teachers
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Collect and sanitize input
    $stream_id = (int)$_POST['stream_id'];
    $subject_id = (int)$_POST['subject_id'];
    $teacher_user_id = (int)$_POST['teacher_user_id']; // This is the ID of the teacher being assigned
    $academic_year = trim($_POST['academic_year']);
    $term = trim($_POST['term']);

    if (empty($current_user_school_id)) {
        // This should not happen if session check is robust, but good for safety
        $response = ['success' => false, 'message' => 'School ID not found in session.'];
        echo json_encode($response);
        exit();
    }

    // Check if an assignment already exists for this stream, subject, academic_year, and term for this school.
    // The UNIQUE KEY `uq_assignment_per_period` (`stream_id`,`subject_id`,`teacher_user_id`,`academic_year`,`term`)
    // implies that one teacher can only be assigned once per stream/subject/academic_year/term combination.
    // If you intend to UPDATE an assignment (change the teacher), you'd look for an existing assignment
    // for stream_id, subject_id, academic_year, term and then UPDATE it.
    // If you intend to assign *another* teacher for the same combination, your schema might need adjustment
    // (e.g., adding an assignment_slot if you support multiple teachers per subject/stream/term).

    // For simplicity, let's assume we either INSERT a new assignment or UPDATE an existing one.

    $sql_check_existing = "SELECT id FROM teacher_stream_subject_assignments 
                           WHERE stream_id = ? AND subject_id = ? AND academic_year = ? AND term = ? AND school_id = ?";
    
    if ($stmt_check = $conn->prepare($sql_check_existing)) {
        $stmt_check->bind_param("iisssi", $stream_id, $subject_id, $academic_year, $term, $current_user_school_id);
        $stmt_check->execute();
        $stmt_check->store_result();
        
        if ($stmt_check->num_rows > 0) {
            // Assignment exists, so update it
            $sql_assign = "UPDATE teacher_stream_subject_assignments 
                           SET teacher_user_id = ? 
                           WHERE stream_id = ? AND subject_id = ? AND academic_year = ? AND term = ? AND school_id = ?";
            $action = "updated";
        } else {
            // No existing assignment, so insert a new one
            $sql_assign = "INSERT INTO teacher_stream_subject_assignments 
                           (stream_id, subject_id, teacher_user_id, academic_year, term, school_id) 
                           VALUES (?, ?, ?, ?, ?, ?)";
            $action = "assigned";
        }
        $stmt_check->close(); // Close the check statement before preparing new one

        if ($stmt_assign = $conn->prepare($sql_assign)) {
            if ($action == "updated") {
                $stmt_assign->bind_param("iiisssi", $teacher_user_id, $stream_id, $subject_id, $academic_year, $term, $current_user_school_id);
            } else { // insert
                $stmt_assign->bind_param("iiisssi", $stream_id, $subject_id, $teacher_user_id, $academic_year, $term, $current_user_school_id);
            }

            if ($stmt_assign->execute()) {
                $response = ['success' => true, 'message' => "Teacher successfully $action."];
            } else {
                // Log detailed error for debugging
                error_log("Error assigning teacher: " . $stmt_assign->error);
                $response = ['success' => false, 'message' => "Error $action teacher: " . $stmt_assign->error];
            }
            $stmt_assign->close();
        } else {
            error_log("Database error (prepare assign/update): " . $conn->error);
            $response = ['success' => false, 'message' => 'Database error during assignment.'];
        }
    } else {
        error_log("Database error (prepare check existing assignment): " . $conn->error);
        $response = ['success' => false, 'message' => 'Database error during assignment check.'];
    }

    echo json_encode($response);
    $conn->close();
    exit();
}

// This part would be for displaying the main page content, if admin_assign_teachers.php
// is also responsible for rendering the HTML form.
// You'll need to fetch lists of streams, subjects, and teachers here to populate dropdowns.
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Assign Teachers</title>
    </head>
<body>
    <div class="container">
        <h2>Assign Teachers to Subjects & Streams</h2>

        <form id="assignTeacherForm" method="POST" action="admin_assign_teachers.php">
            <label for="streamSelect">Select Stream/Class:</label>
            <select id="streamSelect" name="stream_id" required>
                <option value="">-- Select Stream --</option>
                <?php
                // Fetch streams for the current school
                $sql_streams = "SELECT stream_id, stream_name FROM streams WHERE school_id = ?";
                if ($stmt_streams = $conn->prepare($sql_streams)) {
                    $stmt_streams->bind_param("i", $current_user_school_id);
                    $stmt_streams->execute();
                    $result_streams = $stmt_streams->get_result();
                    while ($stream_row = $result_streams->fetch_assoc()) {
                        echo "<option value='{$stream_row['stream_id']}'>{$stream_row['stream_name']}</option>";
                    }
                    $stmt_streams->close();
                } else {
                    error_log("Error fetching streams: " . $conn->error);
                }
                ?>
            </select><br><br>

            <label for="subjectSelect">Select Subject:</label>
            <select id="subjectSelect" name="subject_id" required>
                <option value="">-- Select Subject --</option>
                <?php
                // Fetch subjects for the current school
                $sql_subjects = "SELECT subject_id, subject_name FROM subjects WHERE school_id = ?";
                if ($stmt_subjects = $conn->prepare($sql_subjects)) {
                    $stmt_subjects->bind_param("i", $current_user_school_id);
                    $stmt_subjects->execute();
                    $result_subjects = $stmt_subjects->get_result();
                    while ($subject_row = $result_subjects->fetch_assoc()) {
                        echo "<option value='{$subject_row['subject_id']}'>{$subject_row['subject_name']}</option>";
                    }
                    $stmt_subjects->close();
                } else {
                    error_log("Error fetching subjects: " . $conn->error);
                }
                ?>
            </select><br><br>

            <label for="academicYearSelect">Academic Year:</label>
            <select id="academicYearSelect" name="academic_year" required>
                <option value="">-- Select Year --</option>
                <?php
                // You might fetch these from a database table (e.g., exams or a dedicated academic_years table)
                // Or hardcode a range if it's fixed.
                $currentYear = date("Y");
                for ($i = $currentYear - 2; $i <= $currentYear + 2; $i++) {
                    $yearRange = $i . "-" . ($i + 1);
                    echo "<option value='{$yearRange}'>{$yearRange}</option>";
                }
                ?>
            </select><br><br>

            <label for="termSelect">Term:</label>
            <select id="termSelect" name="term" required>
                <option value="">-- Select Term --</option>
                <option value="Term 1">Term 1</option>
                <option value="Term 2">Term 2</option>
                <option value="Term 3">Term 3</option>
            </select><br><br>

            <label for="teacherSelect">Assign Teacher:</label>
            <select id="teacherSelect" name="teacher_user_id" required>
                <option value="">-- Select Teacher --</option>
                <?php
                // Fetch users with ROLE_TEACHER for the current school
                $sql_teachers = "SELECT id, username FROM users WHERE role = ? AND school_id = ? ORDER BY username ASC";
                if ($stmt_teachers = $conn->prepare($sql_teachers)) {
                    $teacher_role = ROLE_TEACHER; // Assuming ROLE_TEACHER is defined as 2 from config.php
                    $stmt_teachers->bind_param("ii", $teacher_role, $current_user_school_id);
                    $stmt_teachers->execute();
                    $result_teachers = $stmt_teachers->get_result();
                    while ($teacher_row = $result_teachers->fetch_assoc()) {
                        echo "<option value='{$teacher_row['id']}'>{$teacher_row['username']}</option>";
                    }
                    $stmt_teachers->close();
                } else {
                    error_log("Error fetching teachers: " . $conn->error);
                }
                $conn->close(); // Close connection after all operations
                ?>
            </select><br><br>

            <button type="submit">Assign Teacher</button>
        </form>

        <div id="statusMessage"></div>

        </div>

    <script>
        // JavaScript for handling form submission via AJAX or fetching existing assignment
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('assignTeacherForm');
            const streamSelect = document.getElementById('streamSelect');
            const subjectSelect = document.getElementById('subjectSelect');
            const academicYearSelect = document.getElementById('academicYearSelect');
            const termSelect = document.getElementById('termSelect');
            const teacherSelect = document.getElementById('teacherSelect');
            const statusMessage = document.getElementById('statusMessage');

            // Function to fetch and pre-fill existing assignment for selected combination
            function fetchExistingAssignment() {
                const stream_id = streamSelect.value;
                const subject_id = subjectSelect.value;
                const academic_year = academicYearSelect.value;
                const term = termSelect.value;

                if (stream_id && subject_id && academic_year && term) {
                    // Send an AJAX request to this same PHP script but with GET parameters
                    fetch(`admin_assign_teachers.php?stream_id=${stream_id}&subject_id=${subject_id}&academic_year=${academic_year}&term=${term}`)
                        .then(response => response.json())
                        .then(data => {
                            if (data.success && data.data) {
                                teacherSelect.value = data.data.teacher_user_id; // Pre-select assigned teacher
                                statusMessage.textContent = `Current teacher: ${data.data.teacher_name}`;
                                statusMessage.style.color = 'blue';
                            } else {
                                teacherSelect.value = ''; // Clear selection
                                statusMessage.textContent = 'No teacher currently assigned for this combination.';
                                statusMessage.style.color = 'orange';
                            }
                        })
                        .catch(error => {
                            console.error('Error fetching existing assignment:', error);
                            statusMessage.textContent = 'Error loading current assignment.';
                            statusMessage.style.color = 'red';
                        });
                } else {
                    teacherSelect.value = ''; // Clear selection if not all fields are chosen
                    statusMessage.textContent = '';
                }
            }

            // Add event listeners to trigger fetchExistingAssignment when relevant dropdowns change
            streamSelect.addEventListener('change', fetchExistingAssignment);
            subjectSelect.addEventListener('change', fetchExistingAssignment);
            academicYearSelect.addEventListener('change', fetchExistingAssignment);
            termSelect.addEventListener('change', fetchExistingAssignment);


            // Handle form submission via AJAX (optional, but good UX)
            form.addEventListener('submit', function(e) {
                e.preventDefault(); // Prevent default form submission

                const formData = new FormData(form);

                fetch('admin_assign_teachers.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        statusMessage.textContent = data.message;
                        statusMessage.style.color = 'green';
                        // Optionally refresh the page or update the display after successful assignment
                        fetchExistingAssignment(); // Update what's shown after assignment
                    } else {
                        statusMessage.textContent = data.message;
                        statusMessage.style.color = 'red';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    statusMessage.textContent = 'An error occurred during submission.';
                    statusMessage.style.color = 'red';
                });
            });
        });
    </script>
</body>
</html>