<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Sentence Library Import
 * File: teacher/sentence-library/import.php
 *
 * Part 5:
 * - Download CSV template
 * - Import CSV or XLSX
 * - Preview before import
 * - Skip duplicate sentences
 * - Import English sentence, Vietnamese meaning, IPA and status
 */

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 = 'Import Sentences';
$pageSubtitle = 'Import reusable speaking sentences from Excel or CSV';
$activeTeacherNav = 'content';

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

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

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

    return null;
}

function sliNormalizeHeader(string $header): string
{
    $header = preg_replace('/^ï»¿/', '', $header) ?? $header;
    $header = mb_strtolower(trim($header));
    $header = str_replace(
        [' ', '-', '.', '/', '\\'],
        '_',
        $header
    );
    $header = preg_replace('/_+/u', '_', $header) ?? $header;

    $aliases = [
        'sentence' => 'sentence_text',
        'english' => 'sentence_text',
        'english_sentence' => 'sentence_text',
        'sentence_text' => 'sentence_text',
        'text' => 'sentence_text',

        'vietnamese' => 'vietnamese_meaning',
        'meaning' => 'vietnamese_meaning',
        'meaning_vi' => 'vietnamese_meaning',
        'vietnamese_meaning' => 'vietnamese_meaning',
        'translation' => 'vietnamese_meaning',

        'phonetic' => 'ipa',
        'ipa' => 'ipa',

        'status' => 'status',
    ];

    return $aliases[$header] ?? $header;
}

function sliCleanCell(mixed $value): string
{
    $value = trim((string)$value);
    $value = preg_replace('/\s+/u', ' ', $value) ?? $value;
    return trim($value);
}

function sliCleanStatus(string $value): string
{
    $value = mb_strtolower(trim($value));

    return in_array($value, ['inactive', '0', 'no', 'false'], true)
        ? 'inactive'
        : 'active';
}

function sliReadCsv(string $path): array
{
    $handle = fopen($path, 'rb');

    if ($handle === false) {
        throw new RuntimeException('Could not open the CSV file.');
    }

    try {
        $firstBytes = fread($handle, 3);
        $hasBom = $firstBytes === "\xEF\xBB\xBF";

        if (!$hasBom) {
            rewind($handle);
        }

        $sample = fgets($handle);
        $delimiter = ',';

        if ($sample !== false) {
            $delimiter = substr_count($sample, ';') > substr_count($sample, ',')
                ? ';'
                : ',';
        }

        rewind($handle);

        if ($hasBom) {
            fread($handle, 3);
        }

        $rows = [];
        $maxRows = 5001;

        while (($row = fgetcsv($handle, 0, $delimiter)) !== false) {
            if ($row === [null] || $row === []) {
                continue;
            }

            $rows[] = $row;

            if (count($rows) > $maxRows) {
                throw new RuntimeException(
                    'The spreadsheet may contain at most 5,000 data rows.'
                );
            }
        }

        return $rows;
    } finally {
        fclose($handle);
    }
}

function sliColumnLettersToIndex(string $letters): int
{
    $letters = strtoupper($letters);
    $index = 0;

    foreach (str_split($letters) as $character) {
        $index = ($index * 26) + (ord($character) - 64);
    }

    return $index - 1;
}

