<?php
require_once '../includes/config.php';
requireLogin();

$country = strtoupper(sanitize($_GET['country'] ?? ''));
if (!$country) jsonResponse(false, 'Country ISO দিন');

$db = getDB();

// PIN products — ReadReceipt + Mobile/Minutes/Data
$stmt = $db->prepare("
    SELECT sku_code, provider_code, provider_name, provider_logo,
           display_text, send_value, send_currency, recv_value, recv_currency, bdt_price
    FROM intl_products
    WHERE country_iso=? AND product_type='pin' AND is_active=1
    ORDER BY provider_name, recv_value, send_value
");
$stmt->execute([$country]);
$rows = $stmt->fetchAll();

if (empty($rows)) {
    jsonResponse(false, 'এই দেশে কোনো Recharge PIN নেই বা sync হয়নি।');
}

$cRow = $db->prepare("SELECT name FROM intl_countries WHERE iso=?");
$cRow->execute([$country]);
$cName = $cRow->fetchColumn() ?: $country;

$flagMap = [
    'BD'=>'🇧🇩','IN'=>'🇮🇳','PK'=>'🇵🇰','SA'=>'🇸🇦','AE'=>'🇦🇪',
    'MY'=>'🇲🇾','US'=>'🇺🇸','GB'=>'🇬🇧','AU'=>'🇦🇺','KW'=>'🇰🇼',
    'QA'=>'🇶🇦','OM'=>'🇴🇲','BH'=>'🇧🇭','NG'=>'🇳🇬','GH'=>'🇬🇭',
    'KE'=>'🇰🇪','ZA'=>'🇿🇦','PH'=>'🇵🇭','ID'=>'🇮🇩','EG'=>'🇪🇬',
    'NP'=>'🇳🇵','LK'=>'🇱🇰','SG'=>'🇸🇬','CN'=>'🇨🇳','JP'=>'🇯🇵',
    'TR'=>'🇹🇷','BR'=>'🇧🇷','MY'=>'🇲🇾',
];

$formatted = [];
$providers = [];
foreach ($rows as $p) {
    $pCode = $p['provider_code'];
    $pName = $p['provider_name'];
    if (!isset($providers[$pCode])) $providers[$pCode] = $pName;
    $formatted[] = [
        'sku_code'      => $p['sku_code'],
        'provider_code' => $pCode,
        'provider_name' => $pName,
        'logo'          => $p['provider_logo'],
        'display_text'  => $p['display_text'],
        'country_flag'  => $flagMap[$country] ?? '🌍',
        'country_name'  => $cName,
        'send_value'    => floatval($p['send_value']),
        'currency'      => $p['send_currency'],
        'recv_value'    => floatval($p['recv_value']),
        'recv_currency' => $p['recv_currency'],
        'bdt_price'     => floatval($p['bdt_price']),
    ];
}
asort($providers);
jsonResponse(true, 'OK', ['pins' => $formatted, 'providers' => $providers]);
