<?php
declare(strict_types=1);
session_start();

$dataFile = __DIR__ . '/data/vocabulary.json';
$uploadDir = __DIR__ . '/uploads/vocabulary';

if (!is_dir(dirname($dataFile))) {
    mkdir(dirname($dataFile), 0775, true);
}
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0775, true);
}
if (!file_exists($dataFile)) {
    file_put_contents($dataFile, '[]');
}

function loadWords(string $file): array {
    $json = file_get_contents($file);
    $data = json_decode($json ?: '[]', true);
    return is_array($data) ? $data : [];
}

function saveWords(string $file, array $words): void {
    file_put_contents(
        $file,
        json_encode(array_values($words), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT),
        LOCK_EX
    );
}

function safeUpload(string $field, string $uploadDir, array $allowedExtensions): string {
    if (empty($_FILES[$field]['name']) || $_FILES[$field]['error'] !== UPLOAD_ERR_OK) {
        return '';
    }

    $extension = strtolower(pathinfo($_FILES[$field]['name'], PATHINFO_EXTENSION));
    if (!in_array($extension, $allowedExtensions, true)) {
        throw new RuntimeException('Định dạng file không được hỗ trợ.');
    }

    $filename = uniqid($field . '_', true) . '.' . $extension;
    $destination = $uploadDir . '/' . $filename;

    if (!move_uploaded_file($_FILES[$field]['tmp_name'], $destination)) {
        throw new RuntimeException('Không thể lưu file tải lên.');
    }

    return 'uploads/vocabulary/' . $filename;
}

$words = loadWords($dataFile);
$message = '';
$error = '';

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

        if ($action === 'delete') {
            $deleteId = (int) ($_POST['id'] ?? 0);
            $words = array_values(array_filter($words, fn($item) => (int)($item['id'] ?? 0) !== $deleteId));
            saveWords($dataFile, $words);
            $message = 'Đã xóa từ.';
        } else {
            $id = (int) ($_POST['id'] ?? 0);
            $old = null;

            foreach ($words as $item) {
                if ((int)($item['id'] ?? 0) === $id) {
                    $old = $item;
                    break;
                }
            }

            $imagePath = safeUpload('image_file', $uploadDir, ['jpg', 'jpeg', 'png', 'webp', 'gif', 'svg']);
            $audioPath = safeUpload('audio_file', $uploadDir, ['mp3', 'wav', 'ogg', 'm4a']);

            $record = [
                'id' => $id > 0 ? $id : (count($words) ? max(array_column($words, 'id')) + 1 : 1),
                'book' => trim($_POST['book'] ?? 'global-success'),
                'grade' => max(1, (int)($_POST['grade'] ?? 1)),
                'unit' => max(1, (int)($_POST['unit'] ?? 1)),
                'lesson' => max(1, (int)($_POST['lesson'] ?? 1)),
                'activity' => max(1, (int)($_POST['activity'] ?? 1)),
                'word' => trim($_POST['word'] ?? ''),
                'ipa' => trim($_POST['ipa'] ?? ''),
                'meaning' => trim($_POST['meaning'] ?? ''),
                'example' => trim($_POST['example'] ?? ''),
                'image' => $imagePath ?: trim($_POST['image_url'] ?? ($old['image'] ?? '')),
                'audio' => $audioPath ?: trim($_POST['audio_url'] ?? ($old['audio'] ?? '')),
                'sort_order' => max(1, (int)($_POST['sort_order'] ?? 1)),
            ];

            if ($record['word'] === '') {
                throw new RuntimeException('Vui lòng nhập từ tiếng Anh.');
            }

            $updated = false;
            foreach ($words as $index => $item) {
                if ((int)($item['id'] ?? 0) === $record['id']) {
                    $words[$index] = $record;
                    $updated = true;
                    break;
                }
            }
            if (!$updated) {
                $words[] = $record;
            }

            usort($words, fn($a, $b) =>
                [$a['book'], $a['grade'], $a['unit'], $a['lesson'], $a['activity'], $a['sort_order']]
                <=>
                [$b['book'], $b['grade'], $b['unit'], $b['lesson'], $b['activity'], $b['sort_order']]
            );

            saveWords($dataFile, $words);
            $message = $updated ? 'Đã cập nhật từ.' : 'Đã thêm từ mới.';
        }

        $words = loadWords($dataFile);
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$editId = (int)($_GET['edit'] ?? 0);
$editWord = null;
foreach ($words as $item) {
    if ((int)($item['id'] ?? 0) === $editId) {
        $editWord = $item;
        break;
    }
}

