<?php
/**
 * POST /api/save-category.php
 * Update setări categorie. Câmpurile gestionate de utilizator: custom_name, notes, is_excluded.
 * `name` și `emag_category_id` sunt informative (sync-ul le actualizează).
 */
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);
$customName  = trim((string)($_POST['custom_name'] ?? '')) ?: null;
$notes       = trim((string)($_POST['notes'] ?? '')) ?: null;
$isExcluded  = !empty($_POST['is_excluded']) ? 1 : 0;

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

try {
    db_exec(
        "UPDATE categories SET custom_name = ?, notes = ?, is_excluded = ? WHERE id = ?",
        [$customName, $notes, $isExcluded, $id]
    );
    $rows = db_select(
        "SELECT c.*,
                (SELECT COUNT(*) FROM products p WHERE p.category_id = c.id) AS products_count
         FROM categories c WHERE c.id = ?",
        [$id]
    );
    json_response(['ok' => true, 'category' => $rows[0] ?? null]);
} catch (Throwable $ex) {
    error_log('[save-category] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => $ex->getMessage()], 500);
}
