<?php
/**
 * Same-origin proxy: forwards phone to FraudChecker.link QC API (Bearer token).
 * Maps upstream JSON into the legacy shape expected by dashboard.js / fraud-check.html.
 */
header('Content-Type: application/json; charset=UTF-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
    exit;
}

$raw = file_get_contents('php://input');
$body = json_decode($raw !== false && $raw !== '' ? $raw : '{}', true);
if (!is_array($body)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid JSON']);
    exit;
}

$phone = isset($body['phone']) ? preg_replace('/\D/', '', (string) $body['phone']) : '';
if (strlen($phone) !== 11 || !preg_match('/^0[1-9]\d{9}$/', $phone)) {
    http_response_code(400);
    echo json_encode([
        'status' => 'error',
        'message' => 'Valid 11-digit Bangladesh mobile required.',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * Trim token, strip UTF-8 BOM, allow pasted "Bearer ..." (proxy adds Bearer itself).
 */
function normalizeFraudCheckerApiKey(string $raw): string
{
    $k = trim($raw);
    if (strncmp($k, "\xEF\xBB\xBF", 3) === 0) {
        $k = trim(substr($k, 3));
    }
    if (preg_match('/^bearer\s+/i', $k)) {
        $k = trim(preg_replace('/^bearer\s+/i', '', $k));
    }

    return trim($k, " \t\n\r\0\x0B");
}

/**
 * @param array<string,mixed> $decoded
 */
function fraudCheckerUpstreamErrorMessage(array $decoded, int $httpCode): string
{
    $msg = '';
    foreach (['message', 'error', 'detail', 'msg', 'description'] as $field) {
        if (!empty($decoded[$field]) && is_string($decoded[$field])) {
            $msg = (string) $decoded[$field];
            break;
        }
    }
    if ($msg === '') {
        $msg = 'FraudChecker API error.';
    }
    if ($httpCode === 403 && (stripos($msg, 'invalid') !== false || stripos($msg, 'key') !== false || stripos($msg, 'authorization') !== false)) {
        $msg .= ' Use Developer API → Copy (do not type from a screenshot—typos cause this). In creative-fraud-config.local.php use api_key = token only (no "Bearer"). Re-upload that file to your live server (cPanel). See api/FRAUDCHECKER-SETUP.md.';
    }

    return $msg;
}

$configPath = __DIR__ . '/creative-fraud-config.local.php';
if (!is_readable($configPath)) {
    http_response_code(503);
    echo json_encode([
        'status' => 'error',
        'message' => 'Fraud API not configured. Copy api/creative-fraud-config.example.php to creative-fraud-config.local.php on the server and set api_key to your FraudChecker Bearer token.',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$config = include $configPath;
if (!is_array($config)) {
    http_response_code(503);
    echo json_encode([
        'status' => 'error',
        'message' => 'creative-fraud-config.local.php must return an array with api_key (your FraudChecker token).',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$rawKey = isset($config['api_key']) ? (string) $config['api_key'] : '';
if ($rawKey === '' && isset($config['bearer_token'])) {
    $rawKey = (string) $config['bearer_token'];
}
$apiKey = normalizeFraudCheckerApiKey($rawKey);
$placeholders = ['', 'PASTE_YOUR_FRAUDCHECKER_BEARER_TOKEN_HERE', 'PASTE_YOUR_X_API_KEY_HERE', 'a4e7c2900d53c0aaa9a53a31901b1fd9'];
if ($apiKey === '' || in_array($apiKey, $placeholders, true)) {
    http_response_code(503);
    echo json_encode([
        'status' => 'error',
        'message' => 'api_key is missing, placeholder, or documentation example key in creative-fraud-config.local.php. Paste your real token from fraudchecker.link dashboard.',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$url = 'https://fraudchecker.link/api/v1/qc/';
$postBody = http_build_query(['phone' => $phone], '', '&', PHP_QUERY_RFC3986);

/**
 * Map FraudChecker success payload to legacy frontend format.
 *
 * @param array<string,mixed> $decoded
 * @return array<string,mixed>
 */
function mapFraudCheckerToLegacy(array $decoded): array
{
    $courierData = [];
    if (isset($decoded['apis']) && is_array($decoded['apis'])) {
        foreach ($decoded['apis'] as $name => $api) {
            if (!is_array($api)) {
                continue;
            }
            $courierData[] = [
                'name' => (string) $name,
                'total' => (int) ($api['total_parcels'] ?? 0),
                'success' => (int) ($api['total_delivered_parcels'] ?? 0),
                'return' => (int) ($api['total_cancelled_parcels'] ?? 0),
            ];
        }
    }

    if ($courierData === [] && isset($decoded['total_parcels'])) {
        $courierData[] = [
            'name' => 'সারাংশ (API)',
            'total' => (int) ($decoded['total_parcels'] ?? 0),
            'success' => (int) ($decoded['total_delivered'] ?? 0),
            'return' => (int) ($decoded['total_cancel'] ?? 0),
        ];
    }

    $message = 'রিপোর্ট তৈরি হয়েছে।';
    if (!empty($decoded['mobile_number'])) {
        $message .= ' (' . (string) $decoded['mobile_number'] . ')';
    }

    return [
        'status' => 'success',
        'message' => $message,
        'courier_data' => $courierData,
        'mobile_number' => $decoded['mobile_number'] ?? null,
        'total_parcels' => $decoded['total_parcels'] ?? null,
        'total_delivered' => $decoded['total_delivered'] ?? null,
        'total_cancel' => $decoded['total_cancel'] ?? null,
    ];
}

if (function_exists('curl_init')) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postBody,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/x-www-form-urlencoded',
            'Accept: application/json',
            'Authorization: Bearer ' . $apiKey,
        ],
        CURLOPT_USERAGENT => 'KuriyarBuilder-FraudProxy/1.0 (+https://fraudchecker.link)',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
    ]);
    $response = curl_exec($ch);
    $errno = curl_errno($ch);
    $httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($errno !== 0 || $response === false) {
        http_response_code(502);
        echo json_encode([
            'status' => 'error',
            'message' => 'Could not reach FraudChecker API. Check server network or PHP curl.',
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $decoded = json_decode($response, true);
    if (!is_array($decoded)) {
        http_response_code($httpCode >= 400 ? $httpCode : 502);
        echo json_encode([
            'status' => 'error',
            'message' => 'Invalid response from FraudChecker API.',
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    if ($httpCode >= 400) {
        $msg = fraudCheckerUpstreamErrorMessage($decoded, $httpCode);
        if ($httpCode >= 100) {
            http_response_code($httpCode);
        }
        echo json_encode(['status' => 'error', 'message' => $msg], JSON_UNESCAPED_UNICODE);
        exit;
    }

    if ($httpCode >= 100) {
        http_response_code($httpCode);
    }
    echo json_encode(mapFraudCheckerToLegacy($decoded), JSON_UNESCAPED_UNICODE);
    exit;
}

$ctx = stream_context_create([
    'http' => [
        'method' => 'POST',
        'header' => "Content-Type: application/x-www-form-urlencoded\r\nAccept: application/json\r\nUser-Agent: KuriyarBuilder-FraudProxy/1.0\r\nAuthorization: Bearer " . $apiKey . "\r\n",
        'content' => $postBody,
        'timeout' => 30,
        'ignore_errors' => true,
    ],
    'ssl' => [
        'verify_peer' => true,
        'verify_peer_name' => true,
    ],
]);

$response = @file_get_contents($url, false, $ctx);
if ($response === false) {
    http_response_code(502);
    echo json_encode([
        'status' => 'error',
        'message' => 'Could not reach FraudChecker API. Enable curl or allow_url_fopen.',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$httpCode = 200;
if (!empty($http_response_header)) {
    foreach ($http_response_header as $h) {
        if (preg_match('/^HTTP\/\S+\s+(\d+)/', $h, $m)) {
            $httpCode = (int) $m[1];
            break;
        }
    }
}

$decoded = json_decode($response, true);
if (!is_array($decoded)) {
    http_response_code($httpCode >= 400 ? $httpCode : 502);
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid response from FraudChecker API.',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($httpCode >= 400) {
    $msg = fraudCheckerUpstreamErrorMessage($decoded, $httpCode);
    if ($httpCode >= 100) {
        http_response_code($httpCode);
    }
    echo json_encode(['status' => 'error', 'message' => $msg], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($httpCode >= 100) {
    http_response_code($httpCode);
}
echo json_encode(mapFraudCheckerToLegacy($decoded), JSON_UNESCAPED_UNICODE);
