<?php
/**
 * POST /api/save-account.php
 * Insert/update cont eMAG. Răspuns JSON.
 */
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);
}

$id          = (int)($_POST['id'] ?? 0);
$accountName = trim((string)($_POST['account_name'] ?? ''));
$username    = trim((string)($_POST['username'] ?? ''));
$password    = (string)($_POST['password'] ?? '');
$platform    = $_POST['platform'] ?? 'ro';
$isActive    = !empty($_POST['is_active']) ? 1 : 0;
$isFbe       = !empty($_POST['is_fbe']) ? 1 : 0;

if ($accountName === '' || $username === '' || $password === '') {
    json_response(['ok' => false, 'error' => 'Denumire, username și parolă sunt obligatorii.'], 422);
}
if (!array_key_exists($platform, EmagAPI::PLATFORMS)) {
    json_response(['ok' => false, 'error' => 'Platformă invalidă.'], 422);
}

try {
    if ($id > 0) {
        db_exec(
            "UPDATE emag_accounts
             SET account_name=?, username=?, password=?, platform=?, is_active=?, is_fbe=?
             WHERE id=?",
            [$accountName, $username, $password, $platform, $isActive, $isFbe, $id]
        );
        $savedId = $id;
    } else {
        $exists = db_scalar("SELECT id FROM emag_accounts WHERE username = ?", [$username]);
        if ($exists) {
            json_response(['ok' => false, 'error' => 'Există deja un cont cu acest username.'], 422);
        }
        $savedId = db_exec(
            "INSERT INTO emag_accounts (account_name, username, password, platform, is_active, is_fbe)
             VALUES (?,?,?,?,?,?)",
            [$accountName, $username, $password, $platform, $isActive, $isFbe]
        );
    }

    $rows = db_select("SELECT * FROM emag_accounts WHERE id = ?", [$savedId]);
    json_response(['ok' => true, 'account' => $rows[0] ?? null]);
} catch (Throwable $ex) {
    error_log('[save-account] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => $ex->getMessage()], 500);
}
