<?php
/**
 * POST /api/apply-template-to-session.php
 *
 * Generează `new_title` pentru itemii unei sesiuni folosind un șablon cu
 * placeholders. Două moduri:
 *
 *   action=preview → returnează { items: [{id, new_title}] } fără save
 *   action=apply   → updatează title_session_items.new_title
 *
 * Body:
 *   action         = preview | apply
 *   session_id     = N
 *   template       = string (cu placeholders) SAU template_id = N (resolved din DB)
 *   item_ids[]     = opțional, dacă lipsește se aplică pe TOȚI itemii editabili
 *                     (sent_status != 'success')
 */
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';
$sessionId        = (int)($_POST['session_id'] ?? 0);
$templateStr      = trim((string)($_POST['template'] ?? ''));
$templateId       = (int)($_POST['template_id'] ?? 0);
$itemIds          = $_POST['item_ids'] ?? null;
$removeDiacritics = !empty($_POST['remove_diacritics']);

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

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 {
    $joinSql = template_join_sql();
    $selSql  = template_select_sql();

    // Includem TOATE items-urile (inclusiv success). Pentru success unde new_title
    // se schimbă efectiv, resetăm la pending — semnal că titlul actual din DB nu
    // mai e sincronizat cu cel trimis la eMAG, deci trebuie re-trimis.
    // is_manual = 1 → titlu sticky, NU se atinge de șablon (preserved)
    $sql = "SELECT i.id AS item_id, i.product_id, i.new_title AS current_new_title, i.sent_status, i.is_manual,
                   p.ean, p.pnk, p.cod_oblio, p.emag_part_number, p.product_name, p.custom_name,
                   $selSql
            FROM title_session_items i
            LEFT JOIN products p ON p.id = i.product_id
            $joinSql
            WHERE i.session_id = ?";
    $params = [$sessionId];

    if (is_array($itemIds) && $itemIds) {
        $itemIds = array_values(array_filter(array_map('intval', $itemIds), fn($v) => $v > 0));
        if ($itemIds) {
            $ph = implode(',', array_fill(0, count($itemIds), '?'));
            $sql .= " AND i.id IN ($ph)";
            $params = array_merge($params, $itemIds);
        }
    }

    $items = db_select($sql, $params);

    $results = [];
    $applied   = 0;
    $skipped   = 0;
    $unchanged = 0;
    $preserved = 0; // items cu is_manual=1 — păstrate intacte

    foreach ($items as $it) {
        // ITEM MANUAL: nu calculez preview, nu modific
        if ((int)$it['is_manual'] === 1) {
            $preserved++;
            $results[] = [
                'id'           => (int)$it['item_id'],
                'old_new'      => $it['current_new_title'],
                'generated'    => $it['current_new_title'], // păstrăm valoarea curentă
                'sent_status'  => $it['sent_status'],
                'is_manual'    => 1,
                'preserved'    => true,
            ];
            continue;
        }

        $newTitle = template_apply($templateStr, $it);
        if ($removeDiacritics) {
            $newTitle = strip_diacritics($newTitle);
        }

        // Title CHANGED:
        //   - failed → pending (curățăm eroarea, e gata pentru retry)
        //   - success → pending (DB-ul nu mai e sincron cu eMAG; trebuie re-trimis)
        //   - pending → rămâne pending
        $titleChanged = $newTitle !== '' && $newTitle !== ($it['current_new_title'] ?? '');
        $newStatus = ($titleChanged && in_array($it['sent_status'], ['failed', 'success'], true))
            ? 'pending' : $it['sent_status'];

        $results[] = [
            'id'           => (int)$it['item_id'],
            'old_new'      => $it['current_new_title'],
            'generated'    => $newTitle,
            'sent_status'  => $it['sent_status'],
            'new_status'   => $newStatus,
            'is_manual'    => 0,
        ];

        if ($action !== 'apply') continue;

        if ($newTitle === '') { $skipped++; continue; }

        // No-op dacă titlul generat e identic cu cel curent — nu „risipim" status-ul success
        if (!$titleChanged) {
            $unchanged++;
            continue;
        }

        db_exec(
            "UPDATE title_session_items
             SET new_title = ?, sent_status = ?, error_message = NULL
             WHERE id = ?",
            [$newTitle, $newStatus, $it['item_id']]
        );
        $applied++;
    }

    json_response([
        'ok'        => true,
        'action'    => $action,
        'items'     => $results,
        'applied'   => $applied,
        'unchanged' => $unchanged,
        'skipped'   => $skipped,
        'preserved' => $preserved,
    ]);
} catch (Throwable $ex) {
    error_log('[apply-template-to-session] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => $ex->getMessage()], 500);
}
