<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Sentence Sets
 * File: teacher/sentence-sets/index.php
 */

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

$pdo = getDbConnection();

$pageTitle = 'Sentence Sets';
$pageSubtitle = 'Manage reusable sentence sets';
$activeTeacherNav = 'content';

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

/*
 * Current working Book + Level.
 */
$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;
    }
}

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

$requestedLevelId = max(0, (int)($_GET['level_id'] ?? 0));
$currentLevelId = in_array($requestedLevelId, $allowedLevelIds, true)
    ? $requestedLevelId
    : ($allowedLevelIds[0] ?? 0);

function ssTableExists(PDO $pdo, string $table): bool
{
    $stmt = $pdo->prepare(
        "SELECT COUNT(*)
         FROM information_schema.TABLES
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = ?"
    );
    $stmt->execute([$table]);

    return (int)$stmt->fetchColumn() > 0;
}

function ssColumns(PDO $pdo, string $table): array
{
    if (!ssTableExists($pdo, $table)) {
        return [];
    }

    $rows = $pdo
        ->query("SHOW COLUMNS FROM `{$table}`")
        ->fetchAll(PDO::FETCH_ASSOC);

    return array_column($rows, null, 'Field');
}

function ssFirstColumn(array $columns, array $candidates): ?string
{
    foreach ($candidates as $candidate) {
        if (isset($columns[$candidate])) {
            return $candidate;
        }
    }

    return null;
}

if (!ssTableExists($pdo, 'sentence_sets')) {
    http_response_code(500);
    exit('The sentence_sets table does not exist.');
}

if (!ssTableExists($pdo, 'sentence_set_sentences')) {
    http_response_code(500);
    exit('The sentence_set_sentences table does not exist.');
}

if (!ssTableExists($pdo, 'sentence_set_books') || !ssTableExists($pdo, 'sentence_set_levels')) {
    http_response_code(500);
    exit('Run the Sentence Set Book/Level SQL first.');
}

$setColumns = ssColumns($pdo, 'sentence_sets');
if (!isset($setColumns['created_by_teacher_id'])) { http_response_code(500); exit('Run ADD_OWNER_COLUMN.sql first.'); }

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string)($_POST['action'] ?? ''));

    try {
        if ($action === 'delete') {
            $setId = max(0, (int)($_POST['id'] ?? 0));

            if ($setId <= 0) {
                throw new RuntimeException('Invalid Sentence Set.');
            }

            $ownerStmt = $pdo->prepare('SELECT created_by_teacher_id FROM sentence_sets WHERE id = ? LIMIT 1');
            $ownerStmt->execute([$setId]);
            $owner = $ownerStmt->fetchColumn();
            if ($owner === false) { throw new RuntimeException('Sentence Set not found.'); }
            if (!$isAdmin && ($owner === null || (int)$owner !== $currentUserId)) { throw new RuntimeException('Bạn không có quyền xóa Set này.'); }

            $pdo->beginTransaction();

            $deleteItems = $pdo->prepare(
                'DELETE FROM sentence_set_sentences WHERE sentence_set_id = ?'
            );
            $deleteItems->execute([$setId]);

            $pdo->prepare('DELETE FROM sentence_set_levels WHERE sentence_set_id = ?')->execute([$setId]);
            $pdo->prepare('DELETE FROM sentence_set_books WHERE sentence_set_id = ?')->execute([$setId]);

            $deleteSet = $pdo->prepare(
                'DELETE FROM sentence_sets WHERE id = ?'
            );
            $deleteSet->execute([$setId]);

            $pdo->commit();
            $success = 'Sentence Set deleted.';
        }
    } catch (Throwable $exception) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        $error = $exception->getMessage();
    }
}

$search = trim((string)($_GET['q'] ?? ''));
$status = trim((string)($_GET['status'] ?? ''));

$where = [];
$params = [];

if ($search !== '') {
    $where[] = '(ss.title LIKE ? OR ss.description LIKE ?)';
    $params[] = '%' . $search . '%';
    $params[] = '%' . $search . '%';
}

if (in_array($status, ['active', 'inactive'], true)) {
    $where[] = 'ss.status = ?';
    $params[] = $status;
}

if ($currentBookId > 0) {
    $bookCondition = "EXISTS (
        SELECT 1
        FROM sentence_set_books ssb_filter
        WHERE ssb_filter.sentence_set_id = ss.id
          AND ssb_filter.book_id = ?
    )";

    /*
     * Legacy unlinked Sets remain visible only to Admin or their owner,
     * so they can be opened and assigned Book + Level once.
     */
    if ($isAdmin) {
        $bookCondition = "(" . $bookCondition . " OR NOT EXISTS (
            SELECT 1 FROM sentence_set_books ssb_any
            WHERE ssb_any.sentence_set_id = ss.id
        ))";
    } else {
        $bookCondition = "(" . $bookCondition . " OR (
            ss.created_by_teacher_id = ?
            AND NOT EXISTS (
                SELECT 1 FROM sentence_set_books ssb_any
                WHERE ssb_any.sentence_set_id = ss.id
            )
        ))";
    }

    $where[] = $bookCondition;
    $params[] = $currentBookId;
    if (!$isAdmin) {
        $params[] = $currentUserId;
    }
}

