<?php

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

allow_roles(['admin', 'teacher']);

$page_title = 'Manage Subjects';

$school_id = $_SESSION['school_id'];

$message = '';

/*
|--------------------------------------------------------------------------
| VALID TYPES
|--------------------------------------------------------------------------
*/

$allowed_types = ['Theory', 'Practical'];

/*
|--------------------------------------------------------------------------
| ADD SUBJECT
|--------------------------------------------------------------------------
*/

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

    $name = trim($_POST['name'] ?? '');

    $subject_code = trim($_POST['subject_code'] ?? '');

    $type = trim($_POST['type'] ?? '');

    if (
        empty($name)
        ||
        empty($subject_code)
        ||
        !in_array($type, $allowed_types, true)
    ) {

        header("Location: subject.php?msg=Invalid Data");

        exit;
    }

    /*
    |--------------------------------------------------------------------------
    | CHECK DUPLICATE SUBJECT CODE
    |--------------------------------------------------------------------------
    */

    $checkStmt = $pdo->prepare("
        SELECT id
        FROM subjects
        WHERE school_id = ?
        AND subject_code = ?
        LIMIT 1
    ");

    $checkStmt->execute([
        $school_id,
        $subject_code
    ]);

    if ($checkStmt->fetch()) {

        header("Location: subject.php?msg=Subject Code Already Exists");

        exit;
    }

    /*
    |--------------------------------------------------------------------------
    | INSERT SUBJECT
    |--------------------------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        INSERT INTO subjects
        (
            school_id,
            name,
            subject_code,
            type
        )
        VALUES (?, ?, ?, ?)
    ");

    $stmt->execute([
        $school_id,
        $name,
        $subject_code,
        $type
    ]);

    header("Location: subject.php?msg=Subject Added Successfully");

    exit;
}

/*
|--------------------------------------------------------------------------
| DELETE SUBJECT
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_subject'])) {

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

    if ($delete_id > 0) {

        $stmt = $pdo->prepare("
            DELETE FROM subjects
            WHERE id = ?
            AND school_id = ?
            LIMIT 1
        ");

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

    header("Location: subject.php?msg=Subject Deleted Successfully");

    exit;
}

/*
|--------------------------------------------------------------------------
| EDIT SUBJECT
|--------------------------------------------------------------------------
*/

$edit_data = null;

$edit_id = (int) ($_GET['edit'] ?? 0);

if ($edit_id > 0) {

    $stmt = $pdo->prepare("
        SELECT *
        FROM subjects
        WHERE id = ?
        AND school_id = ?
        LIMIT 1
    ");

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

    $edit_data = $stmt->fetch(PDO::FETCH_ASSOC);
}

/*
|--------------------------------------------------------------------------
| UPDATE SUBJECT
|--------------------------------------------------------------------------
*/

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

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

    $name = trim($_POST['name'] ?? '');

    $subject_code = trim($_POST['subject_code'] ?? '');

    $type = trim($_POST['type'] ?? '');

    if (
        $id <= 0
        ||
        empty($name)
        ||
        empty($subject_code)
        ||
        !in_array($type, $allowed_types, true)
    ) {

        header("Location: subject.php?msg=Invalid Data");

        exit;
    }

    /*
    |--------------------------------------------------------------------------
    | CHECK DUPLICATE SUBJECT CODE
    |--------------------------------------------------------------------------
    */

    $checkStmt = $pdo->prepare("
        SELECT id
        FROM subjects
        WHERE school_id = ?
        AND subject_code = ?
        AND id != ?
        LIMIT 1
    ");

    $checkStmt->execute([
        $school_id,
        $subject_code,
        $id
    ]);

    if ($checkStmt->fetch()) {

        header("Location: subject.php?msg=Subject Code Already Exists");

        exit;
    }

    /*
    |--------------------------------------------------------------------------
    | UPDATE SUBJECT
    |--------------------------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        UPDATE subjects
        SET
            name = ?,
            subject_code = ?,
            type = ?
        WHERE id = ?
        AND school_id = ?
    ");

    $stmt->execute([
        $name,
        $subject_code,
        $type,
        $id,
        $school_id
    ]);

    header("Location: subject.php?msg=Subject Updated Successfully");

    exit;
}

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

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

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

$subjects = $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">

                        Manage Subjects

                    </h1>

                </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; ?>

            <div class="row">

                <!-- FORM -->

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

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

                        <div class="card-header">

                            <h3 class="card-title">

                                <?php echo $edit_data ? 'Edit Subject' : 'Add Subject'; ?>

                            </h3>

                        </div>

                        <form method="POST">

                            <div class="card-body">

                                <?php if ($edit_data): ?>

                                    <input
                                        type="hidden"
                                        name="id"
                                        value="<?php echo (int) $edit_data['id']; ?>"
                                    >

                                <?php endif; ?>

                                <!-- SUBJECT NAME -->

                                <div class="form-group">

                                    <label>

                                        Subject Name

                                    </label>

                                    <input
                                        type="text"
                                        name="name"
                                        class="form-control"
                                        maxlength="100"
                                        required
                                        value="<?php echo htmlspecialchars($edit_data['name'] ?? ''); ?>"
                                    >

                                </div>

                                <!-- SUBJECT CODE -->

                                <div class="form-group">

                                    <label>

                                        Subject Code

                                    </label>

                                    <input
                                        type="text"
                                        name="subject_code"
                                        class="form-control"
                                        maxlength="30"
                                        required
                                        value="<?php echo htmlspecialchars($edit_data['subject_code'] ?? ''); ?>"
                                    >

                                </div>

                                <!-- TYPE -->

                                <div class="form-group">

                                    <label>

                                        Subject Type

                                    </label>

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

                                        <option value="Theory"
                                            <?php echo (($edit_data['type'] ?? 'Theory') === 'Theory') ? 'selected' : ''; ?>>

                                            Theory

                                        </option>

                                        <option value="Practical"
                                            <?php echo (($edit_data['type'] ?? '') === 'Practical') ? 'selected' : ''; ?>>

                                            Practical

                                        </option>

                                    </select>

                                </div>

                            </div>

                            <div class="card-footer">

                                <button
                                    type="submit"
                                    name="<?php echo $edit_data ? 'update_subject' : 'add_subject'; ?>"
                                    class="btn btn-success"
                                >

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

                                    <?php echo $edit_data ? 'Update Subject' : 'Save Subject'; ?>

                                </button>

                                <?php if ($edit_data): ?>

                                    <a
                                        href="subject.php"
                                        class="btn btn-secondary"
                                    >

                                        Reset

                                    </a>

                                <?php endif; ?>

                            </div>

                        </form>

                    </div>

                </div>

                <!-- TABLE -->

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

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

                        <div class="card-header">

                            <h3 class="card-title">

                                Subject List

                            </h3>

                        </div>

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

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

                                <thead class="thead-dark">

                                    <tr>

                                        <th width="120">

                                            Subject Code

                                        </th>

                                        <th>

                                            Subject Name

                                        </th>

                                        <th width="130">

                                            Type

                                        </th>

                                        <th width="140">

                                            Actions

                                        </th>

                                    </tr>

                                </thead>

                                <tbody>

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

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

                                            <tr>

                                                <td>

                                                    <?php echo htmlspecialchars($sub['subject_code']); ?>

                                                </td>

                                                <td>

                                                    <strong>

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

                                                    </strong>

                                                </td>

                                                <td>

                                                    <span class="badge badge-info">

                                                        <?php echo htmlspecialchars($sub['type']); ?>

                                                    </span>

                                                </td>

                                                <td>

                                                    <a
                                                        href="subject.php?edit=<?php echo (int) $sub['id']; ?>"
                                                        class="btn btn-sm btn-warning"
                                                    >

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

                                                    </a>

                                                    <form
                                                        method="POST"
                                                        class="d-inline"
                                                        onsubmit="return confirm('Delete this subject?')"
                                                    >

                                                        <input
                                                            type="hidden"
                                                            name="delete_id"
                                                            value="<?php echo (int) $sub['id']; ?>"
                                                        >

                                                        <button
                                                            type="submit"
                                                            name="delete_subject"
                                                            class="btn btn-sm btn-danger"
                                                        >

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

                                                        </button>

                                                    </form>

                                                </td>

                                            </tr>

                                        <?php endforeach; ?>

                                    <?php else: ?>

                                        <tr>

                                            <td
                                                colspan="4"
                                                class="text-center text-muted"
                                            >

                                                No Subjects Found

                                            </td>

                                        </tr>

                                    <?php endif; ?>

                                </tbody>

                            </table>

                        </div>

                    </div>

                </div>

            </div>

        </div>

    </section>

</div>

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