<?php

include('includes/session1.php');

error_reporting();

include('includes/dbconnection.php');
include('includes/session_term_helper.php');

// Resolve current session and term (with fallback support)
$sessionTerm = resolveCurrentSessionTerm($con);
$currentSessionId   = $sessionTerm['session_id']   ?: null;
$currentSessionName = $sessionTerm['session_name'];
$currentTermId      = $sessionTerm['term_id']       ?: null;
$currentTermName    = $sessionTerm['term_name'];



if (!isset($_SESSION['sid'])) {

    header('location:logoutteacher.php');

    exit();

}



// Defaults (in practice, get from form select)

$class = $_GET['class'] ?? '';

$section = $_GET['section'] ?? '';

$teacher_id = $_GET['tid'] ?? '';

$tabSessionID = $_GET['tab_id'] ?? '';



// Fetch students in this class

$students_stmt = $con->prepare("SELECT id, studentName FROM students WHERE class = ? AND section = ? AND status < 3");

$students_stmt->bind_param("ss", $class, $section);

$students_stmt->execute();

$students = $students_stmt->get_result();



// Fetch subject list from subjectcombination table

$elective_subjects_stmt = $con->prepare("SELECT DISTINCT Subject_name FROM subjectcombination WHERE Class = ? AND section = ? AND subject_type = 'Elective'");

$elective_subjects_stmt->bind_param("ss", $class, $section);

$elective_subjects_stmt->execute();

$electives = $elective_subjects_stmt->get_result();



$elective_subject_list = [];

while ($row = $electives->fetch_assoc()) {

    $elective_subject_list[] = $row['Subject_name'];

}



// Fetch compulsory subjects too for automatic backend allocation

$compulsory_subjects_stmt = $con->prepare("SELECT DISTINCT Subject_name FROM subjectcombination WHERE Class = ? AND section = ? AND subject_type = 'Compulsory'");

$compulsory_subjects_stmt->bind_param("ss", $class, $section);

$compulsory_subjects_stmt->execute();

$compulsory_result = $compulsory_subjects_stmt->get_result();



$compulsory_subject_list = [];

while ($row = $compulsory_result->fetch_assoc()) {

    $compulsory_subject_list[] = $row['Subject_name'];

}



?>





<!DOCTYPE html>

<html lang="en">

<?php @include("includes/head.php"); ?>



<style>



    .table {

    table-layout: fixed; /* forces equal column shrink */

    width: 100%;         /* stretch table to fit page */

    word-wrap: break-word; /* wrap long text inside cells */

    font-size: 12px;     /* shrink font size */

}

.table th, 

.table td {

    padding: 4px; /* reduce padding for compact table */

    text-align: center;

    vertical-align: middle;

}

</style>







<body class="hold-transition sidebar-mini layout-fixed">

    <div class="wrapper">

        <?php @include("includes/headert.php"); ?>

        <?php @include("includes/sidebart.php"); ?>



        <div class="content-wrapper">

            <!-- Content Header (Page header) -->

<section class="content-header premium-header">

    <div class="container-fluid">

        <div class="header-glass-card">

            <div class="row align-items-center">

                <div class="col-md-8">

                    <div class="title-section">

                        <div class="icon-box bg-primary-gradient shadow-sm">

                            <i class="fas fa-clipboard-list"></i>

                        </div>

                        <div>

                            <h1 class="premium-title text-primary">

                                Subject Management

                                <span class="premium-subtitle text-secondary">Manage Subject <?= htmlspecialchars($class) ?> - <?= htmlspecialchars($section) ?></span>

                            </h1>
                                        <div class="mt-1">
                                            <?php if ($currentSessionName): ?>
                                                <span class="badge badge-primary mr-1">
                                                    <i class="fas fa-calendar-alt"></i> <?= htmlspecialchars($currentSessionName) ?>
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($currentTermName): ?>
                                                <span class="badge badge-success">
                                                    <i class="fas fa-bookmark"></i> <?= htmlspecialchars($currentTermName) ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="badge badge-warning">
                                                    <i class="fas fa-exclamation-triangle"></i> No active term
                                                </span>
                                            <?php endif; ?>
                                        </div>

                        </div>

                    </div>

                </div>

                <div class="col-md-4">

                    <nav aria-label="breadcrumb">

                        <ol class="breadcrumb premium-breadcrumb">

                            <li class="breadcrumb-item"><a href="teacher_dashboard.php" class="text-primary">Home</a></li>

                            <li class="breadcrumb-item active" aria-current="page">Assign Subject</li>

                        </ol>

                    </nav>

                </div>

            </div>

        </div>

    </div>

