<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Teacher Units
 * File: teacher/units/edit.php
 *
 * Updates one Unit under one Book.
 */

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

$pdo = getDbConnection();

$unitId = max(0, (int)($_GET['id'] ?? 0));

if ($unitId <= 0) {
    $_SESSION['units_message'] = 'Invalid Unit ID.';
    $_SESSION['units_message_type'] = 'error';
    header('Location: index.php');
    exit;
}

$unitStmt = $pdo->prepare(
    "SELECT
        id,
        book_id,
        unit_number,
        title,
        thumbnail,
        description,
        required_xp,
        sort_order,
        status
     FROM units
     WHERE id = ?
     LIMIT 1"
);
$unitStmt->execute([$unitId]);
$unit = $unitStmt->fetch(PDO::FETCH_ASSOC);

if (!$unit) {
    $_SESSION['units_message'] = 'Unit not found.';
    $_SESSION['units_message_type'] = 'error';
    header('Location: index.php');
    exit;
}

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

$pageTitle = 'Edit Unit';
$pageSubtitle = 'Update Unit information';
$activeTeacherNav = 'content';

$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']);

$form = [
    'book_id' => $old['book_id'] ?? $unit['book_id'],
    'unit_number' => $old['unit_number'] ?? $unit['unit_number'],
    'title' => $old['title'] ?? $unit['title'],
    'description' => $old['description'] ?? ($unit['description'] ?? ''),
    'required_xp' => $old['required_xp'] ?? $unit['required_xp'],
    'sort_order' => $old['sort_order'] ?? $unit['sort_order'],
    'status' => $old['status'] ?? $unit['status'],
];

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

$thumbnailUrl = '';
if (!empty($unit['thumbnail'])) {
    $thumbnailUrl = '../../' . ltrim((string)$unit['thumbnail'], '/');
}

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}
.unit-thumbnail-row{display:flex;align-items:center;gap:14px}
.unit-thumbnail-preview{width:88px;height:64px;border:1px solid #e2e8f0;border-radius:12px;overflow:hidden;background:#f8fafc;display:grid;place-items:center;color:#94a3b8}
.unit-thumbnail-preview img{width:100%;height:100%;object-fit:cover}
.unit-checkbox{display:flex;align-items:center;gap:8px;color:#475569;font-size:13px}
@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>Edit Unit</h2>
            <p style="margin:7px 0 0;color:#64748b">
                Update Unit information without changing its lessons.
            </p>
        </div>

        <a href="index.php?book_id=<?= (int)$unit['book_id'] ?>" 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="update.php" method="post" enctype="multipart/form-data">
        <input type="hidden" name="id" value="<?= $unitId ?>">

        <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']; ?>
                        <option value="<?= $bookId ?>" <?= $bookId === (int)$form['book_id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars((string)$book['name'], ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <div class="unit-form-help">Moving a Unit to another Book keeps its lessons.</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="<?= editOldValue($form, 'unit_number') ?>"
                    required
                >
            </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="<?= editOldValue($form, 'title') ?>"
                    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..."
                ><?= editOldValue($form, 'description') ?></textarea>
            </div>

            <div class="unit-form-field unit-form-field-full">
                <label class="unit-form-label" for="thumbnail">Thumbnail</label>

                <div class="unit-thumbnail-row">
                    <div class="unit-thumbnail-preview">
                        <?php if ($thumbnailUrl !== ''): ?>
                            <img src="<?= htmlspecialchars($thumbnailUrl, ENT_QUOTES, 'UTF-8') ?>" alt="">
                        <?php else: ?>
                            No image
                        <?php endif; ?>
                    </div>

                    <div style="flex:1;display:grid;gap:8px">
                        <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">Upload a new image only when you want to replace the current one.</div>

                        <?php if ($thumbnailUrl !== ''): ?>
                            <label class="unit-checkbox">
                                <input type="checkbox" name="remove_thumbnail" value="1">
                                Remove current thumbnail
                            </label>
                        <?php endif; ?>
                    </div>
                </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="<?= editOldValue($form, 'sort_order', '0') ?>"
                >
            </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="<?= editOldValue($form, 'required_xp', '0') ?>"
                >
            </div>

            <div class="unit-form-field">
                <label class="unit-form-label" for="status">Status</label>
                <select class="unit-form-select" id="status" name="status">
                    <option value="active" <?= (string)$form['status'] === 'active' ? 'selected' : '' ?>>Active</option>
                    <option value="inactive" <?= (string)$form['status'] === '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">Unit</strong>
                        <small id="unitPreviewBook">Book</small>
                    </div>
                </div>
            </div>
        </div>

        <div class="unit-form-actions">
            <a href="index.php?book_id=<?= (int)$unit['book_id'] ?>" class="button button-secondary">
                Cancel
            </a>
            <button type="submit" class="button button-primary">
                Save Changes
            </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(' • ') || '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';
