<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Preview Sentence Set
 * File: teacher/sentence-sets/preview.php
 */

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

$pdo = getDbConnection();

$pageTitle = 'Preview Sentence Set';
$pageSubtitle = 'Review sentences in this reusable set';
$activeTeacherNav = 'sentence-sets';

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

function sspTableExists(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 sspColumns(PDO $pdo, string $table): array
{
    if (!sspTableExists($pdo, $table)) {
        return [];
    }

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

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

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

    return null;
}

function sspNormalizeWord(string $value): string
{
    $value = mb_strtolower(trim($value), 'UTF-8');
    $value = preg_replace('/[^\p{L}\p{N}\']+/u', '', $value) ?? $value;
    return trim($value);
}

function sspSentenceTokens(string $sentence): array
{
    $sentence = mb_strtolower($sentence, 'UTF-8');
    $parts = preg_split('/[^\p{L}\p{N}\']+/u', $sentence) ?: [];

    return array_values(array_filter(array_map(
        static fn(string $part): string => sspNormalizeWord($part),
        $parts
    )));
}

function sspAssetUrl(string $path): string
{
    $path = trim($path);

    if ($path === '') {
        return '';
    }

    if (
        str_starts_with($path, 'http://')
        || str_starts_with($path, 'https://')
        || str_starts_with($path, 'data:')
        || str_starts_with($path, '/')
    ) {
        return $path;
    }

    return '/EnglishSpeak/' . ltrim($path, './');
}

if (
    !sspTableExists($pdo, 'sentence_sets')
    || !sspTableExists($pdo, 'sentence_set_sentences')
    || !sspTableExists($pdo, 'sentences')
) {
    http_response_code(500);
    exit('Sentence Set tables are missing.');
}

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

if ($setId <= 0) {
    http_response_code(400);
    exit('Invalid Sentence Set.');
}

$setStmt = $pdo->prepare(
    'SELECT id, title, description, status, created_by_teacher_id
     FROM sentence_sets
     WHERE id = ?
     LIMIT 1'
);
$setStmt->execute([$setId]);
$set = $setStmt->fetch(PDO::FETCH_ASSOC);

if (!$set) {
    http_response_code(404);
    exit('Sentence Set not found.');
}
$canManageSet = $isAdmin || ($set['created_by_teacher_id'] !== null && (int)$set['created_by_teacher_id'] === $currentUserId);

$sentenceColumns = sspColumns($pdo, 'sentences');
$itemColumns = sspColumns($pdo, 'sentence_set_sentences');

$textColumn = sspFirstColumn(
    $sentenceColumns,
    ['sentence_text', 'sentence', 'text', 'content']
);

$meaningColumn = sspFirstColumn(
    $sentenceColumns,
    ['vietnamese_meaning', 'meaning_vi', 'meaning']
);

$audioColumn = sspFirstColumn(
    $sentenceColumns,
    ['audio_url', 'audio_path', 'audio', 'tts_audio']
);

$imageColumn = sspFirstColumn(
    $sentenceColumns,
    ['image_path', 'image', 'image_url']
);


if ($textColumn === null) {
    http_response_code(500);
    exit('Sentence text column is missing.');
}

$meaningSelect = $meaningColumn !== null
    ? "s.`{$meaningColumn}` AS vietnamese_meaning"
    : "'' AS vietnamese_meaning";

$audioSelect = $audioColumn !== null
    ? "s.`{$audioColumn}` AS audio_value"
    : "'' AS audio_value";

$imageSelect = $imageColumn !== null
    ? "s.`{$imageColumn}` AS image_path"
    : "'' AS image_path";


$orderSql = isset($itemColumns['display_order'])
    ? 'ORDER BY sss.display_order ASC, sss.id ASC'
    : 'ORDER BY sss.id ASC';

$itemsStmt = $pdo->prepare(
    "SELECT
        s.id,
        s.`{$textColumn}` AS sentence_text,
        {$meaningSelect},
        {$audioSelect},
        {$imageSelect}
     FROM sentence_set_sentences sss
     INNER JOIN sentences s
       ON s.id = sss.sentence_id
     WHERE sss.sentence_set_id = ?
     {$orderSql}"
);
$itemsStmt->execute([$setId]);
$sentences = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);

/*
 * Preview does not resolve images by itself.
 * It calls the shared resolver used by Sentence Library.
 */
foreach ($sentences as &$sentence) {
    $resolvedImage = esResolveSentenceImage(
        $pdo,
        (string)$sentence['sentence_text'],
        (string)($sentence['image_path'] ?? '')
    );

    $sentence['image_value'] = (string)($resolvedImage['url'] ?? '');
    $sentence['image_source'] = (string)($resolvedImage['source'] ?? 'none');
}
unset($sentence);

ob_start();
?>

