<?php
require_once __DIR__ . '/../library/auth.php';

$school_id = $_SESSION['school_id'];
allow_roles(['admin', 'teacher']);

// ======================================================
// DYNAMIC PERIOD SETTINGS
// ======================================================

$stmt = $pdo->prepare("
    SELECT total_periods
    FROM period_settings
    WHERE school_id = ?
    LIMIT 1
");

$stmt->execute([$school_id]);

$max_periods = $stmt->fetchColumn() ?: 6;

// ======================================================
// SAVE / UPDATE TIMETABLE
// ======================================================

if (isset($_POST['save_timetable'])) {

    $class_id = (int) ($_POST['class_id'] ?? 0);

    /*
    |--------------------------------------------------------------------------
    | VALIDATE CLASS
    |--------------------------------------------------------------------------
    */

    $verifyClass = $pdo->prepare("
        SELECT id
        FROM classes
        WHERE id = ?
        AND school_id = ?
        LIMIT 1
    ");

    $verifyClass->execute([
        $class_id,
        $school_id
    ]);

    if (!$verifyClass->fetch()) {

        die('Invalid class');
    }

    /*
    |--------------------------------------------------------------------------
    | SAVE TIMETABLE
    |--------------------------------------------------------------------------
    */

    if ($class_id > 0 && !empty($_POST['timetable'])) {

        foreach ($_POST['timetable'] as $day => $periods) {

            foreach ($periods as $p_num => $data) {

                $subject_id = (int) ($data['subject_id'] ?? 0);

                $teacher_id = (int) ($data['teacher_id'] ?? 0);

                if ($subject_id > 0 && $teacher_id > 0) {

                    $stmt = $pdo->prepare("
                        INSERT INTO timetable
                        (
                            school_id,
                            class_id,
                            day_name,
                            period_number,
                            subject_id,
                            teacher_id
                        )
                        VALUES (?, ?, ?, ?, ?, ?)

                        ON DUPLICATE KEY UPDATE
                            subject_id = VALUES(subject_id),
                            teacher_id = VALUES(teacher_id)
                    ");

                    $stmt->execute([
                        $school_id,
                        $class_id,
                        $day,
                        $p_num,
                        $subject_id,
                        $teacher_id
                    ]);
                }
            }
        }
    }

    header("Location: timetable.php?class_id=$class_id&msg=Timetable Updated Successfully");

    exit;
}

// ======================================================
// CLASSES
// ======================================================

$stmt = $pdo->prepare("
    SELECT *
    FROM classes
    WHERE school_id = ?
    ORDER BY class_name, section
");

$stmt->execute([$school_id]);

$classes = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ======================================================
// SUBJECTS + TEACHERS
// ======================================================

$subjects = [];
$teachers = [];

// ======================================================
// SELECTED CLASS
// ======================================================

$selected_class = (int)($_GET['class_id'] ?? 0);
if ($selected_class < 0) {
    $selected_class = 0;
}

$existing = [];

if ($selected_class > 0) {

    // Existing timetable
    $data = $pdo->prepare("
        SELECT *
        FROM timetable
        WHERE class_id = ?
        AND school_id = ?
    ");

    $data->execute([
        $selected_class,
        $school_id
    ]);

    foreach ($data->fetchAll(PDO::FETCH_ASSOC) as $row) {

        $existing[$row['day_name']][$row['period_number']] = $row;
    }

    // Assigned subjects + teachers
    $stmt = $pdo->prepare("
        SELECT
            cst.subject_id,
            cst.teacher_id,

            s.name AS subject_name,
            t.name AS teacher_name

        FROM class_subject_teachers cst

        INNER JOIN subjects s
    ON s.id = cst.subject_id
    AND s.school_id = cst.school_id

INNER JOIN teachers t
    ON t.id = cst.teacher_id
    AND t.school_id = cst.school_id

        WHERE cst.class_id = ?
        AND cst.school_id = ?
    ");

    $stmt->execute([
        $selected_class,
        $school_id
    ]);

    $assigned = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($assigned as $a) {

        $subjects[$a['subject_id']] = [
            'id'   => $a['subject_id'],
            'name' => $a['subject_name']
        ];

        $teachers[$a['teacher_id']] = [
            'id'   => $a['teacher_id'],
            'name' => $a['teacher_name']
        ];
    }
}

// ======================================================

$days = [
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday'
];

require_once __DIR__ . '/../include/header.php';
require_once __DIR__ . '/../include/sidebar.php';

?>

<div class="content-wrapper">
    <section class="content-header">
        <div class="row">
            <div class="col-sm-6"><h1>Manage Timetable</h1></div>
            <div class="col-sm-6 text-right">
                <a href="period_settings.php" class="btn btn-warning"><i class="fa fa-cog"></i> Period Settings</a>
            </div>
        </div>
    </section>

    <section class="content">
        <div class="card mt-3">
            <div class="card-body">
                <form method="GET" class="row mb-4">
                    <div class="col-md-4">
                        <select name="class_id" class="form-control" required>
                            <option value="">Select Class</option>
                            <?php foreach($classes as $c): ?>
                                <option value="<?= $c['id'] ?>" <?= $selected_class == $c['id'] ? 'selected' : '' ?>><?= $c['class_name'] ?> (<?= $c['section'] ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2"><button type="submit" class="btn btn-primary">Load Grid</button></div>
                </form>

                <?php if($selected_class): ?>
                <form method="POST">
                    <input type="hidden" name="class_id" value="<?= $selected_class ?>">
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead><tr><th>Day</th><?php for($i=1; $i<=$max_periods; $i++): ?><th>Period <?= $i ?></th><?php endfor; ?></tr></thead>
                            <tbody>
                                <?php foreach($days as $day): ?>
                                <tr>
                                    <th><?= $day ?></th>
                                    <?php for($i=1; $i<=$max_periods; $i++): 
                                        $sub_id = $existing[$day][$i]['subject_id'] ?? '';
                                        $tea_id = $existing[$day][$i]['teacher_id'] ?? '';
                                    ?>
                                    <td>
                                        <select name="timetable[<?=$day?>][<?=$i?>][subject_id]" class="form-control mb-1"><option value="">Subject</option><?php foreach($subjects as $s): ?><option value="<?=$s['id']?>" <?= $sub_id==$s['id']?'selected':'' ?>><?=$s['name']?></option><?php endforeach; ?></select>
                                        <select name="timetable[<?=$day?>][<?=$i?>][teacher_id]" class="form-control"><option value="">Teacher</option><?php foreach($teachers as $t): ?><option value="<?=$t['id']?>" <?= $tea_id==$t['id']?'selected':'' ?>><?=$t['name']?></option><?php endforeach; ?></select>
                                    </td>
                                    <?php endfor; ?>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <button type="submit" name="save_timetable" class="btn btn-success"><i class="fa fa-save"></i> Save Timetable</button>
                </form>
                <?php endif; ?>
            </div>
        </div>
    </section>
</div>
<?php require_once __DIR__ . '/../include/footer.php'; ?>