<?php
declare(strict_types=1);

/**
 * EnglishSpeak
 * File: teacher/flashcards/create.php
 *
 * Create a reusable Flashcard Set, then continue to Word Library selection.
 */

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

$pdo = getDbConnection();

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

$pageTitle = 'New Flashcard Set';
$pageSubtitle = 'Create the Set first, then add words from Word Library';
$activeTeacherNav = 'flashcards';

$error = '';
$title = trim((string)($_POST['title'] ?? ''));
$description = trim((string)($_POST['description'] ?? ''));
$status = (string)($_POST['status'] ?? 'active');

if (!in_array($status, ['active', 'inactive'], true)) {
    $status = 'active';
}

/**
 * Resolve the teacher's current working book.
 */
$books = [];
if ($isAdmin) {
    $books = $pdo->query(
        "SELECT id, name, slug
         FROM books
         WHERE status = 'active'
         ORDER BY sort_order, name"
    )->fetchAll(PDO::FETCH_ASSOC);
} else {
    $bookStmt = $pdo->prepare(
        "SELECT b.id, b.name, b.slug
         FROM teacher_content_assignments tca
         INNER JOIN books b ON b.id = tca.book_id
         WHERE tca.teacher_id = ?
           AND tca.status = 'active'
           AND b.status = 'active'
         GROUP BY b.id, b.name, b.slug, b.sort_order
         ORDER BY b.sort_order, b.name"
    );
    $bookStmt->execute([$currentUserId]);
    $books = $bookStmt->fetchAll(PDO::FETCH_ASSOC);
}

$allowedBookIds = array_map(
    static fn(array $book): int => (int)$book['id'],
    $books
);

$currentBookId = max(0, (int)($_SESSION['teacher_book_id'] ?? 0));

if (!in_array($currentBookId, $allowedBookIds, true)) {
    $currentBookId = $allowedBookIds[0] ?? 0;
    if ($currentBookId > 0) {
        $_SESSION['teacher_book_id'] = $currentBookId;
    }
}

$currentBookName = '';
foreach ($books as $book) {
    if ((int)$book['id'] === $currentBookId) {
        $currentBookName = (string)$book['name'];
        break;
    }
}

$levelId = max(0, (int)($_POST['level_id'] ?? 0));
$levels = [];
if ($currentBookId > 0) {
    $levelStmt = $pdo->prepare(
        "SELECT id, name, level_number
         FROM levels
         WHERE book_id = ?
           AND status = 'active'
         ORDER BY sort_order, level_number, name"
    );
    $levelStmt->execute([$currentBookId]);
    $levels = $levelStmt->fetchAll(PDO::FETCH_ASSOC);
}

$allowedLevelIds = array_map(
    static fn(array $level): int => (int)$level['id'],
    $levels
);

if ($levelId > 0 && !in_array($levelId, $allowedLevelIds, true)) {
    $levelId = 0;
}

/**
 * @return array<string,array<string,mixed>>
 */
function fccColumns(PDO $pdo, string $table): array
{
    $stmt = $pdo->prepare(
        "SELECT COUNT(*)
         FROM information_schema.TABLES
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = ?"
    );
    $stmt->execute([$table]);

    if ((int)$stmt->fetchColumn() === 0) {
        return [];
    }

    $rows = $pdo->query("SHOW COLUMNS FROM `{$table}`")->fetchAll(PDO::FETCH_ASSOC);
    return array_column($rows, null, 'Field');
}

$setColumns = fccColumns($pdo, 'flashcard_sets');
$setBookColumns = fccColumns($pdo, 'flashcard_set_books');
$setLevelColumns = fccColumns($pdo, 'flashcard_set_levels');

$titleColumn = isset($setColumns['title'])
    ? 'title'
    : (isset($setColumns['name']) ? 'name' : null);

$descriptionColumn = isset($setColumns['description'])
    ? 'description'
    : null;