function sliReadXlsx(string $path): array
{
    if (!class_exists(ZipArchive::class)) {
        throw new RuntimeException(
            'PHP ZipArchive is required to read XLSX files. CSV import is still available.'
        );
    }

    $zip = new ZipArchive();

    if ($zip->open($path) !== true) {
        throw new RuntimeException('Could not open the XLSX file.');
    }

    try {
        $sharedStrings = [];
        $sharedXml = $zip->getFromName('xl/sharedStrings.xml');

        if (is_string($sharedXml) && $sharedXml !== '') {
            $xml = simplexml_load_string($sharedXml);

            if ($xml !== false) {
                $namespaces = $xml->getNamespaces(true);
                $main = isset($namespaces[''])
                    ? $xml->children($namespaces[''])
                    : $xml;

                foreach ($main->si as $item) {
                    $parts = [];

                    if (isset($item->t)) {
                        $parts[] = (string)$item->t;
                    }

                    foreach ($item->r as $run) {
                        $parts[] = (string)$run->t;
                    }

                    $sharedStrings[] = implode('', $parts);
                }
            }
        }

        $sheetXml = $zip->getFromName('xl/worksheets/sheet1.xml');

        if (!is_string($sheetXml) || $sheetXml === '') {
            throw new RuntimeException('The XLSX file does not contain Sheet1.');
        }

        $sheet = simplexml_load_string($sheetXml);

        if ($sheet === false) {
            throw new RuntimeException('Could not read Sheet1 from the XLSX file.');
        }

        $namespaces = $sheet->getNamespaces(true);
        $main = isset($namespaces[''])
            ? $sheet->children($namespaces[''])
            : $sheet;

        if (!isset($main->sheetData)) {
            throw new RuntimeException('Could not read Sheet1 from the XLSX file.');
        }

        $rows = [];
        $maxRows = 5001;

        foreach ($main->sheetData->row as $rowNode) {
            $row = [];

            foreach ($rowNode->c as $cell) {
                $reference = (string)$cell['r'];
                preg_match('/([A-Z]+)\d+/i', $reference, $matches);
                $columnIndex = sliColumnLettersToIndex($matches[1] ?? 'A');

                $type = (string)$cell['t'];
                $value = '';

                if ($type === 'inlineStr' && isset($cell->is)) {
                    $parts = [];

                    if (isset($cell->is->t)) {
                        $parts[] = (string)$cell->is->t;
                    }

                    foreach ($cell->is->r as $run) {
                        $parts[] = (string)$run->t;
                    }

                    $value = implode('', $parts);
                } elseif (isset($cell->v)) {
                    $raw = (string)$cell->v;

                    if ($type === 's') {
                        $value = $sharedStrings[(int)$raw] ?? '';
                    } elseif ($type === 'b') {
                        $value = $raw === '1' ? 'true' : 'false';
                    } else {
                        $value = $raw;
                    }
                }

                $row[$columnIndex] = $value;
            }

            if ($row === []) {
                continue;
            }

            $maxIndex = max(array_keys($row));

            for ($index = 0; $index <= $maxIndex; $index++) {
                $row[$index] = $row[$index] ?? '';
            }

            ksort($row);
            $rows[] = array_values($row);

            if (count($rows) > $maxRows) {
                throw new RuntimeException(
                    'The spreadsheet may contain at most 5,000 data rows.'
                );
            }
        }

        return $rows;
    } finally {
        $zip->close();
    }
}

function sliReadSpreadsheet(string $path, string $extension): array
{
    return match ($extension) {
        'csv' => sliReadCsv($path),
        'xlsx' => sliReadXlsx($path),
        default => throw new RuntimeException('Only CSV and XLSX files are supported.'),
    };
}

function sliMapRows(array $rawRows): array
{
    if ($rawRows === []) {
        throw new RuntimeException('The uploaded file is empty.');
    }

    $headers = array_map(
        static fn(mixed $value): string => sliNormalizeHeader((string)$value),
        array_shift($rawRows)
    );

    if (!in_array('sentence_text', $headers, true)) {
        throw new RuntimeException(
            'The file must contain a sentence_text or sentence column.'
        );
    }

    $rows = [];
    $seen = [];

    foreach ($rawRows as $rowNumber => $rawRow) {
        $record = [
            'row_number' => $rowNumber + 2,
            'sentence_text' => '',
            'vietnamese_meaning' => '',
            'ipa' => '',
            'status' => 'active',
        ];

        foreach ($headers as $index => $header) {
            if (!array_key_exists($header, $record)) {
                continue;
            }

            $record[$header] = sliCleanCell($rawRow[$index] ?? '');
        }

        $record['status'] = sliCleanStatus($record['status']);

        if ($record['sentence_text'] === '') {
            continue;
        }

        $duplicateKey = mb_strtolower(trim($record['sentence_text']));

        if (isset($seen[$duplicateKey])) {
            continue;
        }

        $seen[$duplicateKey] = true;
        $rows[] = $record;
    }

    if ($rows === []) {
        throw new RuntimeException('No valid sentences were found in the file.');
    }

    return $rows;
}

