<?php
declare(strict_types=1);

/**
 * EnglishSpeak
 * teacher/lessons/edit.php
 */

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

$pdo = getDbConnection();

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

$id = max(0, (int)($_GET['id'] ?? 0));
if ($id <= 0) {
    header('Location: index.php');
    exit;
}

$pageTitle = 'Edit Lesson';
$pageSubtitle = 'Update lesson information';
$activeTeacherNav = 'content';

$stmt = $pdo->prepare(
"SELECT l.*,u.book_id
 FROM lessons l
 INNER JOIN units u ON u.id=l.unit_id
 WHERE l.id=? LIMIT 1");
$stmt->execute([$id]);
$lesson=$stmt->fetch(PDO::FETCH_ASSOC);

if(!$lesson){
    $_SESSION['lessons_message']='Lesson not found.';
    $_SESSION['lessons_message_type']='error';
    header('Location:index.php');
    exit;
}

$lessonOwnerId = (int)($lesson['created_by_teacher_id'] ?? 0);
$canManageLesson = $isAdmin || ($lessonOwnerId > 0 && $lessonOwnerId === $teacherId);

if (!$canManageLesson) {
    $_SESSION['lessons_message'] = 'You do not have permission to edit this Lesson.';
    $_SESSION['lessons_message_type'] = 'error';
    header('Location:index.php');
    exit;
}

$books=$pdo->query("SELECT id,name FROM books WHERE status='active' ORDER BY sort_order,name")->fetchAll(PDO::FETCH_ASSOC);

$bookId=(int)$lesson['book_id'];

$u=$pdo->prepare("SELECT id,unit_number,title FROM units WHERE book_id=? AND status='active' ORDER BY sort_order,id");
$u->execute([$bookId]);
$units=$u->fetchAll(PDO::FETCH_ASSOC);

ob_start();
?>
<style>
.form-card{max-width:950px;background:#fff;border:1px solid #e5e7eb;border-radius:18px;padding:24px}
.grid{display:grid;grid-template-columns:1fr 1fr;gap:18px}
.full{grid-column:1/-1}
input,select,textarea{width:100%;min-height:44px;padding:10px 12px;border:1px solid #dbe2ea;border-radius:10px;font:inherit}
textarea{min-height:120px}
label{font-weight:700;font-size:13px}
.actions{display:flex;justify-content:flex-end;gap:10px;margin-top:20px}
@media(max-width:700px){.grid{grid-template-columns:1fr}.full{grid-column:auto}}
</style>

<h2>Edit Lesson</h2>

<form class="form-card" action="update.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?=$lesson['id']?>">

<div class="grid">

<div>
<label>Book</label>
<select disabled>
<?php foreach($books as $b): ?>
<option <?=$b['id']==$bookId?'selected':''?>><?=htmlspecialchars($b['name'])?></option>
<?php endforeach;?>
</select>
</div>

<div>
<label>Unit</label>
<select name="unit_id" required>
<?php foreach($units as $x): ?>
<option value="<?=$x['id']?>" <?=$x['id']==$lesson['unit_id']?'selected':''?>>
<?=htmlspecialchars($x['unit_number'].' • '.$x['title'])?>
</option>
<?php endforeach;?>
</select>
</div>

<div>
<label>Lesson Number</label>
<input name="lesson_number" required value="<?=htmlspecialchars($lesson['lesson_number'])?>">
</div>

<div>
<label>Lesson Type</label>
<input name="lesson_type" value="<?=htmlspecialchars($lesson['lesson_type'])?>">
</div>

<div class="full">
<label>Lesson Title</label>
<input name="title" required value="<?=htmlspecialchars($lesson['title'])?>">
</div>

<div class="full">
<label>Description</label>
<textarea name="description"><?=htmlspecialchars((string)$lesson['description'])?></textarea>
</div>

<div>
<label>Thumbnail</label>
<input type="file" name="thumbnail">
<?php if(!empty($lesson['thumbnail'])):?>
<div style="margin-top:8px">
<img src="/EnglishSpeak/<?=htmlspecialchars($lesson['thumbnail'])?>" style="max-width:120px;border-radius:10px">
</div>
<?php endif;?>
</div>

<div>
<label>Status</label>
<select name="status">
<option value="active" <?=$lesson['status']=='active'?'selected':''?>>Active</option>
<option value="inactive" <?=$lesson['status']=='inactive'?'selected':''?>>Hidden</option>
</select>
</div>

<div>
<label>Access</label>
<select name="access_type">
<option value="free" <?=$lesson['access_type']=='free'?'selected':''?>>Free</option>
<option value="premium" <?=$lesson['access_type']=='premium'?'selected':''?>>Premium</option>
</select>
</div>

<div>
<label>Required XP</label>
<input type="number" name="required_xp" value="<?=$lesson['required_xp']?>">
</div>

<div>
<label>Unlock Mode</label>
<select name="unlock_mode" id="unlock_mode">
<option value="sequential_daily" <?=($lesson['unlock_mode'] ?? 'sequential_daily')==='sequential_daily'?'selected':''?>>Sequential Daily</option>
<option value="scheduled" <?=($lesson['unlock_mode'] ?? '')==='scheduled'?'selected':''?>>Scheduled Unlock</option>
</select>
<div style="margin-top:6px;color:#64748b;font-size:12px;line-height:1.4">Sequential Daily opens the next Lesson no earlier than the next day. Scheduled Unlock uses a specific date.</div>
</div>

<div id="unlockDateField" <?=($lesson['unlock_mode'] ?? 'sequential_daily')==='scheduled'?'':'hidden'?>>
<label>Unlock Date</label>
<input type="date" name="unlock_date" id="unlock_date" value="<?=htmlspecialchars((string)($lesson['unlock_date'] ?? ''))?>">
<div style="margin-top:6px;color:#64748b;font-size:12px">Used only for Scheduled Unlock.</div>
</div>

<div>
<label>Sort Order</label>
<input type="number" name="sort_order" value="<?=$lesson['sort_order']?>">
</div>

</div>

<div class="actions">
<a class="button button-secondary" href="index.php">Cancel</a>
<button class="button button-primary">Save Changes</button>
</div>

</form>

<script>
(function(){
    const mode=document.getElementById('unlock_mode');
    const date=document.getElementById('unlock_date');
    const field=document.getElementById('unlockDateField');
    function syncUnlockFields(){
        const scheduled=mode && mode.value==='scheduled';
        if(field) field.hidden=!scheduled;
        if(date) date.required=scheduled;
        if(!scheduled && date) date.value='';
    }
    mode?.addEventListener('change',syncUnlockFields);
    syncUnlockFields();
})();
</script>

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