<?php

declare(strict_types=1);



session_start();

require_once '../../config.php';

requireModule('timetable');

require_once __DIR__ . '/helpers.php';



if (!isset($_SESSION['user_id'])) {

    header('Location: ../../login.php');

    exit;

}



$conn = getDBConnection();

if (!$conn instanceof mysqli) {

    http_response_code(500);

    exit('Database connection failed.');

}

$classes = timetableGetClasses($conn);

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Timetable - Period Setup</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

    <link rel="stylesheet" href="../../css/style.css">

    <style>

        .drag-handle { cursor: grab; }

        .period-row.dragging { opacity: 0.45; }

        .table td, .table th { vertical-align: middle; }

    </style>

</head>

<body>

    <div class="wrapper">

        <nav id="sidebar" class="sidebar">

        <?php echo buildSidebar('modules/timetable/' . basename($_SERVER['PHP_SELF'])); ?>

        </nav>



        <div id="content" class="content">

            <header class="top-navbar d-flex justify-content-between align-items-center flex-wrap gap-2">

                <div>

                    <h4 class="mb-1">Timetable - Period Setup</h4>

                    <div class="text-muted small">Periods are class-specific. Select a class to manage its periods.</div>

                </div>

                <div class="d-flex gap-2">

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

                        <i class="fas fa-arrow-left me-1"></i>Back

                    </a>

                    <button class="btn btn-primary" id="addPeriodBtn" disabled>

                        <i class="fas fa-plus me-1"></i>Add Period

                    </button>

                </div>

            </header>



            <main class="container-fluid py-4">

                <div class="card shadow-sm border-0 mb-4">

                    <div class="card-body">

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

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

                                <label class="form-label fw-semibold">Class</label>

                                <select id="classPicker" class="form-select">

                                    <option value="">— Select a class —</option>

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

                                        <option value="<?= htmlspecialchars($cls) ?>"><?= htmlspecialchars($cls) ?></option>

                                    <?php endforeach; ?>

                                </select>

                            </div>

                            <div class="col-md-8 text-muted small d-flex align-items-center">

                                <i class="fas fa-info-circle me-2 text-primary"></i>

                                Each class has its own set of periods. Drag rows to reorder. Time overlaps are checked per class.

                            </div>

                        </div>

                    </div>

                </div>



                <div id="noclassBanner" class="alert alert-secondary text-center py-4">

                    <i class="fas fa-chalkboard-teacher fa-2x mb-2 d-block text-muted"></i>

                    Select a class above to view and manage its periods.

                </div>



                <div id="periodTableWrap" style="display:none;">

                    <div class="card shadow-sm border-0">

                        <div class="card-body">

                            <div class="table-responsive">

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

                                    <thead class="table-light">

                                        <tr>

                                            <th style="width: 60px;"></th>

                                            <th>Order</th>

                                            <th>Period Name</th>

                                            <th>Start Time</th>

                                            <th>End Time</th>

                                            <th>Type</th>

                                            <th class="text-end">Actions</th>

                                        </tr>

                                    </thead>

                                    <tbody id="periodTableBody">

                                        <tr>

                                            <td colspan="7" class="text-center py-4 text-muted">Loading periods…</td>

                                        </tr>

                                    </tbody>

                                </table>

                            </div>

                        </div>

                    </div>

                </div>

            </main>

        </div>

    </div>



    <div class="modal fade" id="periodModal" tabindex="-1" aria-hidden="true">

        <div class="modal-dialog">

            <div class="modal-content">

                <form id="periodForm">

                    <div class="modal-header">

                        <h5 class="modal-title">Period Details</h5>

                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>

                    </div>

                    <div class="modal-body">

                        <input type="hidden" name="id" id="period_id" value="0">

                        <input type="hidden" name="class_name" id="modal_class_name" value="">

                        <div class="mb-3">

                            <label for="period_name" class="form-label">Period Name</label>

                            <input type="text" class="form-control" id="period_name" name="period_name" required>

                        </div>

                        <div class="row g-3">

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

                                <label for="start_time" class="form-label">Start Time</label>

                                <input type="time" class="form-control" id="start_time" name="start_time" required>

                            </div>

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

                                <label for="end_time" class="form-label">End Time</label>

                                <input type="time" class="form-control" id="end_time" name="end_time" required>

                            </div>

                        </div>

                        <div class="row g-3 mt-1">

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

                                <label for="order_no" class="form-label">Order No</label>

                                <input type="number" class="form-control" id="order_no" name="order_no" min="1" required>

                            </div>

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

                                <label for="period_type" class="form-label">Period Type</label>

                                <select class="form-select" id="period_type" name="period_type" onchange="togglePeriodTypeOther()">
                                    <?php
                                    $ptGroups = [];
                                    foreach (timetablePeriodTypes($conn) as $ptSlug => $ptMeta) {
                                        $ptGroups[$ptMeta["group"] ?? "Other"][$ptSlug] = $ptMeta;
                                    }
                                    foreach ($ptGroups as $ptGroupName => $ptItems): ?>
                                        <optgroup label="<?php echo htmlspecialchars($ptGroupName); ?>">
                                            <?php foreach ($ptItems as $ptSlug => $ptMeta): ?>
                                                <option value="<?php echo htmlspecialchars($ptSlug); ?>"><?php echo htmlspecialchars($ptMeta["icon"] . " " . $ptMeta["label"]); ?></option>
                                            <?php endforeach; ?>
                                        </optgroup>
                                    <?php endforeach; ?>
                                    <option value="__other__">➕ Other (type your own)...</option>
                                </select>
                                <input type="text" class="form-control mt-2 d-none" id="period_type_custom"
                                       name="period_type_custom" maxlength="30"
                                       placeholder="e.g. Nature Walk, Handwriting, Quiz Time">
                                <div class="form-text d-none" id="period_type_custom_help">
                                    Saved for this school and offered in this list from now on.
                                </div>

                            </div>

                        </div>

                    </div>

                    <div class="modal-footer">

                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>

                        <button type="submit" class="btn btn-primary">Save Period</button>

                    </div>

                </form>

            </div>

        </div>

    </div>



    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <script>

        const periodModal = new bootstrap.Modal(document.getElementById('periodModal'));

        let dragSourceRow = null;

        let currentPeriods = [];

        let selectedClass  = '';



        // ── Class picker ──────────────────────────────────────────────────────

        document.getElementById('classPicker').addEventListener('change', function () {

            selectedClass = this.value;

            const addBtn = document.getElementById('addPeriodBtn');

            const banner = document.getElementById('noclassBanner');

            const wrap   = document.getElementById('periodTableWrap');

            if (!selectedClass) {

                addBtn.disabled = true;

                banner.style.display = '';

                wrap.style.display   = 'none';

            } else {

                addBtn.disabled = false;

                banner.style.display = 'none';

                wrap.style.display   = '';

                loadPeriods();

            }

        });



        function escapeHtml(value) {

            return String(value ?? '').replace(/[&<>"']/g, function(char) {

                return ({

                    '&': '&amp;',

                    '<': '&lt;',

                    '>': '&gt;',

                    '"': '&quot;',

                    "'": '&#039;'

                })[char];

            });

        }



        function formatTime(value) {

            return value ? value.slice(0, 5) : '';

        }



        function showAlert(message, type = 'success') {

            const wrapper = document.createElement('div');

            wrapper.className = `alert alert-${type} alert-dismissible fade show position-fixed top-0 end-0 m-3`;

            wrapper.style.zIndex = '1080';

            wrapper.innerHTML = `${escapeHtml(message)}<button type="button" class="btn-close" data-bs-dismiss="alert"></button>`;

            document.body.appendChild(wrapper);

            setTimeout(() => wrapper.remove(), 3500);

        }



        const TYPE_BADGE = <?php echo json_encode(timetablePeriodTypes($conn), JSON_UNESCAPED_UNICODE); ?>;



        function getPeriodTypeFallback(period) {

            if (period.period_type && period.period_type !== 'teaching') return period.period_type;

            const n = (period.period_name || '').toLowerCase();

            if (/\bnap\b/.test(n)) return 'nap';

            if (/circle/.test(n)) return 'circle_time';

            if (/assembly/.test(n)) return 'assembly';

            if (/\blunch\b|launch/.test(n)) return 'lunch';

            if (/recess/.test(n)) return 'recess';

            if (/arrival|settling|reporting/.test(n)) return 'arrival';

            if (/routine/.test(n)) return 'routines';

            if (/silent/.test(n)) return 'silent_hour';

            if (Number(period.is_break) === 1) return 'break';

            return 'teaching';

        }



        function buildRow(period) {

            const pType = getPeriodTypeFallback(period);

            const badge = TYPE_BADGE[pType] || { icon: "🏷️", label: String(pType).replace(/_/g, " "), bg: "#e2e8f0", text: "#334155" };

            const typeBadge = `<span class="badge" style="background:${badge.bg};color:${badge.text};padding:.35em .65em">${badge.icon} ${escapeHtml(badge.label)}</span>`;



            return `

                <tr class="period-row" draggable="true"

                    data-id="${period.id}"

                    data-period_name="${escapeHtml(period.period_name)}"

                    data-start_time="${period.start_time}"

                    data-end_time="${period.end_time}"

                    data-period_type="${pType}"

                    data-order_no="${period.order_no}">

                    <td class="text-muted drag-handle"><i class="fas fa-grip-vertical"></i></td>

                    <td>${period.order_no}</td>

                    <td>${escapeHtml(period.period_name)}</td>

                    <td>${formatTime(period.start_time)}</td>

                    <td>${formatTime(period.end_time)}</td>

                    <td>${typeBadge}</td>

                    <td class="text-end">

                        <button class="btn btn-sm btn-outline-primary me-1" onclick="editPeriodById(${period.id})">

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

                        </button>

                        <button class="btn btn-sm btn-outline-danger" onclick="deletePeriod(${period.id})">

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

                        </button>

                    </td>

                </tr>

            `;

        }



        function bindDragEvents() {

            document.querySelectorAll('.period-row').forEach((row) => {

                row.addEventListener('dragstart', () => {

                    dragSourceRow = row;

                    row.classList.add('dragging');

                });

                row.addEventListener('dragend', () => {

                    row.classList.remove('dragging');

                });

                row.addEventListener('dragover', (event) => {

                    event.preventDefault();

                });

                row.addEventListener('drop', async (event) => {

                    event.preventDefault();

                    if (!dragSourceRow || dragSourceRow === row) {

                        return;

                    }



                    const tbody = document.getElementById('periodTableBody');

                    const rows = Array.from(tbody.querySelectorAll('.period-row'));

                    const sourceIndex = rows.indexOf(dragSourceRow);

                    const targetIndex = rows.indexOf(row);



                    if (sourceIndex < targetIndex) {

                        row.after(dragSourceRow);

                    } else {

                        row.before(dragSourceRow);

                    }



                    await persistOrder();

                });

            });

        }



        async function persistOrder() {

            const rows = Array.from(document.querySelectorAll('.period-row'));

            for (let index = 0; index < rows.length; index += 1) {

                const row = rows[index];

                const payload = new URLSearchParams({

                    id: row.dataset.id,

                    period_name: row.dataset.period_name,

                    start_time: row.dataset.start_time,

                    end_time: row.dataset.end_time,

                    period_type: row.dataset.period_type || 'teaching',

                    order_no: String(index + 1),

                    class_name: selectedClass

                });



                const response = await fetch('ajax/save_period.php', {

                    method: 'POST',

                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},

                    body: payload.toString()

                });



                const data = await response.json();

                if (!data.success) {

                    showAlert(data.message || 'Failed to reorder periods.', 'danger');

                    loadPeriods();

                    return;

                }

            }



            showAlert('Period order updated.');

            loadPeriods();

        }



        async function loadPeriods() {

            if (!selectedClass) return;

            const response = await fetch('ajax/get_periods.php?class_name=' + encodeURIComponent(selectedClass));

            const periods = await response.json();

            const tbody = document.getElementById('periodTableBody');



            if (!Array.isArray(periods) || periods.length === 0) {

                tbody.innerHTML = '<tr><td colspan="7" class="text-center py-4 text-muted">No periods found.</td></tr>';

                return;

            }



            currentPeriods = periods;

            tbody.innerHTML = periods.map(buildRow).join('');

            bindDragEvents();

        }



        // Reveals the free-text box when "Other" is picked, so a school can

        // name a period type we did not ship with.

        function togglePeriodTypeOther() {

            const isOther = document.getElementById('period_type').value === '__other__';

            document.getElementById('period_type_custom').classList.toggle('d-none', !isOther);

            document.getElementById('period_type_custom_help').classList.toggle('d-none', !isOther);

            document.getElementById('period_type_custom').required = isOther;

            if (!isOther) { document.getElementById('period_type_custom').value = ''; }

        }



        function resetForm() {

            document.getElementById('periodForm').reset();

            document.getElementById('period_id').value = '0';

            togglePeriodTypeOther();

        }



        function editPeriod(period) {

            document.getElementById('period_id').value = period.id;

            document.getElementById('period_name').value = period.period_name;

            document.getElementById('start_time').value = formatTime(period.start_time);

            document.getElementById('end_time').value = formatTime(period.end_time);

            document.getElementById('order_no').value = period.order_no;

            const pt = getPeriodTypeFallback(period);

            const ptSelect = document.getElementById('period_type');

            ptSelect.value = pt;

            if (ptSelect.value !== pt) {

                // A school-defined type missing from the list - surface it in

                // the free-text box instead of silently resetting to Teaching.

                ptSelect.value = '__other__';

                togglePeriodTypeOther();

                document.getElementById('period_type_custom').value = pt.replace(/_/g, ' ');

            } else {

                togglePeriodTypeOther();

            }

            document.getElementById('modal_class_name').value = selectedClass;

            periodModal.show();

        }



        function editPeriodById(id) {

            const period = currentPeriods.find((item) => Number(item.id) === Number(id));

            if (period) {

                editPeriod(period);

            }

        }



        async function deletePeriod(id) {

            if (!confirm('Delete this period?')) {

                return;

            }



            const payload = new URLSearchParams({id: String(id)});

            const response = await fetch('ajax/delete_period.php', {

                method: 'POST',

                headers: {'Content-Type': 'application/x-www-form-urlencoded'},

                body: payload.toString()

            });

            const data = await response.json();

            showAlert(data.message || (data.success ? 'Deleted.' : 'Delete failed.'), data.success ? 'success' : 'danger');

            if (data.success) {

                loadPeriods();

            }

        }



        document.getElementById('addPeriodBtn').addEventListener('click', function () {

            resetForm();

            document.getElementById('modal_class_name').value = selectedClass;

            periodModal.show();

        });



        document.getElementById('periodForm').addEventListener('submit', async function(event) {

            event.preventDefault();

            const formData = new FormData(event.target);

            formData.set('class_name', selectedClass);

            const response = await fetch('ajax/save_period.php', {

                method: 'POST',

                body: new URLSearchParams(formData)

            });

            const data = await response.json();

            showAlert(data.message || (data.success ? 'Saved.' : 'Save failed.'), data.success ? 'success' : 'danger');

            if (data.success) {

                periodModal.hide();

                resetForm();

                loadPeriods();

            }

        });

    </script>

</body>

</html>

