<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Sentence Library V2
 * File: teacher/sentence-library/detail.php
 *
 * Create / Edit one shared sentence.
 */

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 = 'Sentence Library';
$pageSubtitle = 'Create and edit reusable sentences';
$activeTeacherNav = 'content';

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

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

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

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

    return null;
}

function sldRedirect(string $message, string $type = 'success'): never
{
    $_SESSION['sentence_library_message'] = $message;
    $_SESSION['sentence_library_message_type'] = $type;

    header('Location: index.php');
    exit;
}

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

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

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

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

function sldUploadFile(
    array $file,
    string $targetFolder,
    array $allowedExtensions,
    int $maxBytes
): string {
    if (
        !isset($file['error'])
        || (int)$file['error'] === UPLOAD_ERR_NO_FILE
    ) {
        return '';
    }

    if ((int)$file['error'] !== UPLOAD_ERR_OK) {
        throw new RuntimeException('Upload failed.');
    }

    if ((int)$file['size'] > $maxBytes) {
        throw new RuntimeException('Uploaded file is too large.');
    }

    $extension = strtolower(
        pathinfo((string)$file['name'], PATHINFO_EXTENSION)
    );

    if (!in_array($extension, $allowedExtensions, true)) {
        throw new RuntimeException('Unsupported file type.');
    }

    $root = dirname(__DIR__, 2);
    $relativeFolder = trim($targetFolder, '/');
    $absoluteFolder = $root . '/' . $relativeFolder;

    if (
        !is_dir($absoluteFolder)
        && !mkdir($absoluteFolder, 0775, true)
        && !is_dir($absoluteFolder)
    ) {
        throw new RuntimeException('Could not create upload folder.');
    }

    $filename = date('Ymd_His')
        . '_'
        . bin2hex(random_bytes(5))
        . '.'
        . $extension;

    $absolutePath = $absoluteFolder . '/' . $filename;

    if (!move_uploaded_file((string)$file['tmp_name'], $absolutePath)) {
        throw new RuntimeException('Could not save uploaded file.');
    }

    return $relativeFolder . '/' . $filename;
}

if (!sldTableExists($pdo, 'sentences')) {
    http_response_code(500);
    exit('Missing required table: sentences');
}

$columns = sldColumns($pdo, 'sentences');
$ownerColumn = isset($columns['created_by_teacher_id']) ? 'created_by_teacher_id' : null;

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

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

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

$imageColumn = sldFirstColumn(
    $columns,
    ['image_path', 'image']
);

$audioColumn = sldFirstColumn(
    $columns,
    ['audio_us_path', 'audio_path', 'audio']
);

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

$difficultyColumn = sldFirstColumn(
    $columns,
    ['difficulty', 'level']
);

$notesColumn = sldFirstColumn(
    $columns,
    ['notes', 'note', 'teacher_note']
);

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

$id = max(0, (int)($_GET['id'] ?? $_POST['id'] ?? 0));
$isEdit = $id > 0;

$form = [
    'sentence_text' => '',
    'vietnamese_meaning' => '',
    'ipa' => '',
    'image_path' => '',
    'audio_path' => '',
    'status' => 'active',
    'difficulty' => '',
    'notes' => '',
];

$error = '';

