<?php
/**
 * POST /api/test-connection.php
 * Body: id=N  (folosește contul salvat)
 *   sau: username + password + platform (test fără salvare)
 */
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);
$username = trim((string)($_POST['username'] ?? ''));
$password = (string)($_POST['password'] ?? '');
$platform = $_POST['platform'] ?? 'ro';

if ($id > 0) {
    $rows = db_select("SELECT username, password, platform FROM emag_accounts WHERE id = ?", [$id]);
    if (!$rows) {
        json_response(['ok' => false, 'error' => 'Contul nu există.'], 404);
    }
    $username = $rows[0]['username'];
    $password = $rows[0]['password'];
    $platform = $rows[0]['platform'];
}

if ($username === '' || $password === '') {
    json_response(['ok' => false, 'error' => 'Credențiale lipsă.'], 422);
}
if (!array_key_exists($platform, EmagAPI::PLATFORMS)) {
    json_response(['ok' => false, 'error' => 'Platformă invalidă.'], 422);
}

try {
    $api = new EmagAPI($username, $password, $platform);
    $res = $api->testConnection();
    json_response($res, $res['ok'] ? 200 : 400);
} catch (Throwable $ex) {
    json_response(['ok' => false, 'error' => $ex->getMessage()], 500);
}
