<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['level'], $_POST['student_subject_number'])) {
    $level = mysqli_real_escape_string($connection, $_POST['level']);
    $number = (int) $_POST['student_subject_number'];

    if ($level === '') {
        $_SESSION['msg'] = "Please select a level.";
        $_SESSION['type'] = "error";
    } elseif ($number <= 0) {
        $_SESSION['msg'] = "Please select a valid subject number.";
        $_SESSION['type'] = "error";
    } else {
        $check = mysqli_query($connection, "SELECT id FROM subject_number_by_level WHERE level = '$level'");
        if (mysqli_num_rows($check) > 0) {
            $update = mysqli_query($connection, "UPDATE subject_number_by_level SET number_of_subject = $number WHERE level = '$level'");
            if ($update) {
                $_SESSION['msg'] = "Subject number for <u>$level</u> updated successfully.";
                $_SESSION['type'] = "success";
            } else {
                $_SESSION['msg'] = "Failed to update subject number.";
                $_SESSION['type'] = "error";
            }
        } else {
            $insert = mysqli_query($connection, "INSERT INTO subject_number_by_level (level, number_of_subject) VALUES ('$level', $number)");
            if ($insert) {
                $_SESSION['msg'] = "Subject number for <u>$level</u> saved successfully.";
                $_SESSION['type'] = "success";
            } else {
                $_SESSION['msg'] = "Failed to save subject number.";
                $_SESSION['type'] = "error";
            }
        }
    }
    header("Location: specify_subject_number");
    exit();
}

// Handle delete request (assuming role check already done earlier)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_level'])) {
    $level_to_delete = mysqli_real_escape_string($connection, $_POST['delete_level']);

    $delete = mysqli_query($connection, "DELETE FROM subject_number_by_level WHERE level = '$level_to_delete'");
    if ($delete) {
        $_SESSION['msg'] = "Subject configuration for <u>$level_to_delete</u> deleted successfully.";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Failed to delete subject configuration for <u>$level_to_delete</u>.";
        $_SESSION['type'] = "error";
    }
    header("Location: specify_subject_number");
    exit();
}
?>

<div class='page-title'>
  <div>
    <h1><i class='fa fa-laptop'></i> Subject Management</h1>
    <p>Specify or update the number of subjects offered by each level</p>
  </div>  
</div>
<div class="card">
    <div class='row'>
        <div class='col-xs-12 col-sm-12 col-md-12'>
            <div class='panel panel-primary ch'>
                <div class='panel-heading text-center'>
                    <h4>Specify Number of Subjects by Level</h4>
                </div>
                <div class='panel-body'>
                    <form method='POST'>
                        <div class='row'>
                            <!-- Level Selection -->
                            <div class="col-xs-12 col-sm-12 col-md-4">
                                <div class="input-group">
                                    <span class="input-group-addon"><strong>Level</strong></span>
                                    <select class="form-control" name="level" required>
                                        <option value="" selected>--Select Level--</option>
                                        <?php
                                        $level_query = 'SELECT * FROM class_level';
                                        $run_level_query = mysqli_query($connection, $level_query);
                                        while ($level_result = mysqli_fetch_assoc($run_level_query)) {
                                            $level = htmlspecialchars($level_result['level']);
                                            echo "<option value='$level'>$level</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                                <br />
                            </div>

                            <!-- Subject Number Selection -->
                            <div class='col-xs-12 col-sm-12 col-md-4'>
                                <div class='input-group'>
                                    <span class='input-group-addon'>Subject Number</span>
                                    <select class='form-control' name='student_subject_number' required>
                                        <option value="">--Select--</option>
                                        <?php for ($i = 1; $i <= 20; $i++) {
                                            echo "<option value='$i'>$i</option>";
                                        } ?>
                                    </select>
                                </div>
                                <br />
                            </div>

                            <!-- Submit Button -->
                            <div class='col-xs-12 col-sm-12 col-md-4'>
                                <button type='submit' class='btn btn-primary'><span class='glyphicon glyphicon-save'></span> Save / Update</button>
                            </div>
                        </div>
                    </form>

                    <!-- Table of All Configured Levels -->
                    <hr />
                    <h4 class="text-center">Current Subject Specifications</h4>
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped">
							<thead>
								<tr>
									<th>S/N</th>
									<th>Level</th>
									<th>Number of Subjects</th>
									<th>Last Updated</th>
									<th>Action</th>
								</tr>
							</thead>
							<tbody>
								<?php
								$fetch_all = mysqli_query($connection, "SELECT * FROM subject_number_by_level ORDER BY level ASC");
								if (mysqli_num_rows($fetch_all) > 0) {
									$sn = 1;
									while ($row = mysqli_fetch_assoc($fetch_all)) {
										$level = htmlspecialchars($row['level']);
										echo "<tr>
											<td>{$sn}</td>
											<td>{$level}</td>
											<td>{$row['number_of_subject']}</td>
											<td>{$row['updated_at']}</td>
											<td>
												<form method='POST' onsubmit='return confirm(\"Are you sure you want to delete subject config for {$level}?\")'>
												    <input type='hidden' name='delete_level' value='{$level}'>
												    <button type='submit' class='btn btn-danger btn-sm'>Delete</button>
												</form>
											</td>
										</tr>";
										$sn++;
									}
								} else {
									echo "<tr><td colspan='5' class='text-center text-danger'>No records found.</td></tr>";
								}
								?>
							</tbody>
						</table>
                    </div>
                </div> <!-- panel-body -->
            </div>
        </div>
    </div>
</div>