if ($isEdit) {
    $selects = [
        'id',
        "`{$textColumn}` AS sentence_text",
        $meaningColumn !== null
            ? "`{$meaningColumn}` AS vietnamese_meaning"
            : "'' AS vietnamese_meaning",
        $ipaColumn !== null
            ? "`{$ipaColumn}` AS ipa"
            : "'' AS ipa",
        $imageColumn !== null
            ? "`{$imageColumn}` AS image_path"
            : "'' AS image_path",
        $audioColumn !== null
            ? "`{$audioColumn}` AS audio_path"
            : "'' AS audio_path",
        $statusColumn !== null
            ? "`{$statusColumn}` AS status"
            : "'active' AS status",
        $difficultyColumn !== null
            ? "`{$difficultyColumn}` AS difficulty"
            : "'' AS difficulty",
        $notesColumn !== null
            ? "`{$notesColumn}` AS notes"
            : "'' AS notes",
    ];

    $stmt = $pdo->prepare(
        'SELECT '
        . implode(', ', $selects)
        . ' FROM sentences WHERE id = ? LIMIT 1'
    );
    $stmt->execute([$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        sldRedirect('Sentence not found.', 'error');
    }
    if (!$isAdmin && $ownerColumn !== null) {
        $own = $pdo->prepare('SELECT created_by_teacher_id FROM sentences WHERE id = ? LIMIT 1');
        $own->execute([$id]);
        $owner = $own->fetchColumn();
        if ($owner === null || (int)$owner !== $currentUserId) { sldRedirect('Bạn không có quyền sửa câu này.', 'error'); }
    }

    $form = [
        'sentence_text' => (string)$row['sentence_text'],
        'vietnamese_meaning' => (string)$row['vietnamese_meaning'],
        'ipa' => (string)$row['ipa'],
        'image_path' => (string)$row['image_path'],
        'audio_path' => (string)$row['audio_path'],
        'status' => (string)$row['status'],
        'difficulty' => (string)$row['difficulty'],
        'notes' => (string)$row['notes'],
    ];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sentenceText = trim((string)($_POST['sentence_text'] ?? ''));
    $meaning = trim((string)($_POST['vietnamese_meaning'] ?? ''));
    $ipa = trim((string)($_POST['ipa'] ?? ''));
    $status = in_array(
        (string)($_POST['status'] ?? 'active'),
        ['active', 'inactive'],
        true
    )
        ? (string)$_POST['status']
        : 'active';
    $difficulty = trim((string)($_POST['difficulty'] ?? ''));
    $notes = trim((string)($_POST['notes'] ?? ''));

    $form['sentence_text'] = $sentenceText;
    $form['vietnamese_meaning'] = $meaning;
    $form['ipa'] = $ipa;
    $form['status'] = $status;
    $form['difficulty'] = $difficulty;
    $form['notes'] = $notes;

    if ($sentenceText === '') {
        $error = 'Please enter a sentence.';
    } else {
        $duplicateSql =
            "SELECT id
             FROM sentences
             WHERE LOWER(TRIM(`{$textColumn}`)) = LOWER(TRIM(?))";

        $duplicateParams = [$sentenceText];

        if ($isEdit) {
            $duplicateSql .= ' AND id <> ?';
            $duplicateParams[] = $id;
        }

        $duplicateSql .= ' LIMIT 1';

        $duplicateStmt = $pdo->prepare($duplicateSql);
        $duplicateStmt->execute($duplicateParams);

        if ($duplicateStmt->fetchColumn()) {
            $error = 'This sentence already exists.';
        }
    }

    if ($error === '') {
        try {
            $newImagePath = '';
            $newAudioPath = '';

            if ($imageColumn !== null && isset($_FILES['image_file'])) {
                $newImagePath = sldUploadFile(
                    $_FILES['image_file'],
                    'uploads/sentences',
                    ['jpg', 'jpeg', 'png', 'webp', 'gif'],
                    5 * 1024 * 1024
                );
            }

            if ($audioColumn !== null && isset($_FILES['audio_file'])) {
                $newAudioPath = sldUploadFile(
                    $_FILES['audio_file'],
                    'uploads/sentence-audio',
                    ['mp3', 'wav', 'ogg', 'm4a'],
                    12 * 1024 * 1024
                );
            }

            $imagePath = $newImagePath !== ''
                ? $newImagePath
                : trim((string)($_POST['existing_image_path'] ?? ''));

            $audioPath = $newAudioPath !== ''
                ? $newAudioPath
                : trim((string)($_POST['existing_audio_path'] ?? ''));

            if (isset($_POST['remove_image'])) {
                $imagePath = '';
            }

            if (isset($_POST['remove_audio'])) {
                $audioPath = '';
            }

            $pdo->beginTransaction();

            if ($isEdit) {
                $updates = ["`{$textColumn}` = ?"];
                $params = [$sentenceText];

                if ($meaningColumn !== null) {
                    $updates[] = "`{$meaningColumn}` = ?";
                    $params[] = $meaning !== '' ? $meaning : null;
                }

                if ($ipaColumn !== null) {
                    $updates[] = "`{$ipaColumn}` = ?";
                    $params[] = $ipa !== '' ? $ipa : null;
                }

                if ($imageColumn !== null) {
                    $updates[] = "`{$imageColumn}` = ?";
                    $params[] = $imagePath !== '' ? $imagePath : null;
                }

                if ($audioColumn !== null) {
                    $updates[] = "`{$audioColumn}` = ?";
                    $params[] = $audioPath !== '' ? $audioPath : null;
                }

                if ($statusColumn !== null) {
                    $updates[] = "`{$statusColumn}` = ?";
                    $params[] = $status;
                }

                if ($difficultyColumn !== null) {
                    $updates[] = "`{$difficultyColumn}` = ?";
                    $params[] = $difficulty !== '' ? $difficulty : null;
                }

                if ($notesColumn !== null) {
                    $updates[] = "`{$notesColumn}` = ?";
                    $params[] = $notes !== '' ? $notes : null;
                }

                if (isset($columns['updated_at'])) {
                    $updates[] = 'updated_at = NOW()';
                }

                $params[] = $id;

                $updateStmt = $pdo->prepare(
                    'UPDATE sentences SET '
                    . implode(', ', $updates)
                    . ' WHERE id = ?'
                );
                $updateStmt->execute($params);
            } else {
                $fields = ["`{$textColumn}`"];
                $placeholders = ['?'];
                $params = [$sentenceText];

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

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

                if ($imageColumn !== null) {
                    $fields[] = "`{$imageColumn}`";
                    $placeholders[] = '?';
                    $params[] = $imagePath !== '' ? $imagePath : null;
                }

                if ($audioColumn !== null) {
                    $fields[] = "`{$audioColumn}`";
                    $placeholders[] = '?';
                    $params[] = $audioPath !== '' ? $audioPath : null;
                }

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

                if ($difficultyColumn !== null) {
                    $fields[] = "`{$difficultyColumn}`";
                    $placeholders[] = '?';
                    $params[] = $difficulty !== '' ? $difficulty : null;
                }

                if ($notesColumn !== null) {
                    $fields[] = "`{$notesColumn}`";
                    $placeholders[] = '?';
                    $params[] = $notes !== '' ? $notes : null;
                }

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

                $insertStmt = $pdo->prepare(
                    'INSERT INTO sentences ('
                    . implode(', ', $fields)
                    . ') VALUES ('
                    . implode(', ', $placeholders)
                    . ')'
                );
                $insertStmt->execute($params);
            }

            $pdo->commit();

            sldRedirect(
                $isEdit
                    ? 'Sentence updated successfully.'
                    : 'Sentence created successfully.'
            );
        } catch (Throwable $exception) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }

            $error = 'Could not save this sentence.';
        }
    }
}