</section>            

            <section class="content">

                <div class="container-fluid">

                    <div class="row">

                        <div class="col-md-12">

                            <div class="card shadow-sm border-0">

                                <div class="card-header bg-primary text-white">

                                    <h5 class="mb-0"><i class="fas fa-book"></i> Assign Subjects for <?= htmlspecialchars($class) ?> - <?= htmlspecialchars($section) ?></h5>

                                </div>

                                <div class="card-body">

                                    <?php

                                    // Fetch previously assigned subjects

                                    $allocations = [];

                                    $alloc_stmt = $con->prepare("SELECT student_id, subject_name FROM subject_allocations WHERE class = ? AND section = ?");

                                    $alloc_stmt->bind_param("ss", $class, $section);

                                    $alloc_stmt->execute();

                                    $result = $alloc_stmt->get_result();

                                    while ($row = $result->fetch_assoc()) {

                                        $allocations[$row['student_id']][] = $row['subject_name'];

                                    }





                                    ?>

                                    <form method="post" action="save_subject_allocations.php">

                                        <input type="hidden" name="class" value="<?= $class ?>">

                                        <input type="hidden" name="section" value="<?= $section ?>">

<div class="table-responsive"> <!-- makes table responsive -->

    <table class="table table-bordered table-hover table-striped">

        <thead>

            <tr>

                <th>Student Name</th>

                <?php foreach ($elective_subject_list as $index => $subject): ?>

                    <th>

                        <?= htmlspecialchars($subject) ?><br>

                        <input type="checkbox" class="select-all" data-subject-index="<?= $index ?>">

                    </th>

                <?php endforeach; ?>

            </tr>

        </thead>

        <tbody>

            <?php while ($student = $students->fetch_assoc()): ?>

                <tr>

                    <td><?= htmlspecialchars($student['studentName']) ?>

                        <input type="hidden" name="student_ids[]" value="<?= $student['id'] ?>">

                    </td>

                    <?php foreach ($elective_subject_list as $index => $subject): ?>

                        <td>

                            <input type="checkbox"

                                class="subject-checkbox subject-<?= $index ?>"

                                name="subjects[<?= $student['id'] ?>][]"

                                value="<?= htmlspecialchars($subject) ?>"

                                <?= (isset($allocations[$student['id']]) && in_array($subject, $allocations[$student['id']])) ? 'checked' : '' ?>>

                        </td>

                    <?php endforeach; ?>

                </tr>

            <?php endwhile; ?>

        </tbody>

    </table>

</div>





                                        <div class="form-group text-center">

                                            <button type="submit" class="btn btn-primary btn-lg">

                                                <i class="fas fa-save"></i> Save Allocation

                                            </button>



                                        </div>

                                        <div class="form-group text-center">

                                            <small class="text-danger" style="font-size: 1rem;">

                                                <i class="fas fa-info-circle text-primary"></i>

                                                Note: Your allocation is saved per page

                                            </small>

                                        </div>

                                    </form>

                                </div>

                            </div>

                        </div>

                    </div>



                </div>

            </section>



        </div>

        <?php @include("includes/footer.php"); ?>

    </div><!-- /.wrapper -->

    <?php @include("includes/foot.php"); ?>

    <script>

        document.addEventListener("DOMContentLoaded", function() {

            document.querySelectorAll(".select-all").forEach(function(checkbox) {

                checkbox.addEventListener("change", function() {

                    let subjectIndex = this.getAttribute("data-subject-index");

                    let subjectCheckboxes = document.querySelectorAll(".subject-" + subjectIndex);

                    subjectCheckboxes.forEach(cb => cb.checked = this.checked);

                });

            });

        });

    </script>

</body>



</html>