<style>
.ssp-page{display:grid;gap:16px}
.ssp-head{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}
.ssp-kicker{color:#7c3aed;font-size:12px;font-weight:850;letter-spacing:.08em;text-transform:uppercase}
.ssp-title{margin:3px 0 0;color:#0f172a;font-size:28px}
.ssp-subtitle{margin:6px 0 0;color:#64748b;font-size:14px}
.ssp-actions{display:flex;gap:8px;flex-wrap:wrap}
.ssp-summary{display:flex;gap:8px;flex-wrap:wrap}
.ssp-pill{display:inline-flex;padding:6px 10px;border-radius:999px;background:#eff6ff;color:#1d4ed8;font-size:12px;font-weight:800}
.ssp-active{background:#dcfce7;color:#166534}
.ssp-inactive{background:#f1f5f9;color:#475569}
.ssp-description{padding:15px;border:1px solid #e5e7eb;border-radius:15px;background:#fff;color:#475569;line-height:1.6}
.ssp-list{display:grid;gap:12px}
.ssp-card{display:grid;grid-template-columns:48px minmax(0,1fr) auto;gap:14px;align-items:start;padding:16px;border:1px solid #e5e7eb;border-radius:16px;background:#fff;box-shadow:0 4px 14px rgba(15,23,42,.04)}
.ssp-number{display:grid;place-items:center;width:40px;height:40px;border-radius:12px;background:#f3e8ff;color:#7e22ce;font-weight:900}
.ssp-text{color:#0f172a;font-size:18px;font-weight:800;line-height:1.45}
.ssp-meaning{margin-top:6px;color:#64748b;font-size:13px;line-height:1.5}
.ssp-media{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.ssp-audio{min-height:38px}
.ssp-image{width:74px;height:74px;object-fit:cover;border:1px solid #e5e7eb;border-radius:12px;background:#f8fafc}
.ssp-empty{padding:55px 20px;border:1px dashed #cbd5e1;border-radius:16px;background:#fff;text-align:center;color:#64748b}
@media(max-width:720px){
    .ssp-head{flex-direction:column}
    .ssp-card{grid-template-columns:42px minmax(0,1fr)}
    .ssp-media{grid-column:1/-1}
}
</style>

<div class="ssp-page">
    <div class="ssp-head">
        <div>
            <span class="ssp-kicker">Sentence Sets</span>
            <h2 class="ssp-title">
                <?= htmlspecialchars((string)$set['title'], ENT_QUOTES, 'UTF-8') ?>
            </h2>
            <p class="ssp-subtitle">Preview the sentences in their saved order.</p>
        </div>

        <div class="ssp-actions">
            <a
                class="button button-secondary"
                href="index.php"
            >
                ← Sentence Sets
            </a>

            <?php if ($canManageSet): ?>
            <a class="button button-secondary" href="edit.php?id=<?= (int)$setId ?>">Edit</a>

            <a
                class="button button-primary"
                href="detail.php?id=<?= (int)$setId ?>"
            >
                Manage
            </a>
            <?php endif; ?>
        </div>
    </div>

    <div class="ssp-summary">
        <span class="ssp-pill">
            <?= count($sentences) ?> sentence(s)
        </span>

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

    <?php if ((string)$set['description'] !== ''): ?>
        <div class="ssp-description">
            <?= nl2br(htmlspecialchars(
                (string)$set['description'],
                ENT_QUOTES,
                'UTF-8'
            )) ?>
        </div>
    <?php endif; ?>

    <?php if ($sentences === []): ?>
        <div class="ssp-empty">
            This Sentence Set does not contain any sentences yet.
        </div>
    <?php else: ?>
        <div class="ssp-list">
            <?php foreach ($sentences as $index => $sentence): ?>
                <article class="ssp-card">
                    <div class="ssp-number"><?= $index + 1 ?></div>

                    <div>
                        <div class="ssp-text">
                            <?= htmlspecialchars(
                                (string)$sentence['sentence_text'],
                                ENT_QUOTES,
                                'UTF-8'
                            ) ?>
                        </div>

                        <?php if ((string)$sentence['vietnamese_meaning'] !== ''): ?>
                            <div class="ssp-meaning">
                                <?= htmlspecialchars(
                                    (string)$sentence['vietnamese_meaning'],
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <?php if (
                        (string)$sentence['audio_value'] !== ''
                        || (string)$sentence['image_value'] !== ''
                    ): ?>
                        <div class="ssp-media">
                            <?php if ((string)$sentence['image_value'] !== ''): ?>
                                <img
                                    class="ssp-image"
                                    src="<?= htmlspecialchars(
                                        (string)$sentence['image_value'],
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>"
                                    alt=""
                                >
                            <?php endif; ?>

                            <?php if ((string)$sentence['audio_value'] !== ''): ?>
                                <audio
                                    class="ssp-audio"
                                    controls
                                    preload="none"
                                    src="<?= htmlspecialchars(
                                        (string)$sentence['audio_value'],
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>"
                                ></audio>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </article>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

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