function sliAnnotateDuplicateRows(
    PDO $pdo,
    array $rows,
    string $textColumn
): array {
    if ($rows === []) {
        return [];
    }

    $checkDuplicate = $pdo->prepare(
        "SELECT id
         FROM sentences
         WHERE LOWER(TRIM(`{$textColumn}`)) = LOWER(TRIM(?))
         LIMIT 1"
    );

    $seenInFile = [];

    foreach ($rows as &$row) {
        $sentenceText = sliCleanCell($row['sentence_text'] ?? '');
        $normalized = mb_strtolower(trim($sentenceText));

        $row['duplicate_type'] = '';
        $row['duplicate_label'] = 'New';
        $row['will_import'] = true;

        if ($normalized === '') {
            $row['duplicate_type'] = 'empty';
            $row['duplicate_label'] = 'Empty';
            $row['will_import'] = false;
            continue;
        }

        if (isset($seenInFile[$normalized])) {
            $row['duplicate_type'] = 'file';
            $row['duplicate_label'] = 'Duplicate in file';
            $row['will_import'] = false;
            continue;
        }

        $seenInFile[$normalized] = true;

        $checkDuplicate->execute([$sentenceText]);

        if ($checkDuplicate->fetchColumn()) {
            $row['duplicate_type'] = 'library';
            $row['duplicate_label'] = 'Already in Library';
            $row['will_import'] = false;
        }
    }
    unset($row);

    return $rows;
}

function sliStorePreviewRows(array $rows): string
{
    $token = bin2hex(random_bytes(16));

    $_SESSION['sentence_import_preview'] = [
        'token' => $token,
        'rows' => $rows,
        'created_at' => time(),
    ];

    return $token;
}

function sliLoadPreviewRows(string $token): array
{
    $stored = $_SESSION['sentence_import_preview'] ?? null;

    if (
        !is_array($stored)
        || !hash_equals((string)($stored['token'] ?? ''), $token)
        || time() - (int)($stored['created_at'] ?? 0) > 1800
        || !is_array($stored['rows'] ?? null)
    ) {
        throw new RuntimeException(
            'The import preview has expired. Please upload the file again.'
        );
    }

    return $stored['rows'];
}

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

$columns = sliColumns($pdo, 'sentences');

$textColumn = sliFirstColumn(
    $columns,
    ['sentence_text', 'sentence', 'text', 'content']
);

$meaningColumn = sliFirstColumn(
    $columns,
    ['vietnamese_meaning', 'meaning_vi', 'meaning']
);

$ipaColumn = sliFirstColumn(
    $columns,
    ['ipa', 'phonetic']
);

$statusColumn = isset($columns['status'])
    ? 'status'
    : null;
$ownerColumn = isset($columns['created_by_teacher_id']) ? 'created_by_teacher_id' : null;

if ($textColumn === null) {
    http_response_code(500);
    exit('The sentences table does not contain a sentence text column.');
}

if ((string)($_GET['download'] ?? '') === 'template') {
    $filename = 'sentence-library-template.csv';

    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');

    echo "\xEF\xBB\xBF";

    $output = fopen('php://output', 'wb');

    fputcsv(
        $output,
        ['sentence_text', 'vietnamese_meaning', 'ipa', 'status']
    );

    fputcsv(
        $output,
        ['This is a bike.', 'Đây là một chiếc xe đạp.', '/ðɪs ɪz ə baɪk/', 'active']
    );

    fputcsv(
        $output,
        ['I have a book.', 'Em có một quyển sách.', '/aɪ hæv ə bʊk/', 'active']
    );

    fclose($output);
    exit;
}

