<?php
/**
 * POST /api/save-template.php
 * Insert/update template pentru nume produs.
 */
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'] ?? ''));
$template    = trim((string)($_POST['template'] ?? ''));
$description = trim((string)($_POST['description'] ?? '')) ?: null;

if ($name === '' || $template === '') {
    json_response(['ok' => false, 'error' => 'Nume și template sunt obligatorii.'], 422);
}

try {
    if ($id > 0) {
        db_exec(
            "UPDATE name_templates SET name=?, template=?, description=? WHERE id=?",
            [$name, $template, $description, $id]
        );
        $savedId = $id;
    } else {
        $savedId = db_exec(
            "INSERT INTO name_templates (name, template, description) VALUES (?,?,?)",
            [$name, $template, $description]
        );
    }
    $rows = db_select("SELECT * FROM name_templates WHERE id = ?", [$savedId]);
    json_response(['ok' => true, 'template' => $rows[0] ?? null]);
} catch (Throwable $ex) {
    error_log('[save-template] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => $ex->getMessage()], 500);
}
