<?php

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

allow_roles(['admin']);

$page_title = 'Assign Subjects & Teachers';

$school_id = $_SESSION['school_id'];

/*
|--------------------------------------------------------------------------
| SAVE ASSIGNMENTS
|--------------------------------------------------------------------------
*/

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

    $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');
    }

    /*
    |--------------------------------------------------------------------------
    | DELETE OLD ASSIGNMENTS
    |--------------------------------------------------------------------------
    */

    $deleteStmt = $pdo->prepare("
        DELETE FROM class_subject_teachers
        WHERE class_id = ?
        AND school_id = ?
    ");

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

    /*
    |--------------------------------------------------------------------------
    | INSERT NEW ASSIGNMENTS
    |--------------------------------------------------------------------------
    */

    if (
        !empty($_POST['subject_id'])
        &&
        !empty($_POST['teacher_id'])
    ) {

        foreach ($_POST['subject_id'] as $key => $subject_id) {

            $subject_id = (int) $subject_id;

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

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

                $stmt = $pdo->prepare("
                    INSERT INTO class_subject_teachers
                    (
                        school_id,
                        class_id,
                        subject_id,
                        teacher_id
                    )
                    VALUES (?, ?, ?, ?)
                ");

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

    header("Location: assign_subject.php?class_id=$class_id&msg=Assignments Saved Successfully");

    exit;
}

/*
|--------------------------------------------------------------------------
| FETCH CLASSES
|--------------------------------------------------------------------------
*/

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

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

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

/*
|--------------------------------------------------------------------------
| FETCH SUBJECTS
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT *
    FROM subjects
    WHERE school_id = ?
    ORDER BY name ASC
");

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

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

/*
|--------------------------------------------------------------------------
| FETCH TEACHERS
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT *
    FROM teachers
    WHERE school_id = ?
    AND status = 'Active'
    ORDER BY name ASC
");

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

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

/*
|--------------------------------------------------------------------------
| SELECTED CLASS
|--------------------------------------------------------------------------
*/

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

$assignments = [];

if ($selected_class > 0) {

    $stmt = $pdo->prepare("
        SELECT *
        FROM class_subject_teachers
        WHERE class_id = ?
        AND school_id = ?
    ");

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

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

/*
|--------------------------------------------------------------------------
| PAGE
|--------------------------------------------------------------------------
*/

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

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

?>

<div class="content-wrapper">

    <section class="content-header">

        <div class="container-fluid">

            <div class="row mb-3">

                <div class="col-sm-6">

                    <h1 class="m-0">

                        Assign Subjects & Teachers

                    </h1>

                </div>

                <div class="col-sm-6 text-right">

                    <a
                        href="timetable.php"
                        class="btn btn-warning"
                    >

                        <i class="fas fa-calendar-alt"></i>

                        Manage Timetable

                    </a>

                </div>

            </div>

        </div>

    </section>

    <section class="content">

        <div class="container-fluid">

            <?php if (isset($_GET['msg'])): ?>

                <div class="alert alert-success alert-dismissible fade show">

                    <button
                        type="button"
                        class="close"
                        data-dismiss="alert"
                    >

                        &times;

                    </button>

                    <?php echo htmlspecialchars($_GET['msg']); ?>

                </div>

            <?php endif; ?>

            <!-- CLASS FILTER -->

            <div class="card card-outline card-primary shadow-sm">

                <div class="card-body">

                    <form method="GET">

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

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

                                <label>

                                    Select Class

                                </label>

                                <select
                                    name="class_id"
                                    class="form-control"
                                    required
                                >

                                    <option value="">

                                        Select Class

                                    </option>

                                    <?php foreach ($classes as $c): ?>

                                        <option
                                            value="<?php echo (int) $c['id']; ?>"
                                            <?php echo ($selected_class == $c['id']) ? 'selected' : ''; ?>
                                        >

                                            <?php echo htmlspecialchars($c['class_name']); ?>

                                            (<?php echo htmlspecialchars($c['section']); ?>)

                                        </option>

                                    <?php endforeach; ?>

                                </select>

                            </div>

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

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

                                    <i class="fas fa-search"></i>

                                    Load

                                </button>

                            </div>

                        </div>

                    </form>

                </div>

            </div>

            <?php if ($selected_class > 0): ?>

                <div class="card card-outline card-primary shadow-sm">

                    <div class="card-header">

                        <h3 class="card-title">

                            Subject & Teacher Assignment

                        </h3>

                    </div>

                    <form method="POST">

                        <input
                            type="hidden"
                            name="class_id"
                            value="<?php echo (int) $selected_class; ?>"
                        >

                        <div class="card-body table-responsive">

                            <table
                                class="table table-bordered table-hover"
                                id="assignmentTable"
                            >

                                <thead class="thead-dark">

                                    <tr>

                                        <th>

                                            Subject

                                        </th>

                                        <th>

                                            Teacher

                                        </th>

                                        <th width="80">

                                            Action

                                        </th>

                                    </tr>

                                </thead>

                                <tbody>

                                    <?php if (!empty($assignments)): ?>

                                        <?php foreach ($assignments as $a): ?>

                                            <tr>

                                                <!-- SUBJECT -->

                                                <td>

                                                    <select
                                                        name="subject_id[]"
                                                        class="form-control"
                                                        required
                                                    >

                                                        <option value="">

                                                            Select Subject

                                                        </option>

                                                        <?php foreach ($subjects as $s): ?>

                                                            <option
                                                                value="<?php echo (int) $s['id']; ?>"
                                                                <?php echo ($a['subject_id'] == $s['id']) ? 'selected' : ''; ?>
                                                            >

                                                                <?php echo htmlspecialchars($s['name']); ?>

                                                            </option>

                                                        <?php endforeach; ?>

                                                    </select>

                                                </td>

                                                <!-- TEACHER -->

                                                <td>

                                                    <select
                                                        name="teacher_id[]"
                                                        class="form-control"
                                                        required
                                                    >

                                                        <option value="">

                                                            Select Teacher

                                                        </option>

                                                        <?php foreach ($teachers as $t): ?>

                                                            <option
                                                                value="<?php echo (int) $t['id']; ?>"
                                                                <?php echo ($a['teacher_id'] == $t['id']) ? 'selected' : ''; ?>
                                                            >

                                                                <?php echo htmlspecialchars($t['name']); ?>

                                                            </option>

                                                        <?php endforeach; ?>

                                                    </select>

                                                </td>

                                                <!-- ACTION -->

                                                <td class="text-center">

                                                    <button
                                                        type="button"
                                                        class="btn btn-danger btn-sm removeRow"
                                                    >

                                                        <i class="fas fa-trash"></i>

                                                    </button>

                                                </td>

                                            </tr>

                                        <?php endforeach; ?>

                                    <?php else: ?>

                                        <tr>

                                            <td>

                                                <select
                                                    name="subject_id[]"
                                                    class="form-control"
                                                    required
                                                >

                                                    <option value="">

                                                        Select Subject

                                                    </option>

                                                    <?php foreach ($subjects as $s): ?>

                                                        <option value="<?php echo (int) $s['id']; ?>">

                                                            <?php echo htmlspecialchars($s['name']); ?>

                                                        </option>

                                                    <?php endforeach; ?>

                                                </select>

                                            </td>

                                            <td>

                                                <select
                                                    name="teacher_id[]"
                                                    class="form-control"
                                                    required
                                                >

                                                    <option value="">

                                                        Select Teacher

                                                    </option>

                                                    <?php foreach ($teachers as $t): ?>

                                                        <option value="<?php echo (int) $t['id']; ?>">

                                                            <?php echo htmlspecialchars($t['name']); ?>

                                                        </option>

                                                    <?php endforeach; ?>

                                                </select>

                                            </td>

                                            <td class="text-center">

                                                <button
                                                    type="button"
                                                    class="btn btn-danger btn-sm removeRow"
                                                >

                                                    <i class="fas fa-trash"></i>

                                                </button>

                                            </td>

                                        </tr>

                                    <?php endif; ?>

                                </tbody>

                            </table>

                            <button
                                type="button"
                                id="addRow"
                                class="btn btn-info"
                            >

                                <i class="fas fa-plus-circle"></i>

                                Add Row

                            </button>

                        </div>

                        <div class="card-footer">

                            <button
                                type="submit"
                                name="save_assignment"
                                class="btn btn-success"
                            >

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

                                Save Assignments

                            </button>

                        </div>

                    </form>

                </div>

            <?php endif; ?>

        </div>

    </section>

</div>

<script>

document.getElementById('addRow')?.addEventListener('click', function () {

    const row = `
        <tr>

            <td>

                <select
                    name="subject_id[]"
                    class="form-control"
                    required
                >

                    <option value="">

                        Select Subject

                    </option>

                    <?php foreach ($subjects as $s): ?>

                        <option value="<?php echo (int) $s['id']; ?>">

                            <?php echo htmlspecialchars($s['name']); ?>

                        </option>

                    <?php endforeach; ?>

                </select>

            </td>

            <td>

                <select
                    name="teacher_id[]"
                    class="form-control"
                    required
                >

                    <option value="">

                        Select Teacher

                    </option>

                    <?php foreach ($teachers as $t): ?>

                        <option value="<?php echo (int) $t['id']; ?>">

                            <?php echo htmlspecialchars($t['name']); ?>

                        </option>

                    <?php endforeach; ?>

                </select>

            </td>

            <td class="text-center">

                <button
                    type="button"
                    class="btn btn-danger btn-sm removeRow"
                >

                    <i class="fas fa-trash"></i>

                </button>

            </td>

        </tr>
    `;

    document
        .querySelector('#assignmentTable tbody')
        .insertAdjacentHTML('beforeend', row);
});

document.addEventListener('click', function (e) {

    if (e.target.closest('.removeRow')) {

        e.target.closest('tr').remove();
    }
});

</script>

<?php require_once __DIR__ . '/../include/footer.php'; ?>