$error = '';
$success = '';
$previewRows = [];
$previewToken = '';

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

    if ($action === 'preview') {
        try {
            $file = $_FILES['import_file'] ?? [];
            $uploadError = (int)($file['error'] ?? UPLOAD_ERR_NO_FILE);

            if ($uploadError === UPLOAD_ERR_NO_FILE) {
                throw new RuntimeException('Please choose a CSV or XLSX file.');
            }

            if ($uploadError !== UPLOAD_ERR_OK) {
                throw new RuntimeException('The spreadsheet upload failed.');
            }

            $tmpPath = (string)($file['tmp_name'] ?? '');
            $originalName = (string)($file['name'] ?? '');
            $extension = mb_strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
            $size = (int)($file['size'] ?? 0);

            if ($size <= 0 || $size > 8 * 1024 * 1024) {
                throw new RuntimeException('The spreadsheet must not exceed 8 MB.');
            }

            if (!in_array($extension, ['csv', 'xlsx'], true)) {
                throw new RuntimeException('Only CSV and XLSX files are supported.');
            }

            $previewRows = sliMapRows(
                sliReadSpreadsheet($tmpPath, $extension)
            );

            $previewRows = sliAnnotateDuplicateRows(
                $pdo,
                $previewRows,
                $textColumn
            );

            $previewToken = sliStorePreviewRows($previewRows);
        } catch (Throwable $exception) {
            $error = $exception->getMessage();
        }
    }

    if ($action === 'import') {
        try {
            $token = trim((string)($_POST['preview_token'] ?? ''));
            $rows = sliLoadPreviewRows($token);

            $selectDuplicate = $pdo->prepare(
                "SELECT id
                 FROM sentences
                 WHERE LOWER(TRIM(`{$textColumn}`)) = LOWER(TRIM(?))
                 LIMIT 1"
            );

            $fields = ["`{$textColumn}`"];
            $placeholders = ['?'];

            if ($meaningColumn !== null) {
                $fields[] = "`{$meaningColumn}`";
                $placeholders[] = '?';
            }

            if ($ipaColumn !== null) {
                $fields[] = "`{$ipaColumn}`";
                $placeholders[] = '?';
            }

            if ($statusColumn !== null) {
                $fields[] = "`{$statusColumn}`";
                $placeholders[] = '?';
            }

            if ($ownerColumn !== null) { $fields[] = '`' . $ownerColumn . '`'; $placeholders[] = '?'; }

            $insert = $pdo->prepare(
                'INSERT INTO sentences ('
                . implode(', ', $fields)
                . ') VALUES ('
                . implode(', ', $placeholders)
                . ')'
            );

            $imported = 0;
            $skipped = 0;

            $pdo->beginTransaction();

            foreach ($rows as $row) {
                $sentenceText = sliCleanCell($row['sentence_text'] ?? '');

                if (
                    $sentenceText === ''
                    || array_key_exists('will_import', $row)
                        && !$row['will_import']
                ) {
                    $skipped++;
                    continue;
                }

                $selectDuplicate->execute([$sentenceText]);

                if ($selectDuplicate->fetchColumn()) {
                    $skipped++;
                    continue;
                }

                $params = [$sentenceText];

                if ($meaningColumn !== null) {
                    $meaning = sliCleanCell($row['vietnamese_meaning'] ?? '');
                    $params[] = $meaning !== '' ? $meaning : null;
                }

                if ($ipaColumn !== null) {
                    $ipa = sliCleanCell($row['ipa'] ?? '');
                    $params[] = $ipa !== '' ? $ipa : null;
                }

                if ($statusColumn !== null) {
                    $params[] = sliCleanStatus(
                        (string)($row['status'] ?? 'active')
                    );
                }

                if ($ownerColumn !== null) { $params[] = $isAdmin ? null : $currentUserId; }
                $insert->execute($params);
                $imported++;
            }

            $pdo->commit();

            unset($_SESSION['sentence_import_preview']);

            $success = "Imported {$imported} sentence(s). Skipped {$skipped} duplicate or empty row(s).";
        } catch (Throwable $exception) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }

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

$previewNewCount = 0;
$previewDuplicateCount = 0;

foreach ($previewRows as $previewRow) {
    if (!empty($previewRow['will_import'])) {
        $previewNewCount++;
    } else {
        $previewDuplicateCount++;
    }
}