$filterBook = $_GET['book'] ?? 'global-success';
$filterGrade = (int)($_GET['grade'] ?? 1);
$filterUnit = (int)($_GET['unit'] ?? 1);
$filtered = array_values(array_filter($words, fn($item) =>
    ($item['book'] ?? '') === $filterBook
    && (int)($item['grade'] ?? 0) === $filterGrade
    && (int)($item['unit'] ?? 0) === $filterUnit
));
?>
<!doctype html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Teacher Vocabulary Studio</title>
<style>
*{box-sizing:border-box}body{margin:0;background:#f4f8fc;font-family:Arial,sans-serif;color:#17324d}
.wrap{max-width:1180px;margin:auto;padding:20px}.top{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:18px}
h1{margin:0;font-size:26px}.sub{color:#6b8194;margin-top:5px}.student-link{background:#174b72;color:#fff;text-decoration:none;padding:11px 15px;border-radius:12px;font-weight:700}
.grid{display:grid;grid-template-columns:380px 1fr;gap:18px}.panel{background:#fff;border:1px solid #deebf3;border-radius:18px;padding:18px;box-shadow:0 8px 24px rgba(24,72,105,.07)}
label{font-weight:700;font-size:13px;display:block;margin:11px 0 6px}input,select,textarea{width:100%;padding:11px;border:1px solid #cbdce8;border-radius:10px;font:inherit}
.row{display:grid;grid-template-columns:1fr 1fr;gap:10px}.actions{display:flex;gap:9px;margin-top:16px}.btn{border:0;border-radius:11px;padding:11px 15px;font-weight:700;cursor:pointer}
.primary{background:#1478b8;color:#fff}.secondary{background:#eaf3f9;color:#174b72}.danger{background:#ffe9e9;color:#a22}
.notice{padding:11px;border-radius:10px;margin-bottom:12px}.ok{background:#e8f8ef;color:#176a3a}.err{background:#fff0f0;color:#9b2525}
.filter{display:flex;gap:8px;align-items:end;margin-bottom:14px}.filter>div{flex:1}.filter button{height:42px}
.cards{display:grid;gap:10px}.word-card{display:grid;grid-template-columns:70px 1fr auto;gap:12px;align-items:center;border:1px solid #dfebf3;border-radius:14px;padding:11px}
.thumb{width:70px;height:70px;border-radius:12px;object-fit:contain;background:#f7fbfe}.word{font-size:20px;font-weight:800}.meta{font-size:13px;color:#6a8193;margin-top:4px}.small-actions{display:flex;gap:7px}.small-actions a,.small-actions button{padding:8px 10px;border-radius:9px;border:0;text-decoration:none;font-weight:700;font-size:13px}
@media(max-width:850px){.grid{grid-template-columns:1fr}.top{align-items:flex-start;flex-direction:column}.filter{display:grid;grid-template-columns:1fr 1fr}.word-card{grid-template-columns:58px 1fr}.thumb{width:58px;height:58px}.small-actions{grid-column:1/-1}}
</style>
</head>
<body>
<div class="wrap">
  <div class="top">
    <div><h1>📚 Teacher Vocabulary Studio</h1><div class="sub">Nhập từ một lần để Word List, Flashcards, Listen & Repeat và Games dùng chung.</div></div>
    <a class="student-link" href="student-word-list.php?book=global-success&grade=1&id=1&lesson=1&activity=1">Xem trang học sinh →</a>
  </div>

  <?php if ($message): ?><div class="notice ok"><?=htmlspecialchars($message)?></div><?php endif; ?>
  <?php if ($error): ?><div class="notice err"><?=htmlspecialchars($error)?></div><?php endif; ?>

  <div class="grid">
    <section class="panel">
      <h2 style="margin-top:0"><?= $editWord ? 'Sửa từ' : 'Thêm từ mới' ?></h2>
      <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="action" value="save">
        <input type="hidden" name="id" value="<?= (int)($editWord['id'] ?? 0) ?>">

        <div class="row">
          <div><label>Bộ sách</label><select name="book"><option value="global-success" selected>Global Success</option><option value="everybody-up">Everybody Up</option></select></div>
          <div><label>Lớp</label><input type="number" name="grade" min="1" value="<?=htmlspecialchars((string)($editWord['grade'] ?? 1))?>"></div>
        </div>
        <div class="row">
          <div><label>Unit</label><input type="number" name="unit" min="1" value="<?=htmlspecialchars((string)($editWord['unit'] ?? 1))?>"></div>
          <div><label>Lesson</label><input type="number" name="lesson" min="1" value="<?=htmlspecialchars((string)($editWord['lesson'] ?? 1))?>"></div>
        </div>
        <div class="row">
          <div><label>Activity</label><input type="number" name="activity" min="1" value="<?=htmlspecialchars((string)($editWord['activity'] ?? 1))?>"></div>
          <div><label>Thứ tự</label><input type="number" name="sort_order" min="1" value="<?=htmlspecialchars((string)($editWord['sort_order'] ?? 1))?>"></div>
        </div>

        <label>Từ tiếng Anh</label>
        <input name="word" required value="<?=htmlspecialchars($editWord['word'] ?? '')?>">

        <div class="row">
          <div><label>Phiên âm</label><input name="ipa" value="<?=htmlspecialchars($editWord['ipa'] ?? '')?>"></div>
          <div><label>Nghĩa tiếng Việt</label><input name="meaning" value="<?=htmlspecialchars($editWord['meaning'] ?? '')?>"></div>
        </div>

        <label>Câu ví dụ</label>
        <textarea name="example" rows="2"><?=htmlspecialchars($editWord['example'] ?? '')?></textarea>

        <label>Tải hình ảnh</label>
        <input type="file" name="image_file" accept="image/*">
        <label>Hoặc đường dẫn hình</label>
        <input name="image_url" value="<?=htmlspecialchars($editWord['image'] ?? '')?>">

        <label>Tải file âm thanh</label>
        <input type="file" name="audio_file" accept="audio/*">
        <label>Hoặc đường dẫn audio</label>
        <input name="audio_url" value="<?=htmlspecialchars($editWord['audio'] ?? '')?>">

        <div class="actions">
          <button class="btn primary" type="submit"><?= $editWord ? 'Lưu thay đổi' : 'Thêm từ' ?></button>
          <?php if ($editWord): ?><a class="btn secondary" href="teacher-vocabulary.php">Hủy sửa</a><?php endif; ?>
        </div>
      </form>
    </section>

    <section class="panel">
      <form class="filter" method="get">
        <div><label>Bộ sách</label><select name="book"><option value="global-success" <?= $filterBook==='global-success'?'selected':'' ?>>Global Success</option><option value="everybody-up" <?= $filterBook==='everybody-up'?'selected':'' ?>>Everybody Up</option></select></div>
        <div><label>Lớp</label><input type="number" name="grade" min="1" value="<?=$filterGrade?>"></div>
        <div><label>Unit</label><input type="number" name="unit" min="1" value="<?=$filterUnit?>"></div>
        <button class="btn secondary" type="submit">Lọc</button>
      </form>

      <div class="cards">
        <?php if (!$filtered): ?><p>Chưa có từ nào trong Unit này.</p><?php endif; ?>
        <?php foreach ($filtered as $item): ?>
        <article class="word-card">
          <img class="thumb" src="<?=htmlspecialchars($item['image'] ?: 'uploads/vocabulary/book.svg')?>" alt="">
          <div>
            <div class="word"><?=htmlspecialchars($item['word'])?></div>
            <div class="meta"><?=htmlspecialchars($item['ipa'])?> • <?=htmlspecialchars($item['meaning'])?></div>
            <div class="meta">Lesson <?=$item['lesson']?> • Activity <?=$item['activity']?> • Thứ tự <?=$item['sort_order']?></div>
          </div>
          <div class="small-actions">
            <button class="secondary" type="button" onclick='speakWord(<?=json_encode($item["word"])?>)'>🔊 Đọc</button>
            <a class="secondary" href="?edit=<?=$item['id']?>">Sửa</a>
            <form method="post" onsubmit="return confirm('Xóa từ này?')">
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?=$item['id']?>">
              <button class="danger" type="submit">Xóa</button>
            </form>
          </div>
        </article>
        <?php endforeach; ?>
      </div>
    </section>
  </div>
</div>
<script>
function speakWord(word){
  if(!('speechSynthesis' in window)){alert('Trình duyệt không hỗ trợ đọc từ.');return;}
  speechSynthesis.cancel();
  const u=new SpeechSynthesisUtterance(word);
  u.lang='en-US';u.rate=.75;
  speechSynthesis.speak(u);
}
</script>
</body>
</html>
