<?php
/**
 * POST /api/save-product.php
 * Insert sau update produs. Răspuns JSON.
 */
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/template-engine.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);
}

// --- Sanitizare & validare ---
$id              = (int)($_POST['id'] ?? 0);
$emagAccountId   = !empty($_POST['emag_account_id']) ? (int)$_POST['emag_account_id'] : null;
$ean             = trim((string)($_POST['ean'] ?? '')) ?: null;
$productName     = trim((string)($_POST['product_name'] ?? ''));
$pnk             = trim((string)($_POST['pnk'] ?? '')) ?: null;
$codOblio        = trim((string)($_POST['cod_oblio'] ?? '')) ?: null;
$emagId          = trim((string)($_POST['emag_id'] ?? '')) ?: null;
$emagPartNumber  = trim((string)($_POST['emag_part_number'] ?? '')) ?: null;
$category        = trim((string)($_POST['category'] ?? '')) ?: null;
$status          = $_POST['status'] ?? 'draft';
$notes           = trim((string)($_POST['notes'] ?? '')) ?: null;
// units_per_box: int sau NULL (gol = NULL, nu 0)
$unitsRaw        = isset($_POST['units_per_box']) ? trim((string)$_POST['units_per_box']) : '';
$unitsPerBox     = $unitsRaw === '' ? null : max(0, (int)$unitsRaw);
// Câmpuri noi (templates + phone link)
$phoneSeriesId   = !empty($_POST['phone_series_id']) ? (int)$_POST['phone_series_id'] : null;
$customName      = trim((string)($_POST['custom_name'] ?? '')) ?: null;

if ($productName === '') {
    json_response(['ok' => false, 'error' => 'Numele produsului este obligatoriu.'], 422);
}
if (mb_strlen($productName) > 500) {
    json_response(['ok' => false, 'error' => 'Numele produsului depășește 500 caractere.'], 422);
}
if (!in_array($status, ['draft','active','synced'], true)) {
    $status = 'draft';
}

try {
    if ($id > 0) {
        db_exec(
            "UPDATE products
             SET emag_account_id=?, ean=?, product_name=?, pnk=?, cod_oblio=?,
                 emag_id=?, emag_part_number=?, category=?, status=?, notes=?,
                 units_per_box=?, phone_series_id=?, custom_name=?
             WHERE id=?",
            [$emagAccountId, $ean, $productName, $pnk, $codOblio,
             $emagId, $emagPartNumber, $category, $status, $notes,
             $unitsPerBox, $phoneSeriesId, $customName, $id]
        );
        $savedId = $id;
    } else {
        $savedId = db_exec(
            "INSERT INTO products
              (emag_account_id, ean, product_name, pnk, cod_oblio,
               emag_id, emag_part_number, category, status, notes,
               units_per_box, phone_series_id, custom_name)
             VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
            [$emagAccountId, $ean, $productName, $pnk, $codOblio,
             $emagId, $emagPartNumber, $category, $status, $notes,
             $unitsPerBox, $phoneSeriesId, $customName]
        );
    }

    $joinSql = template_join_sql();
    $selSql  = template_select_sql();
    $rows = db_select(
        "SELECT p.*,
                a.account_name,
                c.name        AS cat_name,
                c.custom_name AS cat_custom_name,
                c.emag_category_id AS cat_emag_id,
                c.is_excluded AS cat_is_excluded,
                $selSql
         FROM products p
         LEFT JOIN emag_accounts a ON a.id = p.emag_account_id
         LEFT JOIN categories    c ON c.id = p.category_id
         $joinSql
         WHERE p.id = ?",
        [$savedId]
    );

    json_response(['ok' => true, 'product' => $rows[0] ?? null]);
} catch (Throwable $ex) {
    error_log('[save-product] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => 'Eroare DB: ' . $ex->getMessage()], 500);
}
