<?php
declare(strict_types=1);
/**
 * EnglishSpeak
 * teacher/lessons/update.php
 */
require __DIR__.'/../partials/auth.php';
require_once __DIR__.'/../../config/database.php';

if($_SERVER['REQUEST_METHOD']!=='POST'){
    header('Location:index.php');
    exit;
}
$pdo=getDbConnection();

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

$id=max(0,(int)($_POST['id']??0));
$unitId=max(0,(int)($_POST['unit_id']??0));
$lessonNumber=trim((string)($_POST['lesson_number']??''));
$title=trim((string)($_POST['title']??''));
$type=trim((string)($_POST['lesson_type']??'vocabulary'));
$description=trim((string)($_POST['description']??''));
$access=(string)($_POST['access_type']??'free');
$status=(string)($_POST['status']??'active');
$xp=max(0,(int)($_POST['required_xp']??0));
$sort=max(0,(int)($_POST['sort_order']??0));
$unlockMode=(string)($_POST['unlock_mode']??'sequential_daily');
$unlockDate=trim((string)($_POST['unlock_date']??''));

if(!in_array($unlockMode,['sequential_daily','scheduled'],true)){
    $unlockMode='sequential_daily';
}
if($unlockMode==='sequential_daily'){
    $unlockDate='';
}
if($unlockMode==='scheduled'){
    $date=DateTimeImmutable::createFromFormat('!Y-m-d',$unlockDate);
    if($unlockDate==='' || !$date || $date->format('Y-m-d')!==$unlockDate){
        $_SESSION['lessons_message']='Please select a valid Unlock Date for Scheduled Unlock.';
        $_SESSION['lessons_message_type']='error';
        header('Location:edit.php?id='.$id);
        exit;
    }
}

if($id<=0||$unitId<=0||$lessonNumber===''||$title===''){
    $_SESSION['lessons_message']='Missing required information.';
    $_SESSION['lessons_message_type']='error';
    header('Location:edit.php?id='.$id);
    exit;
}

$current=$pdo->prepare(
    "SELECT l.thumbnail, l.created_by_teacher_id, u.book_id
     FROM lessons l
     INNER JOIN units u ON u.id = l.unit_id
     WHERE l.id = ?
     LIMIT 1"
);
$current->execute([$id]);
$row=$current->fetch(PDO::FETCH_ASSOC);
if(!$row){
    $_SESSION['lessons_message']='Lesson not found.';
    $_SESSION['lessons_message_type']='error';
    header('Location:index.php');
    exit;
}

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

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

$currentBookId = (int)$row['book_id'];

$targetUnitStmt = $pdo->prepare(
    "SELECT u.id, u.book_id
     FROM units u
     WHERE u.id = ?
       AND u.status = 'active'
     LIMIT 1"
);
$targetUnitStmt->execute([$unitId]);
$targetUnit = $targetUnitStmt->fetch(PDO::FETCH_ASSOC);

if (!$targetUnit || (int)$targetUnit['book_id'] !== $currentBookId) {
    $_SESSION['lessons_message'] = 'The selected Unit is not valid for this Lesson.';
    $_SESSION['lessons_message_type'] = 'error';
    header('Location:edit.php?id='.$id);
    exit;
}

if (!$isAdmin) {
    $bookAccessStmt = $pdo->prepare(
        "SELECT 1
         FROM teacher_books
         WHERE teacher_id = ?
           AND book_id = ?
         LIMIT 1"
    );
    $bookAccessStmt->execute([$teacherId, $currentBookId]);

    if (!$bookAccessStmt->fetchColumn()) {
        $_SESSION['lessons_message'] = 'You are not allowed to edit Lessons in this Book.';
        $_SESSION['lessons_message_type'] = 'error';
        header('Location:index.php');
        exit;
    }
}

$thumb=$row['thumbnail'];

if(isset($_FILES['thumbnail']) && ($_FILES['thumbnail']['error']??UPLOAD_ERR_NO_FILE)===UPLOAD_ERR_OK){
    $dir=dirname(__DIR__,2).'/uploads/lessons';
    if(!is_dir($dir)) mkdir($dir,0775,true);
    $ext=strtolower(pathinfo($_FILES['thumbnail']['name'],PATHINFO_EXTENSION));
    if(!in_array($ext,['jpg','jpeg','png','webp'],true)){
        $_SESSION['lessons_message']='Invalid thumbnail format.';
        $_SESSION['lessons_message_type']='error';
        header('Location:edit.php?id='.$id);
        exit;
    }
    $name='lesson-'.date('Ymd-His').'-'.bin2hex(random_bytes(6)).'.'.$ext;
    if(move_uploaded_file($_FILES['thumbnail']['tmp_name'],$dir.'/'.$name)){
        if($thumb){
            $old=dirname(__DIR__,2).'/'.str_replace('\\','/',$thumb);
            if(is_file($old)) @unlink($old);
        }
        $thumb='uploads/lessons/'.$name;
    }
}

$dup=$pdo->prepare("SELECT id FROM lessons WHERE unit_id=? AND LOWER(TRIM(lesson_number))=LOWER(TRIM(?)) AND id<>? LIMIT 1");
$dup->execute([$unitId,$lessonNumber,$id]);
if($dup->fetchColumn()){
    $_SESSION['lessons_message']='Lesson Number already exists.';
    $_SESSION['lessons_message_type']='error';
    header('Location:edit.php?id='.$id);
    exit;
}

$stmt=$pdo->prepare("UPDATE lessons SET
unit_id=?,
lesson_number=?,
title=?,
lesson_type=?,
thumbnail=?,
description=?,
access_type=?,
required_xp=?,
unlock_mode=?,
unlock_date=?,
sort_order=?,
status=?,
updated_at=NOW()
WHERE id=?");
$stmt->execute([
$unitId,
$lessonNumber,
$title,
$type,
$thumb,
$description!==''?$description:NULL,
$access,
$xp,
$unlockMode,
$unlockMode==='scheduled'?$unlockDate:NULL,
$sort,
$status,
$id
]);

$_SESSION['lessons_message']='Lesson updated successfully.';
$_SESSION['lessons_message_type']='success';
header('Location:index.php');
exit;