$statusColumn = isset($setColumns['status'])
    ? 'status'
    : null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($setBookColumns === []) {
        $error = 'Missing flashcard_set_books table. Run the provided SQL first.';
    } elseif ($setLevelColumns === []) {
        $error = 'Missing flashcard_set_levels table. Run the provided SQL first.';
    } elseif ($currentBookId <= 0) {
        $error = 'No active book is assigned to this teacher.';
    } elseif ($levelId <= 0 || !in_array($levelId, $allowedLevelIds, true)) {
        $error = 'Hãy chọn Lớp / Level thuộc sách đang làm việc.';
    } elseif ($titleColumn === null) {
        $error = 'The flashcard_sets table is missing a title or name column.';
    } elseif ($title === '') {
        $error = 'Please enter a Flashcard Set name.';
    } elseif (mb_strlen($title) > 255) {
        $error = 'Flashcard Set name must not exceed 255 characters.';
    } elseif (mb_strlen($description) > 2000) {
        $error = 'Description is too long.';
    } else {
        /*
         * Set names only need to be unique inside the current working book.
         * This allows, for example, "Unit 1. Lesson 1" to exist once in
         * Global Success and once in Everybody Up without adding the book
         * name to the Set title.
         */
        $duplicateStmt = $pdo->prepare(
            "SELECT fs.id
             FROM flashcard_sets fs
             INNER JOIN flashcard_set_books fsb
                     ON fsb.flashcard_set_id = fs.id
             INNER JOIN flashcard_set_levels fsl
                     ON fsl.flashcard_set_id = fs.id
             WHERE fsb.book_id = ?
               AND fsl.level_id = ?
               AND LOWER(TRIM(fs.`{$titleColumn}`)) = LOWER(TRIM(?))
             LIMIT 1"
        );
        $duplicateStmt->execute([$currentBookId, $levelId, $title]);

        if ($duplicateStmt->fetchColumn()) {
            $error = 'A Flashcard Set with this name already exists in ' . $currentBookName . '.';
        } else {
            try {
                $fields = [];
                $placeholders = [];
                $values = [];

                $appendValue = static function (
                    string $column,
                    mixed $value
                ) use (&$fields, &$placeholders, &$values): void {
                    $fields[] = "`{$column}`";
                    $placeholders[] = '?';
                    $values[] = $value;
                };

                $appendSql = static function (
                    string $column,
                    string $expression
                ) use (&$fields, &$placeholders): void {
                    $fields[] = "`{$column}`";
                    $placeholders[] = $expression;
                };

                $appendValue($titleColumn, $title);

                if ($descriptionColumn !== null) {
                    $appendValue(
                        $descriptionColumn,
                        $description !== '' ? $description : null
                    );
                }

                if ($statusColumn !== null) {
                    $appendValue($statusColumn, $status);
                }

                if (isset($setColumns['created_by_teacher_id'])) {
                    $appendValue(
                        'created_by_teacher_id',
                        $isAdmin ? null : $currentUserId
                    );
                }

                if (isset($setColumns['sort_order'])) {
                    $nextOrder = (int)$pdo->query(
                        "SELECT COALESCE(MAX(sort_order), 0) + 1
                         FROM flashcard_sets"
                    )->fetchColumn();

                    $appendValue('sort_order', $nextOrder);
                }

                if (isset($setColumns['created_at'])) {
                    $appendSql('created_at', 'NOW()');
                }

                if (isset($setColumns['updated_at'])) {
                    $appendSql('updated_at', 'NOW()');
                }

                $sql = sprintf(
                    "INSERT INTO flashcard_sets (%s) VALUES (%s)",
                    implode(', ', $fields),
                    implode(', ', $placeholders)
                );

                $pdo->beginTransaction();

                $stmt = $pdo->prepare($sql);
                $stmt->execute($values);

                $newId = (int)$pdo->lastInsertId();

                $bookLinkStmt = $pdo->prepare(
                    "INSERT IGNORE INTO flashcard_set_books
                        (flashcard_set_id, book_id, created_at)
                     VALUES (?, ?, NOW())"
                );
                $bookLinkStmt->execute([$newId, $currentBookId]);

                $levelLinkStmt = $pdo->prepare(
                    "INSERT INTO flashcard_set_levels
                        (flashcard_set_id, level_id, created_at)
                     VALUES (?, ?, NOW())"
                );
                $levelLinkStmt->execute([$newId, $levelId]);

                $pdo->commit();

                $_SESSION['flashcards_message'] =
                    'Flashcard Set created and linked to ' . $currentBookName . '. Add words from Word Library.';
                $_SESSION['flashcards_message_type'] = 'success';

                header('Location: edit.php?id=' . $newId);
                exit;
            } catch (Throwable $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }

                error_log(
                    'EnglishSpeak flashcards/create.php: ' . $e->getMessage()
                );

                $error = 'Could not create the Flashcard Set. Please try again.';
            }
        }
    }
}

