<?php
declare(strict_types=1);

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

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

$pdo = getDbConnection();

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

$booksStmt = $pdo->query(
    "SELECT id, name
     FROM books
     WHERE status = 'active'
     ORDER BY sort_order ASC, name ASC"
);
$books = $booksStmt->fetchAll(PDO::FETCH_ASSOC);

$selectedBookId = max(0, (int)($_GET['book_id'] ?? ($_SESSION['units_old']['book_id'] ?? 0)));
$old = is_array($_SESSION['units_old'] ?? null) ? $_SESSION['units_old'] : [];
$errors = is_array($_SESSION['units_errors'] ?? null) ? $_SESSION['units_errors'] : [];

unset($_SESSION['units_old'], $_SESSION['units_errors']);

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

ob_start();
?>

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

<div class="unit-form-page">
    <div class="unit-form-header">
        <div>
            <span class="unit-form-kicker">Content Library</span>
            <h2>New Unit</h2>
            <p style="margin:7px 0 0;color:#64748b">
                Add a Unit to Global Success or Everybody Up.
            </p>
        </div>

        <a href="index.php<?= $selectedBookId > 0 ? '?book_id=' . $selectedBookId : '' ?>" class="button button-secondary">
            ← Back to Units
        </a>
    </div>

    <?php if ($errors !== []): ?>
        <div class="unit-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="unit-form-card" action="store.php" method="post" enctype="multipart/form-data">
        <div class="unit-form-grid">
            <div class="unit-form-field">
                <label class="unit-form-label" for="book_id">Book *</label>
                <select class="unit-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'];
                        $isSelected = $bookId === (int)($old['book_id'] ?? $selectedBookId);
                        ?>
                        <option value="<?= $bookId ?>" <?= $isSelected ? 'selected' : '' ?>>
                            <?= htmlspecialchars((string)$book['name'], ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <div class="unit-form-help">Each Unit must belong to exactly one Book.</div>
            </div>

            <div class="unit-form-field">
                <label class="unit-form-label" for="unit_number">Unit Number *</label>
                <input
                    class="unit-form-input"
                    id="unit_number"
                    name="unit_number"
                    type="text"
                    maxlength="20"
                    value="<?= oldValue($old, 'unit_number') ?>"
                    placeholder="Unit 1"
                    required
                >
                <div class="unit-form-help">Examples: Unit 1, Unit 2, Review 1.</div>
            </div>

            <div class="unit-form-field unit-form-field-full">
                <label class="unit-form-label" for="title">Unit Title *</label>
                <input
                    class="unit-form-input"
                    id="title"
                    name="title"
                    type="text"
                    maxlength="150"
                    value="<?= oldValue($old, 'title') ?>"
                    placeholder="In the school playground"
                    required
                >
            </div>

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

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

            <div class="unit-form-field">
                <label class="unit-form-label" for="sort_order">Sort Order</label>
                <input
                    class="unit-form-input"
                    id="sort_order"
                    name="sort_order"
                    type="number"
                    min="0"
                    value="<?= oldValue($old, 'sort_order', '0') ?>"
                >
                <div class="unit-form-help">Lower numbers appear first.</div>
            </div>

            <div class="unit-form-field">
                <label class="unit-form-label" for="required_xp">Required XP</label>
                <input
                    class="unit-form-input"
                    id="required_xp"
                    name="required_xp"
                    type="number"
                    min="0"
                    value="<?= oldValue($old, 'required_xp', '0') ?>"
                >
                <div class="unit-form-help">Keep 0 if this Unit has no XP requirement.</div>
            </div>

            <div class="unit-form-field">
                <label class="unit-form-label" for="status">Status</label>
                <?php $oldStatus = (string)($old['status'] ?? 'active'); ?>
                <select class="unit-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="unit-form-field unit-form-field-full">
                <div class="unit-form-preview" aria-live="polite">
                    <div class="unit-form-preview-badge" id="unitPreviewBadge">U</div>
                    <div>
                        <strong id="unitPreviewTitle">New Unit</strong>
                        <small id="unitPreviewBook">Choose a Book</small>
                    </div>
                </div>
            </div>
        </div>

        <div class="unit-form-actions">
            <a href="index.php<?= $selectedBookId > 0 ? '?book_id=' . $selectedBookId : '' ?>" class="button button-secondary">
                Cancel
            </a>
            <button type="submit" class="button button-primary">
                Save Unit
            </button>
        </div>
    </form>
</div>

<script>
(function () {
    const book = document.getElementById('book_id');
    const number = document.getElementById('unit_number');
    const title = document.getElementById('title');
    const previewBadge = document.getElementById('unitPreviewBadge');
    const previewTitle = document.getElementById('unitPreviewTitle');
    const previewBook = document.getElementById('unitPreviewBook');

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

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

        const selected = book.options[book.selectedIndex];
        previewBook.textContent = selected && selected.value ? selected.text : 'Choose a Book';
    }

    book.addEventListener('change', updatePreview);
    number.addEventListener('input', updatePreview);
    title.addEventListener('input', updatePreview);
    updatePreview();
})();
</script>

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