<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Teacher Lessons
 * File: teacher/lessons/create.php
 *
 * Architecture:
 * Books -> Units -> Lessons -> Practices
 */

require __DIR__ . '/../partials/auth.php';
require_once __DIR__ . '/../../config/database.php';

$pdo = getDbConnection();

$teacherId = (int)($_SESSION['teacher_id'] ?? $_SESSION['user_id'] ?? 0);
$role = strtolower((string)($_SESSION['role'] ?? $_SESSION['user_role'] ?? 'teacher'));
$isAdmin = ($role === 'admin');

if (!$isAdmin && $teacherId <= 0) {
    http_response_code(403);
    exit('Teacher account not found.');
}

$pageTitle = 'New Lesson';
$pageSubtitle = 'Create a new Lesson inside a Unit';
$activeTeacherNav = 'content';

if ($isAdmin) {
    $booksStmt = $pdo->query(
        "SELECT id, name
         FROM books
         WHERE status = 'active'
         ORDER BY sort_order ASC, name ASC"
    );
} else {
    $booksStmt = $pdo->prepare(
        "SELECT DISTINCT b.id, b.name, b.sort_order
         FROM books b
         INNER JOIN teacher_books tb ON tb.book_id = b.id
         WHERE b.status = 'active'
           AND tb.teacher_id = ?
         ORDER BY b.sort_order ASC, b.name ASC"
    );
    $booksStmt->execute([$teacherId]);
}
$books = $booksStmt->fetchAll(PDO::FETCH_ASSOC);
$allowedBookIds = array_map(static fn(array $book): int => (int)$book['id'], $books);

$old = is_array($_SESSION['lessons_old'] ?? null) ? $_SESSION['lessons_old'] : [];
$errors = is_array($_SESSION['lessons_errors'] ?? null) ? $_SESSION['lessons_errors'] : [];

unset($_SESSION['lessons_old'], $_SESSION['lessons_errors']);

$selectedUnitId = max(0, (int)($_GET['unit_id'] ?? ($old['unit_id'] ?? 0)));
$selectedBookId = max(0, (int)($old['book_id'] ?? 0));

if ($selectedUnitId > 0 && $selectedBookId <= 0) {
    $selectedUnitStmt = $pdo->prepare(
        "SELECT book_id
         FROM units
         WHERE id = ?
         LIMIT 1"
    );
    $selectedUnitStmt->execute([$selectedUnitId]);
    $selectedBookId = (int)($selectedUnitStmt->fetchColumn() ?: 0);
}

if (
    !$isAdmin
    && $selectedBookId > 0
    && !in_array($selectedBookId, $allowedBookIds, true)
) {
    $selectedBookId = 0;
    $selectedUnitId = 0;
}

$unitsSql = "
    SELECT
        u.id,
        u.book_id,
        u.unit_number,
        u.title,
        b.name AS book_name
    FROM units u
    INNER JOIN books b ON b.id = u.book_id
    WHERE u.status = 'active'
";

$unitsParams = [];

if (!$isAdmin) {
    $unitsSql .= "
        AND EXISTS (
            SELECT 1
            FROM teacher_books tb
            WHERE tb.teacher_id = :teacher_id
              AND tb.book_id = u.book_id
        )
    ";
    $unitsParams[':teacher_id'] = $teacherId;
}

if ($selectedBookId > 0) {
    $unitsSql .= " AND u.book_id = :book_id";
    $unitsParams[':book_id'] = $selectedBookId;
}

$unitsSql .= " ORDER BY b.sort_order ASC, u.sort_order ASC, u.id ASC";

$unitsStmt = $pdo->prepare($unitsSql);
$unitsStmt->execute($unitsParams);
$units = $unitsStmt->fetchAll(PDO::FETCH_ASSOC);

if ($selectedUnitId > 0) {
    $validUnitIds = array_map(static fn(array $unit): int => (int)$unit['id'], $units);
    if (!in_array($selectedUnitId, $validUnitIds, true)) {
        $selectedUnitId = 0;
    }
}

function lessonOldValue(array $old, string $key, string $default = ''): string
{
    return htmlspecialchars((string)($old[$key] ?? $default), ENT_QUOTES, 'UTF-8');
}

$oldStatus = (string)($old['status'] ?? 'active');
$oldAccessType = (string)($old['access_type'] ?? 'free');
$oldLessonType = (string)($old['lesson_type'] ?? 'vocabulary');
$oldUnlockMode = (string)($old['unlock_mode'] ?? 'sequential_daily');
$oldUnlockDate = (string)($old['unlock_date'] ?? '');