ob_start();
?>

<style>
.sli-page{display:grid;gap:18px}
.sli-head{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}
.sli-kicker{display:block;color:#7c3aed;font-size:12px;font-weight:850;letter-spacing:.09em;text-transform:uppercase}
.sli-head h2{margin:4px 0 0;color:#0f172a;font-size:28px}
.sli-subtitle{margin:7px 0 0;color:#64748b;font-size:14px}
.sli-actions{display:flex;gap:9px;flex-wrap:wrap}
.sli-card{padding:20px;border:1px solid #e5e7eb;border-radius:18px;background:#fff}
.sli-card h3{margin:0;color:#0f172a;font-size:18px}
.sli-desc{margin:5px 0 16px;color:#64748b;font-size:13px;line-height:1.55}
.sli-upload{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:end}
.sli-field{display:grid;gap:7px}
.sli-field span{color:#334155;font-size:13px;font-weight:750}
.sli-input{width:100%;min-height:44px;padding:8px 12px;border:1px solid #dbe2ea;border-radius:10px;background:#fff;color:#0f172a;font:inherit}
.sli-message{padding:12px 15px;border-radius:12px;font-weight:700}
.sli-error{border:1px solid #fecaca;background:#fef2f2;color:#991b1b}
.sli-success{border:1px solid #bbf7d0;background:#ecfdf3;color:#166534}
.sli-help{display:grid;gap:8px;padding:14px;border:1px solid #dbeafe;border-radius:13px;background:#eff6ff;color:#1d4ed8;font-size:13px;line-height:1.55}
.sli-columns{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px}
.sli-column{padding:9px;border:1px solid #dbeafe;border-radius:9px;background:#fff;font-family:Consolas,monospace;font-size:12px}
.sli-table-wrap{overflow:auto;margin-top:15px;border:1px solid #e5e7eb;border-radius:14px}
.sli-table{width:100%;border-collapse:collapse}
.sli-table th{padding:11px 12px;background:#f8fafc;color:#64748b;font-size:11px;text-align:left;text-transform:uppercase;letter-spacing:.06em;white-space:nowrap}
.sli-table td{padding:12px;border-top:1px solid #edf0f3;color:#334155;vertical-align:top}
.sli-sentence{min-width:260px;color:#0f172a;font-weight:750;line-height:1.45}
.sli-status-badge{display:inline-flex;padding:5px 9px;border-radius:999px;font-size:11px;font-weight:800;white-space:nowrap}
.sli-new{background:#dcfce7;color:#166534}
.sli-duplicate{background:#fef3c7;color:#92400e}
.sli-row-duplicate{background:#fffbeb}
.sli-preview-summary{display:flex;gap:10px;flex-wrap:wrap;margin:10px 0 0}
.sli-preview-chip{display:inline-flex;padding:6px 10px;border-radius:999px;font-size:12px;font-weight:800}
.sli-footer{display:flex;justify-content:flex-end;gap:9px;margin-top:15px}
.sli-note{color:#64748b;font-size:12px;line-height:1.5}
@media(max-width:760px){
  .sli-head{flex-direction:column}
  .sli-upload{grid-template-columns:1fr}
  .sli-columns{grid-template-columns:1fr 1fr}
}
</style>

<div class="sli-page">
    <div class="sli-head">
        <div>
            <span class="sli-kicker">Sentence Library</span>
            <h2>Import Sentences</h2>
            <p class="sli-subtitle">
                Upload a CSV or XLSX file, review the rows, then import.
            </p>
        </div>

        <div class="sli-actions">
            <a class="button button-secondary" href="index.php">
                ← Sentence Library
            </a>
            <a class="button button-secondary" href="import.php?download=template">
                Download Template
            </a>
        </div>
    </div>

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

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

    <section class="sli-help">
        <strong>Supported columns</strong>
        <div class="sli-columns">
            <div class="sli-column">sentence_text</div>
            <div class="sli-column">vietnamese_meaning</div>
            <div class="sli-column">ipa</div>
            <div class="sli-column">status</div>
        </div>
        <span>
            Only <strong>sentence_text</strong> is required. Status defaults to
            <strong>active</strong>. Existing duplicate sentences are skipped.
        </span>
    </section>

    <section class="sli-card">
        <h3>1. Choose spreadsheet</h3>
        <p class="sli-desc">
            Maximum file size: 8 MB. The first row must contain column names.
        </p>

        <form method="post" enctype="multipart/form-data" class="sli-upload">
            <input type="hidden" name="action" value="preview">

            <label class="sli-field">
                <span>CSV or XLSX file</span>
                <input
                    class="sli-input"
                    type="file"
                    name="import_file"
                    accept=".csv,.xlsx,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                    required
                >
            </label>

            <button class="button button-primary" type="submit">
                Preview Import
            </button>
        </form>
    </section>

    <?php if ($previewRows !== []): ?>
        <section class="sli-card">
            <h3>2. Review <?= count($previewRows) ?> sentence(s)</h3>
            <p class="sli-desc">
                Duplicate sentences are marked before import and will be skipped automatically.
            </p>

            <div class="sli-preview-summary">
                <span class="sli-preview-chip sli-new">
                    <?= $previewNewCount ?> new
                </span>
                <span class="sli-preview-chip sli-duplicate">
                    <?= $previewDuplicateCount ?> duplicate / skipped
                </span>
            </div>

            <div class="sli-table-wrap">
                <table class="sli-table">
                    <thead>
                        <tr>
                            <th>Row</th>
                            <th>Sentence</th>
                            <th>Vietnamese</th>
                            <th>IPA</th>
                            <th>Status</th>
                            <th>Import Result</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($previewRows as $row): ?>
                            <tr class="<?= !empty($row['will_import']) ? '' : 'sli-row-duplicate' ?>">
                                <td><?= (int)$row['row_number'] ?></td>
                                <td>
                                    <div class="sli-sentence">
                                        <?= htmlspecialchars(
                                            (string)$row['sentence_text'],
                                            ENT_QUOTES,
                                            'UTF-8'
                                        ) ?>
                                    </div>
                                </td>
                                <td>
                                    <?= (string)$row['vietnamese_meaning'] !== ''
                                        ? htmlspecialchars(
                                            (string)$row['vietnamese_meaning'],
                                            ENT_QUOTES,
                                            'UTF-8'
                                        )
                                        : '—' ?>
                                </td>
                                <td>
                                    <?= (string)$row['ipa'] !== ''
                                        ? htmlspecialchars(
                                            (string)$row['ipa'],
                                            ENT_QUOTES,
                                            'UTF-8'
                                        )
                                        : '—' ?>
                                </td>
                                <td>
                                    <?= $row['status'] === 'inactive'
                                        ? 'Inactive'
                                        : 'Active' ?>
                                </td>
                                <td>
                                    <span class="sli-status-badge <?= !empty($row['will_import']) ? 'sli-new' : 'sli-duplicate' ?>">
                                        <?= htmlspecialchars(
                                            (string)($row['duplicate_label'] ?? 'New'),
                                            ENT_QUOTES,
                                            'UTF-8'
                                        ) ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <form method="post" class="sli-footer">
                <input type="hidden" name="action" value="import">
                <input
                    type="hidden"
                    name="preview_token"
                    value="<?= htmlspecialchars($previewToken, ENT_QUOTES, 'UTF-8') ?>"
                >

                <a class="button button-secondary" href="import.php">
                    Cancel
                </a>

                <button
                    class="button button-primary"
                    type="submit"
                    <?= $previewNewCount === 0 ? 'disabled' : '' ?>
                >
                    Import <?= $previewNewCount ?> New Sentence(s)
                </button>
            </form>
        </section>
    <?php endif; ?>

    <div class="sli-note">
        CSV is the most compatible format. UTF-8 CSV files with either comma
        or semicolon separators are supported. XLSX import requires the PHP
        <strong>ZipArchive</strong> extension enabled in Laragon. Maximum:
        5,000 data rows per import.
    </div>
</div>

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