<?php
declare(strict_types=1);

/**
 * EnglishSpeak
 * Save the Example Sentence selected for one Word inside one Flashcard Set.
 */

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

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

function exampleResponse(bool $success, string $message = '', int $status = 200): never
{
    http_response_code($status);
    echo json_encode(
        ['success' => $success, 'message' => $message],
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
    );
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    exampleResponse(false, 'Method not allowed.', 405);
}

$setId = filter_input(INPUT_POST, 'set_id', FILTER_VALIDATE_INT);
$wordId = filter_input(INPUT_POST, 'word_id', FILTER_VALIDATE_INT);
$exampleId = filter_input(INPUT_POST, 'example_id', FILTER_VALIDATE_INT);

if (!$setId || !$wordId || !$exampleId) {
    exampleResponse(false, 'Invalid Set, Word or Example.', 422);
}

$pdo = getDbConnection();
$currentUserId = (int)($_SESSION['user_id'] ?? 0);
$currentUserRole = strtolower(trim((string)($_SESSION['user_role'] ?? $_SESSION['role'] ?? 'teacher')));
$isAdmin = $currentUserRole === 'admin';

try {
    $columns = $pdo->query('SHOW COLUMNS FROM flashcard_set_words')->fetchAll(PDO::FETCH_COLUMN);
    if (!in_array('example_id', $columns, true)) {
        exampleResponse(false, 'Database chưa có cột flashcard_set_words.example_id.', 409);
    }

    $setStmt = $pdo->prepare(
        'SELECT created_by_teacher_id FROM flashcard_sets WHERE id = ? LIMIT 1'
    );
    $setStmt->execute([$setId]);
    $owner = $setStmt->fetchColumn();

    if ($owner === false) {
        exampleResponse(false, 'Flashcard Set not found.', 404);
    }
    if (!$isAdmin && ($owner === null || (int)$owner !== $currentUserId)) {
        exampleResponse(false, 'Bạn không có quyền sửa Flashcard Set này.', 403);
    }

    $exampleStmt = $pdo->prepare(
        "SELECT id
         FROM word_examples
         WHERE id = ?
           AND word_id = ?
           AND status = 'active'
         LIMIT 1"
    );
    $exampleStmt->execute([$exampleId, $wordId]);
    if (!$exampleStmt->fetchColumn()) {
        exampleResponse(false, 'Example không thuộc Word này hoặc đã bị khóa.', 422);
    }

    $updateStmt = $pdo->prepare(
        'UPDATE flashcard_set_words
         SET example_id = ?
         WHERE set_id = ?
           AND word_id = ?'
    );
    $updateStmt->execute([$exampleId, $setId, $wordId]);

    if ($updateStmt->rowCount() < 1) {
        $existsStmt = $pdo->prepare(
            'SELECT 1 FROM flashcard_set_words WHERE set_id = ? AND word_id = ? LIMIT 1'
        );
        $existsStmt->execute([$setId, $wordId]);
        if (!$existsStmt->fetchColumn()) {
            exampleResponse(false, 'Word is not in this Flashcard Set.', 404);
        }
    }

    exampleResponse(true, 'Example saved.');
} catch (Throwable $e) {
    error_log('EnglishSpeak flashcards/ajax/update_example.php: ' . $e->getMessage());
    exampleResponse(false, 'Could not save Example.', 500);
}
