<?php

// DELETE handler
if (isset($_POST['teachers_delete_btn'])) {
    $delete_id = $_POST['teachers_hidden_id'];
    $query = "DELETE FROM `teacher_classes` WHERE `id` = '{$delete_id}'";
    $run_query = mysqli_query($connection, $query);

    if ($run_query) {
        $_SESSION['msg'] = "Teacher's Class Assignment Deleted Successfully";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Error! Could Not Delete Record";
        $_SESSION['type'] = "error";
    }

    header("Location: assign_class_to_staff");
    exit();
}

// SAVE handler
if (isset($_POST['save_btn'])) {
    $teacher_id = inject_checker($connection, $_POST['teacher_id']);
    $class = inject_checker($connection, $_POST['class']);
    $term = inject_checker($connection, $_POST['term']);

    // Validate that teacher exists and is a Teacher
    $teacher_query = "SELECT staff.name FROM staff 
                      INNER JOIN role ON staff.role = role.id 
                      WHERE staff.id = '{$teacher_id}' 
                      AND role.role_name = 'class teacher'";
    $teacher_result = mysqli_query($connection, $teacher_query);

    if (mysqli_num_rows($teacher_result) > 0) {
        $teacher_row = mysqli_fetch_assoc($teacher_result);
        $teacher_name = $teacher_row['name'];

        // Check for existing assignment
        $check_query = "SELECT * FROM `teacher_classes` WHERE `class` = '{$class}' AND `term` = '{$term}'";
        $check_result = mysqli_query($connection, $check_query);

        if (mysqli_num_rows($check_result) > 0) {
            $_SESSION['msg'] = "Another teacher has already been assigned to {$class} for {$term}";
            $_SESSION['type'] = "error";
        } else {
            $insert_query = "INSERT INTO `teacher_classes`(`teacher_id`, `class`, `term`) 
                             VALUES('{$teacher_id}', '{$class}', '{$term}')";
            $insert_result = mysqli_query($connection, $insert_query);

            if ($insert_result) {
                $_SESSION['msg'] = "{$teacher_name} assigned to {$class} for {$term} successfully";
                $_SESSION['type'] = "success";
            } else {
                $_SESSION['msg'] = "Failed to assign teacher to {$class}";
                $_SESSION['type'] = "error";
            }
        }
    } else {
        $_SESSION['msg'] = "Selected teacher not found or is not a valid 'Class Teacher' in staff records";
        $_SESSION['type'] = "error";
    }

    header("Location: assign_class_to_staff");
    exit();
}
?>

<!-- HTML PAGE STARTS -->

<div class="page-title">
    <div>
        <h1><i class="fa fa-calendar"></i> Teachers</h1>
        <p>Assign teachers to a class</p>
    </div>    
</div>

<div class="card">
    <form action="" method="POST">
        <div class="panel panel-primary ch">
            <div class="panel-heading">
                <h4 class="text-center">Assign Teachers to their class</h4>
            </div>
            <div class="panel-body">
                <div class="row">
                    <div class='col-md-4'>

                        <!-- Teacher Dropdown -->
                        <div class="input-group">
                            <span class="input-group-addon">Staff</span>
                            <select class="form-control" name="teacher_id" required>
                                <option value="">-- Select Teacher --</option>
                                <?php
                                $query = "SELECT staff.id, staff.name 
                                          FROM staff 
                                          INNER JOIN role ON staff.role = role.id 
                                          WHERE role.role_name = 'class teacher'
                                          ORDER BY staff.name ASC";
                                $result = mysqli_query($connection, $query);
                                while ($row = mysqli_fetch_assoc($result)) {
                                    echo "<option value='{$row['id']}'>{$row['name']}</option>";
                                }
                                ?>
                            </select>
                        </div>
                      </div>

                        <!-- Class Dropdown -->
                        <div class='col-md-4'>
                        <div class="input-group">
                            <span class="input-group-addon">Class</span>
                            <select class="form-control" name="class" required>
                                <option value="">-- Select Class --</option>
                                <?php
                                $query = "SELECT classes FROM `classes` ORDER BY classes ASC";
                                $result = mysqli_query($connection, $query);
                                while ($row = mysqli_fetch_assoc($result)) {
                                    echo "<option>{$row['classes']}</option>";
                                }
                                ?>
                            </select>
                        </div>
                        <br />
</div>
                        <!-- Term Dropdown -->
                        <div class='col-md-4'>
                        <div class="input-group">
                            <span class="input-group-addon">Term</span>
                            <select class="form-control" name="term" required>
                                <option value="">-- Select Term --</option>
                                <?php
                                $term_array = ["First Term", "Second Term", "Third Term"];
                                foreach ($term_array as $term) {
                                    echo "<option>{$term}</option>";
                                }
                                ?>
                            </select>
                        </div>
                        <br />
                        </div>

                        <!-- Submit Button -->
                        <div class='col-md-4'>
                            <button type="submit" name="save_btn" class="btn btn-primary btn-md">
                                <span class="glyphicon glyphicon-user"></span> SAVE
                            </button><br />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <!-- Assigned Teachers Table -->
    <?php
    $query = "SELECT tc.id, s.name, tc.class, tc.term 
              FROM teacher_classes tc
              INNER JOIN staff s ON tc.teacher_id = s.id
              INNER JOIN role r ON s.role = r.id
              WHERE r.role_name = 'class teacher'
              ORDER BY tc.class ASC";

    $result = mysqli_query($connection, $query);
    if (mysqli_num_rows($result) > 0) {
        echo "
        <div class='table-responsive'>
            <table class='table table-striped'>
                <thead>
                    <tr>
                        <th>S/N</th>
                        <th>NAME</th>
                        <th>ASSIGNED CLASS</th>
                        <th>TERM</th>
                        <th>ACTION</th>
                    </tr>
                </thead>";
        $i = 0;
        while ($row = mysqli_fetch_assoc($result)) {
            $i++;
            echo "
                <tbody>
                    <tr>
                        <td>{$i}</td>
                        <td>{$row['name']}</td>
                        <td>{$row['class']}</td>
                        <td>{$row['term']}</td>
                        <td>
                            <form method='POST' action=''>
                                <input type='hidden' name='teachers_hidden_id' value='{$row['id']}' />
                                <input type='submit' name='teachers_delete_btn' class='btn btn-xs btn-danger' value='Delete' />
                            </form>
                        </td>
                    </tr>
                </tbody>";
        }
        echo "</table></div>";
    }
    ?>
</div>

