<?php
if (isset($_POST['add_subject_btn'])) {
    $subject = inject_checker($connection, ucwords($_POST['subject']));
    $level = $_POST['level'];
    $date = date("Y-m-d");

    if (empty($subject) || empty($level)) {
        $_SESSION['msg'] = "❗ Subject or level cannot be empty.";
        $_SESSION['type'] = "error";
    } else {
        // Check for existing subject-level pair
        $stmt_check = $connection->prepare("SELECT * FROM school_subject_levels WHERE subject = ? AND level = ?");
        $stmt_check->bind_param("ss", $subject, $level);
        $stmt_check->execute();
        $result_check = $stmt_check->get_result();

        if ($result_check->num_rows > 0) {
            $_SESSION['msg'] = "⚠️ $subject already exists for $level.";
            $_SESSION['type'] = "warning";
        } else {
            $stmt_insert = $connection->prepare("INSERT INTO school_subject_levels (subject, level, upload_date) VALUES (?, ?, ?)");
            $stmt_insert->bind_param("sss", $subject, $level, $date);

            if ($stmt_insert->execute()) {
                $_SESSION['msg'] = "$subject added successfully to $level.";
                $_SESSION['type'] = "success";
            } else {
                $_SESSION['msg'] = "Failed to add $subject to $level.";
                $_SESSION['type'] = "error";
            }
            $stmt_insert->close();
        }
        $stmt_check->close();
    }

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_single_subject_btn'], $_POST['subject_id'])) {
    $subject_id = (int) $_POST['subject_id'];
    $delete_one = mysqli_query($connection, "DELETE FROM school_subject_levels WHERE id = $subject_id");

    if ($delete_one) {
        $_SESSION['msg'] = "Subject deleted successfully.";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Failed to delete subject.";
        $_SESSION['type'] = "error";
    }
     header("Location: specify_subjects_level");
    exit();
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_subjects_by_level_btn'], $_POST['delete_level'])) {
    $delete_level = mysqli_real_escape_string($connection, $_POST['delete_level']);
    $delete_query = mysqli_query($connection, "DELETE FROM school_subject_levels WHERE level = '$delete_level'");

    if ($delete_query) {
        $_SESSION['msg'] = "All subjects for <u>$delete_level</u> deleted successfully.";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Failed to delete subjects for <u>$delete_level</u>.";
        $_SESSION['type'] = "error";
    }
    header("Location: specify_subjects_level");
    exit();
}

?>


<div class='page-title'>
  <div>
    <h1><i class='fa fa-laptop'></i> Subject Management</h1>
    <p>Specify subjects offered by LEVELS</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-body'>
<form method="POST" action="">
    <div class="row" style="align-items: center;">
        <!-- Subject Selection -->
        <div class="col-xs-12 col-sm-12 col-md-4">
            <div class="input-group">
                <span class="input-group-addon"><strong>Subjects</strong></span>
                <select class="form-control" name="subject" required>
                    <option value="">--Select Subject--</option>
                    <?php
                        $query = "SELECT * FROM `school_subjects` ORDER BY `subjects` ASC";
                        $run_query = mysqli_query($connection, $query);

                        if(mysqli_num_rows($run_query) > 0){
                            while($result = mysqli_fetch_assoc($run_query)){
                                $subjects = $result['subjects'];
                                echo "<option>{$subjects}</option>";
                            }
                        }
                    ?>
                </select>
            </div>
            <br />
        </div>
        <!-- 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);
												if (mysqli_num_rows($run_level_query) > 0) {
													while ($level_result = mysqli_fetch_assoc($run_level_query)) {
														$level = $level_result['level'];
														echo "<option value='" . htmlspecialchars($level) . "'>" . htmlspecialchars($level) . "</option>";
													}
												}
												?>
											</select>
										</div>
										<br />
									</div>
									<!-- Submit Button -->
									<div class="col-xs-12 col-sm-12 col-md-4 text-left" style="margin-top: 5px;">
										<button type="submit" name="add_subject_btn" class="btn btn-primary btn-md">
											<span class="glyphicon glyphicon-plus"></span>&nbsp;SAVE SUBJECT
										</button>
									</div>
								</div>
							</form>
							<br />


												<div class='row'>
													<div class='col-md-12'>
														<div class='col-xs-12 col-sm-12 col-md-12'>                                
														        <?php
// Get all levels
$level_query = "SELECT DISTINCT level FROM school_subject_levels ORDER BY level ASC";
$level_result = mysqli_query($connection, $level_query);
?>

<?php if (mysqli_num_rows($level_result) > 0): ?>
    <div class='table-responsive'>
        <table class='table table-hover table-bordered' id='myTable'>
            <thead>
                <tr>
                    <th>S/N</th>
                    <th>LEVEL</th>
                    <th>SUBJECT(S)</th>
                    <th>ACTION</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $i = 0;
                while ($level_row = mysqli_fetch_assoc($level_result)):
                    $i++;
                    $level = $level_row['level'];

                    // Get all subjects for this level
                    $subject_query = "SELECT id, subject FROM school_subject_levels WHERE level = '$level' ORDER BY subject ASC";
                    $subject_result = mysqli_query($connection, $subject_query);
                ?>
                    <tr>
                        <td><?= $i ?></td>
                        <td><?= htmlspecialchars($level) ?></td>
                        <td>
                            <ul style="padding-left: 20px;">
                                <?php while ($subject = mysqli_fetch_assoc($subject_result)): ?>
                                    <li>
                                        <?= htmlspecialchars($subject['subject']) ?>
                                        <form method="POST" action="" style="display:inline;">
                                            <input type="hidden" name="subject_id" value="<?= $subject['id'] ?>">
                                            <button type="submit" name="delete_single_subject_btn" class="btn btn-xs btn-link text-danger" onclick="return confirm('Delete this subject?')">
                                                <i class="fa fa-times"></i>
                                            </button>
                                        </form>
                                    </li>
                                <?php endwhile; ?>
                            </ul>
                        </td>
                        <td>
                            <form method="POST" action="" onsubmit="return confirm('Are you sure you want to delete all subjects for this level?');">
                                <input type="hidden" name="delete_level" value="<?= htmlspecialchars($level) ?>" />
                                <button type="submit" name="delete_subjects_by_level_btn" class="btn btn-xs btn-danger">DELETE ALL</button>
                            </form>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
<?php else: ?>
    <p class="text-danger text-center">No subjects assigned to any level yet.</p>
<?php endif; ?>


                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

