<?php
declare(strict_types=1);
require __DIR__ . '/../partials/auth.php';
require_once __DIR__ . '/../../config/database.php';
header('Content-Type: application/json; charset=utf-8');

$currentUserId = (int)($_SESSION['user_id'] ?? 0);
$currentUserRole = strtolower(trim((string)($_SESSION['user_role'] ?? $_SESSION['role'] ?? 'teacher')));
$isAdmin = $currentUserRole === 'admin';
if($_SERVER['REQUEST_METHOD']!=='POST'){http_response_code(405);echo json_encode(['success'=>false]);exit;}
$data=json_decode(file_get_contents('php://input'),true)?:$_POST;
$id=filter_var($data['set_id']??null,FILTER_VALIDATE_INT);
$title=trim((string)($data['title']??'')); $description=trim((string)($data['description']??''));
if(!$id||$title===''){http_response_code(422);echo json_encode(['success'=>false,'message'=>'Title is required.']);exit;}
$pdo=getDbConnection();
$ownerStmt=$pdo->prepare('SELECT created_by_teacher_id FROM flashcard_sets WHERE id=? LIMIT 1');
$ownerStmt->execute([$id]);
$owner=$ownerStmt->fetchColumn();
if(!$isAdmin && ($owner===false || $owner===null || (int)$owner!==$currentUserId)){http_response_code(403);echo json_encode(['success'=>false,'message'=>'Bạn không có quyền sửa Set này.'],JSON_UNESCAPED_UNICODE);exit;}
$stmt=$pdo->prepare("UPDATE flashcard_sets SET title=?,description=?,updated_at=NOW() WHERE id=?");
$stmt->execute([$title,$description?:null,$id]);
echo json_encode(['success'=>true,'message'=>'Saved'],JSON_UNESCAPED_UNICODE);
