<?php

declare(strict_types=1);

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

allow_roles(['admin']);

$school_id = (int) $_SESSION['school_id'];

$page_title = 'Holiday Management';

// ======================================================
// ADD HOLIDAY
// ======================================================

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

    try {

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

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

        $holiday_type = trim(
            $_POST['holiday_type'] ?? 'Holiday'
        );

        $allowed_types = [

            'Holiday',
            'Vacation',
            'Event'

        ];

        // ==============================================
        // VALIDATION
        // ==============================================

        if ($title === '') {

            throw new Exception(
                'Holiday title required.'
            );
        }

        if (
            !preg_match(
                '/^\d{4}-\d{2}-\d{2}$/',
                $holiday_date
            )
        ) {

            throw new Exception(
                'Invalid holiday date.'
            );
        }

        if (
            !in_array(
                $holiday_type,
                $allowed_types,
                true
            )
        ) {

            throw new Exception(
                'Invalid holiday type.'
            );
        }

        // ==============================================
        // DUPLICATE CHECK
        // ==============================================

        $stmt = $pdo->prepare("
            SELECT id

            FROM holidays

            WHERE school_id = ?
            AND holiday_date = ?

            LIMIT 1
        ");

        $stmt->execute([

            $school_id,
            $holiday_date

        ]);

        if ($stmt->fetch()) {

            throw new Exception(
                'Holiday already exists for this date.'
            );
        }

        // ==============================================
        // INSERT
        // ==============================================

        $stmt = $pdo->prepare("
            INSERT INTO holidays (

                school_id,
                title,
                holiday_date,
                holiday_type

            )

            VALUES (

                ?, ?, ?, ?

            )
        ");

        $stmt->execute([

            $school_id,
            $title,
            $holiday_date,
            $holiday_type

        ]);

        header(
            'Location: holidays.php?msg=' .
            urlencode('Holiday added successfully.')
        );

        exit;

    } catch (Throwable $e) {

        $error = $e->getMessage();
    }
}

// ======================================================
// DELETE HOLIDAY
// ======================================================

if (isset($_GET['delete'])) {

    $holiday_id = (int) ($_GET['delete'] ?? 0);

    if ($holiday_id > 0) {

        $stmt = $pdo->prepare("
            DELETE FROM holidays

            WHERE id = ?
            AND school_id = ?
        ");

        $stmt->execute([

            $holiday_id,
            $school_id

        ]);

        header(
            'Location: holidays.php?msg=' .
            urlencode('Holiday deleted.')
        );

        exit;
    }
}

// ======================================================
// FETCH HOLIDAYS
// ======================================================

$stmt = $pdo->prepare("
    SELECT

        id,
        title,
        holiday_date,
        holiday_type,
        created_at

    FROM holidays

    WHERE school_id = ?

    ORDER BY holiday_date DESC
");

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

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

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="d-flex justify-content-between align-items-center">

                <div>

                    <h1>

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

                        Holiday Management

                    </h1>

                    <small class="text-muted">

                        Manage school holidays

                    </small>

                </div>

            </div>

        </div>

    </section>

    <section class="content">

        <div class="container-fluid">

            <!-- ALERT -->

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

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

                    <?= htmlspecialchars($_GET['msg']) ?>

                    <button
                        type="button"
                        class="close"
                        data-dismiss="alert"
                    >
                        <span>&times;</span>
                    </button>

                </div>

            <?php endif; ?>

            <?php if (isset($error)) : ?>

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

                    <?= htmlspecialchars($error) ?>

                    <button
                        type="button"
                        class="close"
                        data-dismiss="alert"
                    >
                        <span>&times;</span>
                    </button>

                </div>

            <?php endif; ?>

            <div class="row">

                <!-- ====================================== -->
                <!-- ADD HOLIDAY -->
                <!-- ====================================== -->

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

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

                        <div class="card-header">

                            <h3 class="card-title">

                                Add Holiday

                            </h3>

                        </div>

                        <form method="POST">

                            <div class="card-body">

                                <div class="form-group">

                                    <label>

                                        Holiday Title *

                                    </label>

                                    <input
                                        type="text"
                                        name="title"
                                        class="form-control"
                                        maxlength="100"
                                        required
                                    >

                                </div>

                                <div class="form-group">

                                    <label>

                                        Holiday Date *

                                    </label>

                                    <input
                                        type="date"
                                        name="holiday_date"
                                        class="form-control"
                                        required
                                    >

                                </div>

                                <div class="form-group">

                                    <label>

                                        Holiday Type *

                                    </label>

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

                                        <option value="Holiday">

                                            Holiday

                                        </option>

                                        <option value="Vacation">

                                            Vacation

                                        </option>

                                        <option value="Event">

                                            Event

                                        </option>

                                    </select>

                                </div>

                            </div>

                            <div class="card-footer">

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

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

                                    Add Holiday

                                </button>

                            </div>

                        </form>

                    </div>

                </div>

                <!-- ====================================== -->
                <!-- HOLIDAY LIST -->
                <!-- ====================================== -->

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

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

                        <div class="card-header">

                            <h3 class="card-title">

                                Holiday List

                            </h3>

                        </div>

                        <div class="card-body p-0">

                            <div class="table-responsive">

                                <table class="table table-hover mb-0">

                                    <thead class="thead-light">

                                        <tr>

                                            <th>Title</th>
                                            <th>Date</th>
                                            <th>Type</th>
                                            <th width="120">

                                                Action

                                            </th>

                                        </tr>

                                    </thead>

                                    <tbody>

                                        <?php if (empty($holidays)) : ?>

                                            <tr>

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

                                                    No holidays added

                                                </td>

                                            </tr>

                                        <?php endif; ?>

                                        <?php foreach ($holidays as $holiday) : ?>

                                            <tr>

                                                <td>

                                                    <?= htmlspecialchars($holiday['title']) ?>

                                                </td>

                                                <td>

                                                    <?= date(
                                                        'd M Y',
                                                        strtotime($holiday['holiday_date'])
                                                    ) ?>

                                                </td>

                                                <td>

                                                    <span class="badge badge-info">

                                                        <?= htmlspecialchars($holiday['holiday_type']) ?>

                                                    </span>

                                                </td>

                                                <td>

                                                    <a
                                                        href="?delete=<?= (int) $holiday['id'] ?>"
                                                        class="btn btn-sm btn-danger"
                                                        onclick="return confirm('Delete holiday?')"
                                                    >

                                                        Delete

                                                    </a>

                                                </td>

                                            </tr>

                                        <?php endforeach; ?>

                                    </tbody>

                                </table>

                            </div>

                        </div>

                    </div>

                </div>

            </div>

        </div>

    </section>

</div>

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