<?php
/**
 * POST /api/save-session.php
 * Insert/update sesiune (doar metadata: name, description).
 */
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);
}

$id          = (int)($_POST['id'] ?? 0);
$name        = trim((string)($_POST['name'] ?? ''));
$description = trim((string)($_POST['description'] ?? '')) ?: null;

if ($name === '') {
    json_response(['ok' => false, 'error' => 'Numele este obligatoriu.'], 422);
}

try {
    if ($id > 0) {
        db_exec("UPDATE title_sessions SET name = ?, description = ? WHERE id = ?",
            [$name, $description, $id]);
        $savedId = $id;
    } else {
        $savedId = db_exec("INSERT INTO title_sessions (name, description) VALUES (?, ?)",
            [$name, $description]);
    }
    $rows = db_select(
        "SELECT s.*,
                (SELECT COUNT(*) FROM title_session_items WHERE session_id = s.id) AS items_count,
                (SELECT COUNT(*) FROM title_session_items WHERE session_id = s.id AND sent_status = 'success') AS success_count,
                (SELECT COUNT(*) FROM title_session_items WHERE session_id = s.id AND sent_status = 'failed')  AS failed_count
         FROM title_sessions s WHERE id = ?",
        [$savedId]
    );
    json_response(['ok' => true, 'session' => $rows[0] ?? null]);
} catch (Throwable $ex) {
    error_log('[save-session] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => $ex->getMessage()], 500);
}