ob_start();
?>

<style>
.fcc-page{display:grid;gap:18px;max-width:900px}
.fcc-head{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}
.fcc-head h2{margin:4px 0 0;font-size:28px}
.fcc-kicker{display:block;color:#2563eb;font-size:12px;font-weight:800;letter-spacing:.09em;text-transform:uppercase}
.fcc-subtitle{margin:7px 0 0;color:#64748b;line-height:1.55}
.fcc-layout{display:grid;grid-template-columns:minmax(0,1fr) 280px;gap:18px;align-items:start}
.fcc-card{padding:22px;border:1px solid #e5e7eb;border-radius:18px;background:#fff}
.fcc-field{display:grid;gap:8px;margin-bottom:18px}
.fcc-label{color:#0f172a;font-size:13px;font-weight:750}
.fcc-input,.fcc-select,.fcc-textarea{
 width:100%;border:1px solid #dbe2ea;border-radius:11px;background:#fff;color:#0f172a;font:inherit
}
.fcc-input,.fcc-select{min-height:44px;padding:0 13px}
.fcc-textarea{min-height:130px;padding:12px 13px;resize:vertical}
.fcc-input:focus,.fcc-select:focus,.fcc-textarea:focus{
 outline:3px solid rgba(37,99,235,.12);border-color:#2563eb
}
.fcc-help{color:#64748b;font-size:12px;line-height:1.45}
.fcc-book-badge{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 14px;border:1px solid #bfdbfe;border-radius:12px;background:#eff6ff;color:#1e3a8a}
.fcc-book-badge strong{font-size:13px}
.fcc-book-badge span{font-size:12px;color:#2563eb}
.fcc-error{padding:13px 15px;border:1px solid #fecaca;border-radius:12px;background:#fef2f2;color:#991b1b}
.fcc-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:22px;padding-top:18px;border-top:1px solid #eef2f7}
.fcc-flow{display:grid;gap:11px}
.fcc-step{display:flex;gap:11px;align-items:flex-start;padding:12px;border:1px solid #e5e7eb;border-radius:13px;background:#f8fafc}
.fcc-step-number{display:grid;place-items:center;width:30px;height:30px;flex:0 0 30px;border-radius:9px;background:#dbeafe;color:#1d4ed8;font-weight:850}
.fcc-step strong{display:block;font-size:13px}
.fcc-step small{display:block;margin-top:3px;color:#64748b;line-height:1.45}
.fcc-note{margin-top:14px;padding:12px;border:1px dashed #93c5fd;border-radius:12px;background:#eff6ff;color:#1d4ed8;font-size:12px;line-height:1.55}
@media(max-width:760px){.fcc-head{flex-direction:column}.fcc-layout{grid-template-columns:1fr}.fcc-actions{flex-direction:column-reverse}.fcc-actions .button{width:100%}}
</style>

<div class="fcc-page">
    <div class="fcc-head">
        <div>
            <span class="fcc-kicker">Shared Content</span>
            <h2>New Flashcard Set</h2>
            <p class="fcc-subtitle">
                Create one reusable Set, then select words from the shared Word Library.
            </p>
        </div>

        <a class="button button-secondary" href="index.php">
            ← Back to Sets
        </a>
    </div>

    <?php if ($error !== ''): ?>
        <div class="fcc-error">
            <?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?>
        </div>
    <?php endif; ?>

    <div class="fcc-layout">
        <form class="fcc-card" method="post">
            <div class="fcc-field">
                <label class="fcc-label">Sách đang làm việc</label>
                <div class="fcc-book-badge">
                    <strong>📘 <?= htmlspecialchars($currentBookName !== '' ? $currentBookName : 'Chưa có sách', ENT_QUOTES, 'UTF-8') ?></strong>
                    <span>Set mới sẽ tự gắn nhãn sách này</span>
                </div>
            </div>

            <div class="fcc-field">
                <label class="fcc-label" for="level_id">Lớp / Level *</label>
                <select class="fcc-select" id="level_id" name="level_id" required>
                    <option value="">-- Chọn Lớp / Level --</option>
                    <?php foreach ($levels as $level): ?>
                        <option value="<?= (int)$level['id'] ?>" <?= $levelId === (int)$level['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars((string)$level['name'], ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <div class="fcc-help">Chỉ hiện Level thuộc <?= htmlspecialchars($currentBookName !== '' ? $currentBookName : 'sách đang làm việc', ENT_QUOTES, 'UTF-8') ?>.</div>
            </div>

            <div class="fcc-field">
                <label class="fcc-label" for="title">
                    Flashcard Set Name *
                </label>

                <input
                    class="fcc-input"
                    id="title"
                    name="title"
                    maxlength="255"
                    required
                    autofocus
                    value="<?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?>"
                    placeholder="Unit 1. Lesson 1"
                >

                <div class="fcc-help">
                    Chỉ nhập tên nội dung, ví dụ: Unit 1. Lesson 1. Sách sẽ được hệ thống tự gắn theo sách đang làm việc.
                </div>
            </div>

            <div class="fcc-field">
                <label class="fcc-label" for="description">
                    Description
                </label>

                <textarea
                    class="fcc-textarea"
                    id="description"
                    name="description"
                    maxlength="2000"
                    placeholder="Optional note about the purpose or content of this Set..."
                ><?= htmlspecialchars($description, ENT_QUOTES, 'UTF-8') ?></textarea>
            </div>

            <?php if ($statusColumn !== null): ?>
                <div class="fcc-field">
                    <label class="fcc-label" for="status">
                        Status
                    </label>

                    <select class="fcc-select" id="status" name="status">
                        <option value="active" <?= $status === 'active' ? 'selected' : '' ?>>
                            Active
                        </option>
                        <option value="inactive" <?= $status === 'inactive' ? 'selected' : '' ?>>
                            Hidden
                        </option>
                    </select>
                </div>
            <?php endif; ?>

            <div class="fcc-actions">
                <a class="button button-secondary" href="index.php">
                    Cancel
                </a>

                <button class="button button-primary" type="submit">
                    Create and Add Words
                </button>
            </div>
        </form>

        <aside class="fcc-card">
            <span class="fcc-kicker">Workflow</span>
            <h3 style="margin:4px 0 14px">What happens next?</h3>

            <div class="fcc-flow">
                <div class="fcc-step">
                    <span class="fcc-step-number">1</span>
                    <div>
                        <strong>Create the Set</strong>
                        <small>Save the Set name and description.</small>
                    </div>
                </div>

                <div class="fcc-step">
                    <span class="fcc-step-number">2</span>
                    <div>
                        <strong>Select Words</strong>
                        <small>Choose existing words from Word Library.</small>
                    </div>
                </div>

                <div class="fcc-step">
                    <span class="fcc-step-number">3</span>
                    <div>
                        <strong>Reuse in Activities</strong>
                        <small>Connect the Set to Flashcards, Memory, Matching and Quiz.</small>
                    </div>
                </div>
            </div>

            <div class="fcc-note">
                Words are not duplicated. The Set only stores references to the shared Word Library.
            </div>
        </aside>
    </div>
</div>

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