ob_start();
?>

<style>
.lesson-form-page{display:grid;gap:18px;max-width:1000px}
.lesson-form-header{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}
.lesson-form-header h2{margin:4px 0 0;font-size:28px;line-height:1.2}
.lesson-form-kicker{display:block;color:#7c3aed;font-size:12px;font-weight:800;letter-spacing:.09em;text-transform:uppercase}
.lesson-form-card{padding:22px;border:1px solid #e5e7eb;border-radius:18px;background:#fff}
.lesson-form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}
.lesson-form-field{display:grid;gap:8px}
.lesson-form-field-full{grid-column:1/-1}
.lesson-form-label{color:#0f172a;font-size:13px;font-weight:750}
.lesson-form-help{color:#64748b;font-size:12px;line-height:1.45}
.lesson-form-input,.lesson-form-select,.lesson-form-textarea{
    width:100%;
    border:1px solid #dbe2ea;
    border-radius:11px;
    background:#fff;
    color:#0f172a;
    font:inherit
}
.lesson-form-input,.lesson-form-select{min-height:44px;padding:0 13px}
.lesson-form-textarea{min-height:120px;padding:12px 13px;resize:vertical}
.lesson-form-input:focus,.lesson-form-select:focus,.lesson-form-textarea:focus{
    outline:3px solid rgba(124,58,237,.12);
    border-color:#7c3aed
}
.lesson-form-actions{display:flex;align-items:center;justify-content:flex-end;gap:10px;margin-top:22px;padding-top:18px;border-top:1px solid #eef2f7}
.lesson-form-errors{padding:14px 16px;border:1px solid #fecaca;border-radius:13px;background:#fef2f2;color:#991b1b}
.lesson-form-errors strong{display:block;margin-bottom:6px}
.lesson-form-errors ul{margin:0;padding-left:20px}
.lesson-form-preview{display:flex;align-items:center;gap:12px;padding:14px;border:1px dashed #cbd5e1;border-radius:14px;background:#faf8ff}
.lesson-form-preview-badge{display:grid;place-items:center;flex:0 0 52px;height:52px;border-radius:14px;background:#f1eaff;color:#7c3aed;font-weight:850}
.lesson-form-preview strong{display:block;color:#0f172a}
.lesson-form-preview small{display:block;margin-top:4px;color:#64748b}
@media(max-width:760px){
    .lesson-form-header{flex-direction:column;align-items:stretch}
    .lesson-form-grid{grid-template-columns:1fr}
    .lesson-form-field-full{grid-column:auto}
    .lesson-form-actions{justify-content:stretch}
    .lesson-form-actions .button{flex:1}
}
</style>

<div class="lesson-form-page">
    <div class="lesson-form-header">
        <div>
            <span class="lesson-form-kicker">Content Library</span>
            <h2>New Lesson</h2>
            <p style="margin:7px 0 0;color:#64748b">
                Add a Lesson inside a Unit.
            </p>
        </div>

        <a
            href="index.php<?= $selectedUnitId > 0 ? '?unit_id=' . $selectedUnitId : '' ?>"
            class="button button-secondary"
        >
            ← Back to Lessons
        </a>
    </div>

    <?php if ($errors !== []): ?>
        <div class="lesson-form-errors">
            <strong>Please check the following:</strong>
            <ul>
                <?php foreach ($errors as $error): ?>
                    <li><?= htmlspecialchars((string)$error, ENT_QUOTES, 'UTF-8') ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <form class="lesson-form-card" action="store.php" method="post" enctype="multipart/form-data">
        <div class="lesson-form-grid">
            <div class="lesson-form-field">
                <label class="lesson-form-label" for="book_id">Book *</label>
                <select class="lesson-form-select" id="book_id" name="book_id" required>
                    <option value="">Select a Book</option>
                    <?php foreach ($books as $book): ?>
                        <?php $bookId = (int)$book['id']; ?>
                        <option value="<?= $bookId ?>" <?= $bookId === $selectedBookId ? 'selected' : '' ?>>
                            <?= htmlspecialchars((string)$book['name'], ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <div class="lesson-form-help">Choose a Book first to narrow the Unit list.</div>
            </div>

            <div class="lesson-form-field">
                <label class="lesson-form-label" for="unit_id">Unit *</label>
                <select class="lesson-form-select" id="unit_id" name="unit_id" required>
                    <option value="">Select a Unit</option>
                    <?php foreach ($units as $unit): ?>
                        <?php $unitId = (int)$unit['id']; ?>
                        <option value="<?= $unitId ?>" <?= $unitId === $selectedUnitId ? 'selected' : '' ?>>
                            <?= htmlspecialchars(
                                (string)$unit['unit_number'] . ' • ' . (string)$unit['title'],
                                ENT_QUOTES,
                                'UTF-8'
                            ) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <div class="lesson-form-help">Each Lesson belongs to exactly one Unit.</div>
            </div>

            <div class="lesson-form-field">
                <label class="lesson-form-label" for="lesson_number">Lesson Number *</label>
                <input
                    class="lesson-form-input"
                    id="lesson_number"
                    name="lesson_number"
                    type="text"
                    maxlength="30"
                    value="<?= lessonOldValue($old, 'lesson_number') ?>"
                    placeholder="Lesson 1"
                    required
                >
            </div>

            <div class="lesson-form-field">
                <label class="lesson-form-label" for="lesson_type">Lesson Type</label>
                <select class="lesson-form-select" id="lesson_type" name="lesson_type">
                    <option value="vocabulary" <?= $oldLessonType === 'vocabulary' ? 'selected' : '' ?>>Vocabulary</option>
                    <option value="listening" <?= $oldLessonType === 'listening' ? 'selected' : '' ?>>Listening</option>
                    <option value="speaking" <?= $oldLessonType === 'speaking' ? 'selected' : '' ?>>Speaking</option>
                    <option value="reading" <?= $oldLessonType === 'reading' ? 'selected' : '' ?>>Reading</option>
                    <option value="writing" <?= $oldLessonType === 'writing' ? 'selected' : '' ?>>Writing</option>
                    <option value="phonics" <?= $oldLessonType === 'phonics' ? 'selected' : '' ?>>Phonics</option>
                    <option value="story" <?= $oldLessonType === 'story' ? 'selected' : '' ?>>Story</option>
                    <option value="review" <?= $oldLessonType === 'review' ? 'selected' : '' ?>>Review</option>
                    <option value="song" <?= $oldLessonType === 'song' ? 'selected' : '' ?>>Song</option>
                    <option value="chant" <?= $oldLessonType === 'chant' ? 'selected' : '' ?>>Chant</option>
                </select>
            </div>

            <div class="lesson-form-field lesson-form-field-full">
                <label class="lesson-form-label" for="title">Lesson Title *</label>
                <input
                    class="lesson-form-input"
                    id="title"
                    name="title"
                    type="text"
                    maxlength="150"
                    value="<?= lessonOldValue($old, 'title') ?>"
                    placeholder="Listen and repeat."
                    required
                >
            </div>

            <div class="lesson-form-field lesson-form-field-full">
                <label class="lesson-form-label" for="description">Description</label>
                <textarea
                    class="lesson-form-textarea"
                    id="description"
                    name="description"
                    placeholder="Optional notes for this Lesson..."
                ><?= lessonOldValue($old, 'description') ?></textarea>
            </div>

            <div class="lesson-form-field">
                <label class="lesson-form-label" for="thumbnail">Thumbnail</label>
                <input
                    class="lesson-form-input"
                    id="thumbnail"
                    name="thumbnail"
                    type="file"
                    accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp"
                >
                <div class="lesson-form-help">Optional. JPG, PNG or WEBP, maximum 3 MB.</div>
            </div>

            <div class="lesson-form-field">
                <label class="lesson-form-label" for="access_type">Access</label>
                <select class="lesson-form-select" id="access_type" name="access_type">
                    <option value="free" <?= $oldAccessType === 'free' ? 'selected' : '' ?>>Free</option>
                    <option value="premium" <?= $oldAccessType === 'premium' ? 'selected' : '' ?>>Premium</option>
                </select>
            </div>

            <div class="lesson-form-field">
                <label class="lesson-form-label" for="required_xp">Required XP</label>
                <input
                    class="lesson-form-input"
                    id="required_xp"
                    name="required_xp"
                    type="number"
                    min="0"
                    value="<?= lessonOldValue($old, 'required_xp', '0') ?>"
                >
            </div>

            <div class="lesson-form-field">
                <label class="lesson-form-label" for="unlock_mode">Unlock Mode</label>
                <select class="lesson-form-select" id="unlock_mode" name="unlock_mode">
                    <option value="sequential_daily" <?= $oldUnlockMode === 'sequential_daily' ? 'selected' : '' ?>>Sequential Daily</option>
                    <option value="scheduled" <?= $oldUnlockMode === 'scheduled' ? 'selected' : '' ?>>Scheduled Unlock</option>
                </select>
                <div class="lesson-form-help">Sequential Daily opens the next Lesson no earlier than the next day. Scheduled Unlock uses a specific date.</div>
            </div>

            <div class="lesson-form-field" id="unlockDateField" <?= $oldUnlockMode === 'scheduled' ? '' : 'hidden' ?>>
                <label class="lesson-form-label" for="unlock_date">Unlock Date</label>
                <input
                    class="lesson-form-input"
                    id="unlock_date"
                    name="unlock_date"
                    type="date"
                    value="<?= htmlspecialchars($oldUnlockDate, ENT_QUOTES, 'UTF-8') ?>"
                >
                <div class="lesson-form-help">Used only for Scheduled Unlock.</div>
            </div>

            <div class="lesson-form-field">
                <label class="lesson-form-label" for="sort_order">Sort Order</label>
                <input
                    class="lesson-form-input"
                    id="sort_order"
                    name="sort_order"
                    type="number"
                    min="0"
                    value="<?= lessonOldValue($old, 'sort_order', '0') ?>"
                >
            </div>

            <div class="lesson-form-field">
                <label class="lesson-form-label" for="status">Status</label>
                <select class="lesson-form-select" id="status" name="status">
                    <option value="active" <?= $oldStatus === 'active' ? 'selected' : '' ?>>Active</option>
                    <option value="inactive" <?= $oldStatus === 'inactive' ? 'selected' : '' ?>>Hidden</option>
                </select>
            </div>

            <div class="lesson-form-field lesson-form-field-full">
                <div class="lesson-form-preview" aria-live="polite">
                    <div class="lesson-form-preview-badge" id="lessonPreviewBadge">L</div>
                    <div>
                        <strong id="lessonPreviewTitle">New Lesson</strong>
                        <small id="lessonPreviewPath">Choose a Book and Unit</small>
                    </div>
                </div>
            </div>
        </div>

        <div class="lesson-form-actions">
            <a
                href="index.php<?= $selectedUnitId > 0 ? '?unit_id=' . $selectedUnitId : '' ?>"
                class="button button-secondary"
            >
                Cancel
            </a>

            <button type="submit" class="button button-primary">
                Save Lesson
            </button>
        </div>
    </form>
</div>

<script>
(function () {
    const book = document.getElementById('book_id');
    const unit = document.getElementById('unit_id');
    const number = document.getElementById('lesson_number');
    const title = document.getElementById('title');
    const unlockMode = document.getElementById('unlock_mode');
    const unlockDate = document.getElementById('unlock_date');
    const unlockDateField = document.getElementById('unlockDateField');
    const previewBadge = document.getElementById('lessonPreviewBadge');
    const previewTitle = document.getElementById('lessonPreviewTitle');
    const previewPath = document.getElementById('lessonPreviewPath');

    book.addEventListener('change', function () {
        const bookId = this.value;
        const url = new URL(window.location.href);

        if (bookId) {
            url.searchParams.set('book_id', bookId);
        } else {
            url.searchParams.delete('book_id');
        }

        url.searchParams.delete('unit_id');
        window.location.href = url.toString();
    });

    function updateUnlockFields() {
        const scheduled = unlockMode && unlockMode.value === 'scheduled';
        if (unlockDateField) unlockDateField.hidden = !scheduled;
        if (unlockDate) unlockDate.required = scheduled;
        if (!scheduled && unlockDate) unlockDate.value = '';
    }

    function updatePreview() {
        const numberText = (number.value || '').trim();
        const titleText = (title.value || '').trim();

        const match = numberText.match(/\d+/);
        previewBadge.textContent = match ? 'L' + match[0] : 'L';
        previewTitle.textContent = [numberText, titleText].filter(Boolean).join(' • ') || 'New Lesson';

        const bookOption = book.options[book.selectedIndex];
        const unitOption = unit.options[unit.selectedIndex];

        const parts = [];

        if (bookOption && bookOption.value) {
            parts.push(bookOption.text);
        }

        if (unitOption && unitOption.value) {
            parts.push(unitOption.text);
        }

        previewPath.textContent = parts.length ? parts.join(' → ') : 'Choose a Book and Unit';
    }

    unlockMode?.addEventListener('change', updateUnlockFields);
    unit.addEventListener('change', updatePreview);
    number.addEventListener('input', updatePreview);
    title.addEventListener('input', updatePreview);
    updateUnlockFields();
    updatePreview();
})();
</script>

<?php
$content = ob_get_clean();
require __DIR__ . '/../layouts/app.php';
