<?php
declare(strict_types=1);
session_start();
if (!isset($_SESSION['student_id'])) {
    header('Location: student-login.php');
    exit;
}

$book=$_GET['book']??'global-success';
$grade=max(1,(int)($_GET['grade']??1));
$id=max(1,(int)($_GET['id']??1));
$lesson=max(1,(int)($_GET['lesson']??1));
$activity=max(1,(int)($_GET['activity']??1));
$_SESSION['last_learning_url']=$_SERVER['REQUEST_URI'];
$file=__DIR__.'/data/vocabulary.json';
$all=[];
if(is_file($file)){
 $decoded=json_decode(file_get_contents($file)?:'[]',true);
 if(is_array($decoded))$all=$decoded;
}
$words=array_values(array_filter($all,fn($w)=>
 ($w['book']??'')===$book &&
 (int)($w['grade']??0)===$grade &&
 (int)($w['unit']??0)===$id &&
 (int)($w['lesson']??0)===$lesson &&
 (int)($w['activity']??0)===$activity
));
usort($words,fn($a,$b)=>(int)($a['sort_order']??0)<=>(int)($b['sort_order']??0));
$pageTitle='Word List';
$pageSubtitle='Unit '.$id.' • Lesson '.$lesson;
$showBack=true;
$backUrl='student-activities.php?book='.urlencode($book).'&grade='.$grade.'&id='.$id.'&lesson='.$lesson.'&activity='.$activity;
$activeStudentNav='learning';
include __DIR__.'/includes/student-layout-start.php';
?>
<div class="search-box"><input data-word-search placeholder="Tìm từ..."></div>
<div class="card-list">
<?php if(!$words): ?><div class="empty">Giáo viên chưa thêm từ cho bài này.</div><?php endif; ?>
<?php foreach($words as $word): 
$search=strtolower(($word['word']??'').' '.($word['meaning']??''));
?>
<article class="word-card" data-word-card data-search="<?=htmlspecialchars($search,ENT_QUOTES,'UTF-8')?>">
<img src="<?=htmlspecialchars($word['image']??'',ENT_QUOTES,'UTF-8')?>" alt="<?=htmlspecialchars($word['word']??'',ENT_QUOTES,'UTF-8')?>">
<div>
<div class="word-card__word"><?=htmlspecialchars($word['word']??'',ENT_QUOTES,'UTF-8')?></div>
<div class="word-card__ipa"><?=htmlspecialchars($word['ipa']??'',ENT_QUOTES,'UTF-8')?></div>
<div class="word-card__meaning">🇻🇳 <?=htmlspecialchars($word['meaning']??'',ENT_QUOTES,'UTF-8')?></div>
</div>
<button class="sound-button" type="button" data-speak="<?=htmlspecialchars($word['word']??'',ENT_QUOTES,'UTF-8')?>" data-audio="<?=htmlspecialchars($word['audio']??'',ENT_QUOTES,'UTF-8')?>">🔊</button>
<?php if(!empty($word['example'])): ?><div class="word-card__example"><?=htmlspecialchars($word['example'],ENT_QUOTES,'UTF-8')?></div><?php endif; ?>
</article>
<?php endforeach; ?>
</div>
<?php include __DIR__.'/includes/student-layout-end.php'; ?>
