<?php
/**
 * POST /api/price-sync.php
 *
 * Împinge prețurile de vânzare locale spre eMAG (resursa `product_offer/save`).
 *
 * Acțiuni:
 *  action=batch (default) — trimite UN lot de produse; returnează stats + has_more
 *      Body: account_id, offset (0..N)
 *
 * Sunt trimise DOAR produsele care:
 *   - aparțin contului selectat
 *   - au emag_id setat (altfel nu pot fi identificate pe eMAG)
 *   - au sale_price completat (> 0)
 *   - NU sunt excluse (EAN în excluded_eans SAU categorie is_excluded)
 *
 * Frontend-ul (prices.php) apelează action=batch în buclă, mărind offset cu
 * numărul de produse procesate, până când has_more devine false.
 */
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/emag-api.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);
}

$accountId = (int)($_POST['account_id'] ?? 0);
if ($accountId <= 0) {
    json_response(['ok' => false, 'error' => 'account_id lipsește'], 422);
}

$accountRows = db_select("SELECT * FROM emag_accounts WHERE id = ? AND is_active = 1", [$accountId]);
if (!$accountRows) {
    json_response(['ok' => false, 'error' => 'Cont inexistent sau inactiv'], 404);
}
$account = $accountRows[0];

const PRICE_BATCH = 20;

// WHERE comun pentru produsele eligibile la push (folosit și la count, și la select)
$eligibleWhere =
    "p.emag_account_id = ?
     AND p.emag_id IS NOT NULL AND p.emag_id != ''
     AND p.sale_price IS NOT NULL AND p.sale_price > 0
     AND (c.is_excluded IS NULL OR c.is_excluded = 0)
     AND (p.ean IS NULL OR p.ean NOT IN (SELECT ean FROM excluded_eans))";

$offset = max(0, (int)($_POST['offset'] ?? 0));

$total = (int)db_scalar(
    "SELECT COUNT(*) FROM products p
     LEFT JOIN categories c ON c.id = p.category_id
     WHERE $eligibleWhere",
    [$accountId]
);

if ($total === 0) {
    json_response([
        'ok'        => true,
        'processed' => 0,
        'stats'     => ['sent' => 0, 'failed' => 0],
        'has_more'  => false,
        'total'     => 0,
        'errors_log'=> [],
    ]);
}

$items = db_select(
    "SELECT p.id, p.emag_id, p.product_name, p.sale_price
     FROM products p
     LEFT JOIN categories c ON c.id = p.category_id
     WHERE $eligibleWhere
     ORDER BY p.id ASC
     LIMIT ? OFFSET ?",
    [$accountId, PRICE_BATCH, $offset]
);

$stats = ['sent' => 0, 'failed' => 0];
$errorMessages = [];

try {
    $api = new EmagAPI($account['username'], $account['password'], $account['platform'] ?? 'ro');
} catch (Throwable $e) {
    json_response(['ok' => false, 'error' => $e->getMessage()], 502);
}

foreach ($items as $idx => $item) {
    // Throttle: ~2.5 req/sec (sub limita eMAG de 3/sec pe resurse non-orders)
    if ($idx > 0) usleep(400000);

    $res = $api->updateProductPrice([
        'id'         => (int)$item['emag_id'],
        'sale_price' => $item['sale_price'],
    ]);

    if ($res['ok']) {
        db_exec(
            "UPDATE products SET price_synced_at = CURRENT_TIMESTAMP, current_sale_price = sale_price WHERE id = ?",
            [$item['id']]
        );
        $stats['sent']++;
    } else {
        $stats['failed']++;
        $name = $item['product_name'] ?: ('emag_id ' . $item['emag_id']);
        $errorMessages[] = mb_substr($name, 0, 60) . ': ' . $res['message'];
        error_log('[price-sync] #' . $item['id'] . ' ' . $res['message']);
    }
}

$processed  = count($items);
$nextOffset = $offset + $processed;
$hasMore    = $nextOffset < $total && $processed > 0;

json_response([
    'ok'          => true,
    'processed'   => $processed,
    'stats'       => $stats,
    'has_more'    => $hasMore,
    'next_offset' => $nextOffset,
    'total'       => $total,
    'errors_log'  => $errorMessages,
]);