if ($currentLevelId > 0) {
    $levelCondition = "EXISTS (
        SELECT 1
        FROM sentence_set_levels ssl_filter
        WHERE ssl_filter.sentence_set_id = ss.id
          AND ssl_filter.level_id = ?
    )";

    if ($isAdmin) {
        $levelCondition = "(" . $levelCondition . " OR NOT EXISTS (
            SELECT 1 FROM sentence_set_levels ssl_any
            WHERE ssl_any.sentence_set_id = ss.id
        ))";
    } else {
        $levelCondition = "(" . $levelCondition . " OR (
            ss.created_by_teacher_id = ?
            AND NOT EXISTS (
                SELECT 1 FROM sentence_set_levels ssl_any
                WHERE ssl_any.sentence_set_id = ss.id
            )
        ))";
    }

    $where[] = $levelCondition;
    $params[] = $currentLevelId;
    if (!$isAdmin) {
        $params[] = $currentUserId;
    }
}

$sql =
    "SELECT
        ss.id,
        ss.title,
        ss.description,
        ss.status,
        ss.created_at,
        ss.updated_at,
        ss.created_by_teacher_id,
        COUNT(DISTINCT sss.id) AS sentence_count,
        COALESCE(
            (
                SELECT GROUP_CONCAT(
                    DISTINCT CONCAT(b.name, ' → ', l.name)
                    ORDER BY b.sort_order, b.name, l.sort_order, l.level_number, l.name
                    SEPARATOR ' · '
                )
                FROM sentence_set_levels sslev
                INNER JOIN levels l ON l.id = sslev.level_id
                INNER JOIN books b ON b.id = l.book_id
                INNER JOIN sentence_set_books ssb
                        ON ssb.sentence_set_id = sslev.sentence_set_id
                       AND ssb.book_id = l.book_id
                WHERE sslev.sentence_set_id = ss.id
            ),
            ''
        ) AS book_level_pairs
     FROM sentence_sets ss
     LEFT JOIN sentence_set_sentences sss
       ON sss.sentence_set_id = ss.id";

if ($where !== []) {
    $sql .= ' WHERE ' . implode(' AND ', $where);
}

$sql .=
    " GROUP BY
        ss.id,
        ss.title,
        ss.description,
        ss.status,
        ss.created_at,
        ss.updated_at,
        ss.created_by_teacher_id
      ORDER BY ss.id DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$sets = $stmt->fetchAll(PDO::FETCH_ASSOC);

ob_start();
?>

