<?php
/**
 * POST /api/apply-template.php
 *
 * Două moduri:
 *   action=preview → returnează { id, current_name, new_name } per produs, FĂRĂ save
 *   action=apply   → updatează products.custom_name pentru fiecare produs
 *
 * Body:
 *   action      = preview | apply
 *   template    = string (cu placeholders {brand} etc.) — fie text liber, fie luat din template_id
 *   template_id = int (opțional; dacă există, se ignoră `template`)
 *   ids[]       = id-uri produse (obligatoriu)
 */
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);
}

$action      = $_POST['action'] ?? 'preview';
$ids         = $_POST['ids'] ?? [];
$templateStr = trim((string)($_POST['template'] ?? ''));
$templateId  = (int)($_POST['template_id'] ?? 0);

if (!is_array($ids) || !$ids) {
    json_response(['ok' => false, 'error' => 'ids[] lipsesc'], 422);
}
$ids = array_values(array_filter(array_map('intval', $ids), fn($v) => $v > 0));
if (!$ids) {
    json_response(['ok' => false, 'error' => 'ID-uri invalide'], 422);
}

// Rezolvă template-ul (din DB dacă a fost dat template_id)
if ($templateId > 0) {
    $row = db_select("SELECT template FROM name_templates WHERE id = ?", [$templateId]);
    if (!$row) json_response(['ok' => false, 'error' => 'Template inexistent'], 404);
    $templateStr = (string)$row[0]['template'];
}
if ($templateStr === '') {
    json_response(['ok' => false, 'error' => 'Template gol'], 422);
}

try {
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $joinSql = template_join_sql();
    $selSql  = template_select_sql();

    $products = db_select(
        "SELECT p.id, p.ean, p.pnk, p.cod_oblio, p.emag_part_number,
                p.product_name, p.custom_name,
                $selSql
         FROM products p
         $joinSql
         WHERE p.id IN ($placeholders)",
        $ids
    );

    $results = [];
    $updated = 0;
    $missingPhone = 0; // produse care nu au phone_series_id legat (placeholderii {brand}/{model}/{series} vor fi goi)

    foreach ($products as $p) {
        $newName = template_apply($templateStr, $p);
        $needsPhone = (str_contains($templateStr, '{brand}') || str_contains($templateStr, '{model}') || str_contains($templateStr, '{series}'));
        $hasPhone   = !empty($p['phone_brand_name']) || !empty($p['phone_model_name']) || !empty($p['phone_series_name']);
        $warning    = ($needsPhone && !$hasPhone);
        if ($warning) $missingPhone++;

        $results[] = [
            'id'           => (int)$p['id'],
            'current_name' => $p['custom_name'] ?: $p['product_name'],
            'new_name'     => $newName,
            'warning'      => $warning,
        ];

        if ($action === 'apply' && $newName !== '') {
            db_exec("UPDATE products SET custom_name = ? WHERE id = ?", [$newName, $p['id']]);
            $updated++;
        }
    }

    json_response([
        'ok'             => true,
        'action'         => $action,
        'results'        => $results,
        'updated'        => $updated,
        'missing_phone'  => $missingPhone,
    ]);
} catch (Throwable $ex) {
    error_log('[apply-template] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => $ex->getMessage()], 500);
}