ob_start();
?>

<style>
.sld-page{display:grid;gap:18px}
.sld-head{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}
.sld-kicker{display:block;color:#7c3aed;font-size:12px;font-weight:850;letter-spacing:.09em;text-transform:uppercase}
.sld-head h2{margin:4px 0 0;color:#0f172a;font-size:28px}
.sld-subtitle{margin:7px 0 0;color:#64748b;font-size:14px}
.sld-card{padding:20px;border:1px solid #e5e7eb;border-radius:18px;background:#fff}
.sld-error{padding:12px 15px;border:1px solid #fecaca;border-radius:12px;background:#fef2f2;color:#991b1b;font-weight:700}
.sld-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}
.sld-field{display:grid;gap:7px}
.sld-full{grid-column:1/-1}
.sld-field span{color:#334155;font-size:13px;font-weight:750}
.sld-input,.sld-select,.sld-textarea{width:100%;min-height:44px;padding:0 12px;border:1px solid #dbe2ea;border-radius:10px;background:#fff;color:#0f172a;font:inherit}
.sld-textarea{min-height:96px;padding-top:10px;resize:vertical}
.sld-help{color:#64748b;font-size:12px;line-height:1.45}
.sld-media-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px;margin-top:16px}
.sld-media{padding:16px;border:1px solid #e5e7eb;border-radius:14px;background:#f8fafc}
.sld-media h3{margin:0 0 12px;color:#0f172a;font-size:15px}
.sld-preview{height:180px;display:grid;place-items:center;overflow:hidden;margin-bottom:12px;border:1px dashed #cbd5e1;border-radius:12px;background:#fff;color:#94a3b8;font-size:42px}
.sld-preview img{width:100%;height:100%;object-fit:contain}
.sld-audio-row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.sld-actions{display:flex;justify-content:flex-end;gap:9px;margin-top:18px}
@media(max-width:760px){
  .sld-head{flex-direction:column}
  .sld-grid,.sld-media-grid{grid-template-columns:1fr}
  .sld-full{grid-column:auto}
}
</style>

<div class="sld-page">
    <div class="sld-head">
        <div>
            <span class="sld-kicker">Sentence Library</span>
            <h2><?= $isEdit ? 'Edit Sentence' : 'Add Sentence' ?></h2>
            <p class="sld-subtitle">
                Create one reusable sentence for Speaking activities.
            </p>
        </div>

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

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

    <form method="post" enctype="multipart/form-data" class="sld-card">
        <input type="hidden" name="id" value="<?= (int)$id ?>">
        <input
            type="hidden"
            name="existing_image_path"
            value="<?= htmlspecialchars($form['image_path'], ENT_QUOTES, 'UTF-8') ?>"
        >
        <input
            type="hidden"
            name="existing_audio_path"
            value="<?= htmlspecialchars($form['audio_path'], ENT_QUOTES, 'UTF-8') ?>"
        >

        <div class="sld-grid">
            <label class="sld-field sld-full">
                <span>Sentence *</span>
                <input
                    class="sld-input"
                    type="text"
                    name="sentence_text"
                    maxlength="500"
                    required
                    value="<?= htmlspecialchars($form['sentence_text'], ENT_QUOTES, 'UTF-8') ?>"
                    placeholder="Example: This is a bike."
                >
            </label>

            <?php if ($meaningColumn !== null): ?>
                <label class="sld-field">
                    <span>Vietnamese meaning</span>
                    <input
                        class="sld-input"
                        type="text"
                        name="vietnamese_meaning"
                        maxlength="500"
                        value="<?= htmlspecialchars($form['vietnamese_meaning'], ENT_QUOTES, 'UTF-8') ?>"
                        placeholder="Đây là một chiếc xe đạp."
                    >
                </label>
            <?php endif; ?>

            <?php if ($ipaColumn !== null): ?>
                <label class="sld-field">
                    <span>IPA</span>
                    <input
                        class="sld-input"
                        type="text"
                        name="ipa"
                        maxlength="500"
                        value="<?= htmlspecialchars($form['ipa'], ENT_QUOTES, 'UTF-8') ?>"
                        placeholder="/ðɪs ɪz ə baɪk/"
                    >
                </label>
            <?php endif; ?>

            <?php if ($statusColumn !== null): ?>
                <label class="sld-field">
                    <span>Status</span>
                    <select class="sld-select" name="status">
                        <option value="active" <?= $form['status'] === 'active' ? 'selected' : '' ?>>
                            Active
                        </option>
                        <option value="inactive" <?= $form['status'] === 'inactive' ? 'selected' : '' ?>>
                            Inactive
                        </option>
                    </select>
                </label>
            <?php endif; ?>

            <?php if ($difficultyColumn !== null): ?>
                <label class="sld-field">
                    <span>Difficulty</span>
                    <input
                        class="sld-input"
                        type="text"
                        name="difficulty"
                        maxlength="100"
                        value="<?= htmlspecialchars($form['difficulty'], ENT_QUOTES, 'UTF-8') ?>"
                        placeholder="Example: easy"
                    >
                </label>
            <?php endif; ?>

            <?php if ($notesColumn !== null): ?>
                <label class="sld-field sld-full">
                    <span>Teacher notes</span>
                    <textarea
                        class="sld-textarea"
                        name="notes"
                        placeholder="Optional notes for teachers."
                    ><?= htmlspecialchars($form['notes'], ENT_QUOTES, 'UTF-8') ?></textarea>
                </label>
            <?php endif; ?>
        </div>

        <div class="sld-media-grid">
            <?php if ($imageColumn !== null): ?>
                <section class="sld-media">
                    <h3>Sentence image</h3>

                    <div class="sld-preview" id="imagePreview">
                        <?php if ($form['image_path'] !== ''): ?>
                            <img
                                src="<?= htmlspecialchars(
                                    sldAssetUrl($form['image_path']),
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>"
                                alt=""
                            >
                        <?php else: ?>
                            🖼️
                        <?php endif; ?>
                    </div>

                    <input
                        class="sld-input"
                        type="file"
                        name="image_file"
                        id="imageFile"
                        accept=".jpg,.jpeg,.png,.webp,.gif"
                    >

                    <?php if ($form['image_path'] !== ''): ?>
                        <label class="sld-help">
                            <input type="checkbox" name="remove_image" value="1">
                            Remove current image
                        </label>
                    <?php else: ?>
                        <div class="sld-help">
                            Optional. Sentence Library can also reuse an image from Word Library.
                        </div>
                    <?php endif; ?>
                </section>
            <?php endif; ?>

            <?php if ($audioColumn !== null): ?>
                <section class="sld-media">
                    <h3>Sentence audio</h3>

                    <div class="sld-audio-row">
                        <button
                            class="button button-secondary"
                            type="button"
                            id="ttsPreview"
                        >
                            🔊 Preview TTS
                        </button>

                        <?php if ($form['audio_path'] !== ''): ?>
                            <button
                                class="button button-secondary"
                                type="button"
                                id="savedAudioPreview"
                                data-audio="<?= htmlspecialchars(
                                    sldAssetUrl($form['audio_path']),
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>"
                            >
                                ▶ Saved audio
                            </button>
                        <?php endif; ?>
                    </div>

                    <div style="margin-top:12px">
                        <input
                            class="sld-input"
                            type="file"
                            name="audio_file"
                            accept=".mp3,.wav,.ogg,.m4a"
                        >
                    </div>

                    <?php if ($form['audio_path'] !== ''): ?>
                        <label class="sld-help">
                            <input type="checkbox" name="remove_audio" value="1">
                            Remove current audio
                        </label>
                    <?php else: ?>
                        <div class="sld-help">
                            Optional. Browser TTS will be used when no audio file is uploaded.
                        </div>
                    <?php endif; ?>
                </section>
            <?php endif; ?>
        </div>

        <div class="sld-actions">
            <a class="button button-secondary" href="index.php">Cancel</a>
            <button class="button button-primary" type="submit">
                <?= $isEdit ? 'Save Changes' : 'Add Sentence' ?>
            </button>
        </div>
    </form>
</div>

<script>
(function () {
    var imageFile = document.getElementById('imageFile');
    var imagePreview = document.getElementById('imagePreview');
    var ttsPreview = document.getElementById('ttsPreview');
    var savedAudioPreview = document.getElementById('savedAudioPreview');
    var sentenceInput = document.querySelector('[name="sentence_text"]');
    var activeAudio = null;

    function stopAudio() {
        if (activeAudio) {
            activeAudio.pause();
            activeAudio.currentTime = 0;
            activeAudio = null;
        }

        if ('speechSynthesis' in window) {
            window.speechSynthesis.cancel();
        }
    }

    if (imageFile && imagePreview) {
        imageFile.addEventListener('change', function () {
            var file = imageFile.files && imageFile.files[0];

            if (!file) {
                return;
            }

            var reader = new FileReader();

            reader.addEventListener('load', function () {
                imagePreview.innerHTML = '';

                var image = document.createElement('img');
                image.src = String(reader.result || '');
                image.alt = '';

                imagePreview.appendChild(image);
            });

            reader.readAsDataURL(file);
        });
    }

    if (ttsPreview) {
        ttsPreview.addEventListener('click', function () {
            var text = sentenceInput
                ? String(sentenceInput.value || '').trim()
                : '';

            if (!text || !('speechSynthesis' in window)) {
                return;
            }

            stopAudio();

            var utterance = new SpeechSynthesisUtterance(text);
            utterance.lang = 'en-US';
            utterance.rate = 0.82;
            utterance.pitch = 1;

            var voices = window.speechSynthesis.getVoices();

            var preferredVoice = voices.find(function (voice) {
                return /^en-US$/i.test(voice.lang);
            }) || voices.find(function (voice) {
                return /^en/i.test(voice.lang);
            });

            if (preferredVoice) {
                utterance.voice = preferredVoice;
            }

            window.speechSynthesis.speak(utterance);
        });
    }

    if (savedAudioPreview) {
        savedAudioPreview.addEventListener('click', function () {
            var source = String(
                savedAudioPreview.getAttribute('data-audio') || ''
            );

            if (!source) {
                return;
            }

            stopAudio();

            activeAudio = new Audio(source);
            activeAudio.play().catch(function () {});
        });
    }

    if ('speechSynthesis' in window) {
        window.speechSynthesis.getVoices();
        window.speechSynthesis.onvoiceschanged = function () {
            window.speechSynthesis.getVoices();
        };
    }
})();
</script>

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