<style>
.ss-page{display:grid;gap:16px}
.ss-head{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}
.ss-kicker{color:#7c3aed;font-size:12px;font-weight:850;letter-spacing:.08em;text-transform:uppercase}
.ss-title{margin:3px 0 0;color:#0f172a;font-size:28px}
.ss-subtitle{margin:6px 0 0;color:#64748b;font-size:14px}
.ss-actions{display:flex;gap:8px;flex-wrap:wrap}
.ss-message{padding:12px 14px;border-radius:12px;font-weight:750}
.ss-error{border:1px solid #fecaca;background:#fef2f2;color:#991b1b}
.ss-success{border:1px solid #bbf7d0;background:#ecfdf3;color:#166534}
.ss-toolbar{display:grid;grid-template-columns:minmax(220px,1fr) minmax(160px,210px) 180px auto;gap:9px;padding:14px;border:1px solid #e5e7eb;border-radius:16px;background:#fff}
.ss-input,.ss-select{width:100%;min-height:42px;padding:8px 11px;border:1px solid #dbe2ea;border-radius:10px;background:#fff;color:#0f172a;font:inherit}
.ss-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}
.ss-card{padding:16px;border:1px solid #e5e7eb;border-radius:17px;background:#fff;box-shadow:0 5px 16px rgba(15,23,42,.04)}
.ss-card-top{display:flex;justify-content:space-between;gap:12px}
.ss-card h3{margin:0;color:#0f172a;font-size:18px;line-height:1.35}
.ss-desc{min-height:40px;margin:8px 0 0;color:#64748b;font-size:13px;line-height:1.5}
.ss-meta{display:flex;gap:8px;flex-wrap:wrap;margin-top:14px}
.ss-pill{display:inline-flex;padding:5px 9px;border-radius:999px;background:#eff6ff;color:#1d4ed8;font-size:11px;font-weight:800}
.ss-active{background:#dcfce7;color:#166534}
.ss-inactive{background:#f1f5f9;color:#475569}
.ss-card-actions{display:flex;gap:7px;flex-wrap:wrap;margin-top:15px}
.ss-empty{padding:60px 20px;border:1px solid #e5e7eb;border-radius:16px;background:#fff;text-align:center;color:#64748b}
@media(max-width:1050px){.ss-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:720px){.ss-head{flex-direction:column}.ss-toolbar{grid-template-columns:1fr}.ss-grid{grid-template-columns:1fr}}
</style>

<div class="ss-page">
    <div class="ss-head">
        <div>
            <span class="ss-kicker">Sentence Sets</span>
            <h2 class="ss-title">Sentence Sets</h2>
            <p class="ss-subtitle">
                Group reusable sentences for Sentence Builder and Speaking activities.
            </p>
        </div>

        <div class="ss-actions">
            <a class="button button-secondary" href="../sentence-library/index.php">
                Sentence Library
            </a>
            <a class="button button-primary" href="create.php">
                + Create Sentence Set
            </a>
        </div>
    </div>

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

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

    <form class="ss-toolbar" method="get">
        <input
            class="ss-input"
            type="search"
            name="q"
            placeholder="Search Sentence Sets..."
            value="<?= htmlspecialchars($search, ENT_QUOTES, 'UTF-8') ?>"
        >

        <select class="ss-select" name="level_id" onchange="this.form.submit()">
            <?php foreach ($levels as $level): ?>
                <option value="<?= (int)$level['id'] ?>" <?= $currentLevelId === (int)$level['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars((string)$level['name'], ENT_QUOTES, 'UTF-8') ?>
                </option>
            <?php endforeach; ?>
        </select>

        <select class="ss-select" name="status">
            <option value="">All status</option>
            <option value="active" <?= $status === 'active' ? 'selected' : '' ?>>
                Active
            </option>
            <option value="inactive" <?= $status === 'inactive' ? 'selected' : '' ?>>
                Inactive
            </option>
        </select>

        <button class="button button-secondary" type="submit">
            Search
        </button>
    </form>

    <?php if ($sets === []): ?>
        <div class="ss-empty">
            No Sentence Sets found.
        </div>
    <?php else: ?>
        <div class="ss-grid">
            <?php foreach ($sets as $set): ?>
                <article class="ss-card">
                    <div class="ss-card-top">
                        <div>
                            <h3><?= htmlspecialchars(
                                (string)$set['title'],
                                ENT_QUOTES,
                                'UTF-8'
                            ) ?></h3>

                            <p class="ss-desc">
                                <?= (string)$set['description'] !== ''
                                    ? htmlspecialchars(
                                        (string)$set['description'],
                                        ENT_QUOTES,
                                        'UTF-8'
                                    )
                                    : 'No description.' ?>
                            </p>
                        </div>
                    </div>

                    <div class="ss-meta">
                        <?php if ((string)$set['book_level_pairs'] !== ''): ?>
                            <?php foreach (explode(' · ', (string)$set['book_level_pairs']) as $pair): ?>
                                <span class="ss-pill">
                                    📘 <?= htmlspecialchars(trim($pair), ENT_QUOTES, 'UTF-8') ?>
                                </span>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <span class="ss-pill" style="background:#fff7ed;color:#c2410c;">
                                📘 Chưa gắn Book / Level
                            </span>
                        <?php endif; ?>

                        <span class="ss-pill">
                            <?= (int)$set['sentence_count'] ?> sentence(s)
                        </span>

                        <span class="ss-pill <?= $set['status'] === 'inactive'
                            ? 'ss-inactive'
                            : 'ss-active' ?>">
                            <?= $set['status'] === 'inactive'
                                ? 'Inactive'
                                : 'Active' ?>
                        </span>
                    </div>

                    <div class="ss-card-actions">
                        <?php $canManageSet = $isAdmin || ($set['created_by_teacher_id'] !== null && (int)$set['created_by_teacher_id'] === $currentUserId); ?>
                        <?php if ($canManageSet): ?>
                        <a class="button button-sm button-primary" href="detail.php?id=<?= (int)$set['id'] ?>">Manage</a>
                        <a class="button button-sm button-secondary" href="edit.php?id=<?= (int)$set['id'] ?>">Edit</a>
                        <?php endif; ?>

                        <a
                            class="button button-sm button-secondary"
                            href="preview.php?id=<?= (int)$set['id'] ?>"
                            target="_blank"
                        >
                            Preview
                        </a>

                        <?php if ($canManageSet): ?>
                        <form
                            method="post"
                            onsubmit="return confirm('Delete this Sentence Set?');"
                            style="display:inline;"
                        >
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?= (int)$set['id'] ?>">

                            <button
                                class="button button-sm button-secondary"
                                type="submit"
                                style="color:var(--danger);"
                            >
                                Delete
                            </button>
                        </form>
                        <?php endif; ?>
                    </div>
                </article>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

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