<?php
/**
 * POST /api/update-session-item.php
 *
 * Body:
 *   action = update | delete
 *   id     = title_session_items.id
 *   new_title = string (pentru update)
 */
require_once __DIR__ . '/../includes/db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(['ok' => false, 'error' => 'Doar POST'], 405);
}
if (!csrf_check($_POST['csrf_token'] ?? null)) {
    json_response(['ok' => false, 'error' => 'CSRF invalid'], 403);
}

$action = $_POST['action'] ?? 'update';
$id     = (int)($_POST['id'] ?? 0);
if ($id <= 0) {
    json_response(['ok' => false, 'error' => 'ID invalid'], 422);
}

try {
    if ($action === 'delete') {
        db_exec("DELETE FROM title_session_items WHERE id = ?", [$id]);
        json_response(['ok' => true]);
    }

    if ($action === 'update') {
        $newTitle = trim((string)($_POST['new_title'] ?? ''));
        // Verific status — nu permit edit pe items deja trimise cu success
        $row = db_select("SELECT sent_status FROM title_session_items WHERE id = ?", [$id]);
        if (!$row) json_response(['ok' => false, 'error' => 'Item inexistent'], 404);
        if ($row[0]['sent_status'] === 'success') {
            json_response(['ok' => false, 'error' => 'Item deja trimis cu succes — nu mai poate fi modificat'], 409);
        }
        // Editare manuală → marchez is_manual=1 (sticky pentru template apply)
        db_exec(
            "UPDATE title_session_items
             SET new_title = ?, sent_status = 'pending', error_message = NULL, is_manual = 1
             WHERE id = ?",
            [$newTitle, $id]
        );
        json_response(['ok' => true, 'is_manual' => 1]);
    }

    // Toggle lock pe is_manual (din UI: butonul lock/unlock)
    if ($action === 'set_manual') {
        $isManual = !empty($_POST['is_manual']) ? 1 : 0;
        db_exec("UPDATE title_session_items SET is_manual = ? WHERE id = ?", [$isManual, $id]);
        json_response(['ok' => true, 'is_manual' => $isManual]);
    }

    json_response(['ok' => false, 'error' => 'Action invalid'], 422);
} catch (Throwable $ex) {
    error_log('[update-session-item] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => $ex->getMessage()], 500);
}
