<?php

declare(strict_types=1);

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

allow_roles(['admin']);

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

$page_title = 'Weekly Off Settings';

// ======================================================
// DAYS
// ======================================================

$days = [

    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday'

];

// ======================================================
// SAVE SETTINGS
// ======================================================

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

    try {

        $selected_days =
            $_POST['days'] ?? [];

        if (!is_array($selected_days)) {

            $selected_days = [];
        }

        // ==============================================
        // VALIDATE DAYS
        // ==============================================

        foreach ($selected_days as $day) {

            if (
                !in_array(
                    $day,
                    $days,
                    true
                )
            ) {

                throw new Exception(
                    'Invalid weekly off day.'
                );
            }
        }

        $pdo->beginTransaction();

        // ==============================================
        // DELETE OLD
        // ==============================================

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

            WHERE school_id = ?
        ");

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

        // ==============================================
        // INSERT NEW
        // ==============================================

        if (!empty($selected_days)) {

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

                    school_id,
                    day_name

                )

                VALUES (

                    ?, ?

                )
            ");

            foreach ($selected_days as $day) {

                $stmt->execute([

                    $school_id,
                    $day

                ]);
            }
        }

        $pdo->commit();

        header(
            'Location: weekly_offs.php?msg=' .
            urlencode('Weekly offs updated successfully.')
        );

        exit;

    } catch (Throwable $e) {

        if ($pdo->inTransaction()) {

            $pdo->rollBack();
        }

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

// ======================================================
// FETCH CURRENT SETTINGS
// ======================================================

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

    FROM weekly_offs

    WHERE school_id = ?
");

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

$current_offs = array_column(

    $stmt->fetchAll(PDO::FETCH_ASSOC),

    'day_name'

);

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

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

?>

<div class="content-wrapper">

    <!-- ============================================== -->
    <!-- HEADER -->
    <!-- ============================================== -->

    <section class="content-header">

        <div class="container-fluid">

            <div>

                <h1>

                    <i class="fas fa-bed text-warning"></i>

                    Weekly Off Settings

                </h1>

                <small class="text-muted">

                    Configure school weekly holidays

                </small>

            </div>

        </div>

    </section>

    <!-- ============================================== -->
    <!-- CONTENT -->
    <!-- ============================================== -->

    <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 justify-content-center">

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

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

                        <div class="card-header">

                            <h3 class="card-title">

                                Select Weekly Off Days

                            </h3>

                        </div>

                        <form method="POST">

                            <div class="card-body">

                                <div class="row">

                                    <?php foreach ($days as $day) : ?>

                                        <div class="col-12 col-md-6 mb-3">

                                            <div class="custom-control custom-checkbox">

                                                <input
                                                    type="checkbox"
                                                    class="custom-control-input"
                                                    id="<?= strtolower($day) ?>"
                                                    name="days[]"
                                                    value="<?= $day ?>"

                                                    <?= in_array($day, $current_offs, true)
                                                        ? 'checked'
                                                        : '' ?>
                                                >

                                                <label
                                                    class="custom-control-label"
                                                    for="<?= strtolower($day) ?>"
                                                >

                                                    <?= htmlspecialchars($day) ?>

                                                </label>

                                            </div>

                                        </div>

                                    <?php endforeach; ?>

                                </div>

                            </div>

                            <div class="card-footer">

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

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

                                    Save Weekly Offs

                                </button>

                            </div>

                        </form>

                    </div>

                </div>

            </div>

        </div>

    </section>

</div>

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