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

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

$db = getDB();

$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='recharge' AND is_active=1 ORDER BY provider_name,recv_value,send_value");
$stmt->execute([$country]);
$rows = $stmt->fetchAll();

if (empty($rows)) {
    jsonResponse(false, 'এই দেশের packages DB তে নেই। Admin থেকে sync করুন।');
}

$formatted = [];
$providers = [];
foreach ($rows as $p) {
    $pCode   = $p['provider_code'];
    $pName   = $p['provider_name'];
    $recvVal = floatval($p['recv_value']);
    $recvCur = $p['recv_currency'];
    if (!isset($providers[$pCode])) $providers[$pCode] = $pName;
    $formatted[] = [
        'sku_code'      => $p['sku_code'],
        'name'          => $pName.' — '.$p['display_text'],
        'provider_code' => $pCode,
        'provider_name' => $pName,
        'provider_logo' => $p['provider_logo'],
        'display_text'  => $p['display_text'],
        'send_value'    => floatval($p['send_value']),
        'currency'      => $p['send_currency'],
        'recv_value'    => $recvVal,
        'recv_currency' => $recvCur,
        'description'   => $recvVal>0 ? $recvCur.' '.$recvVal.' পাবেন' : '',
        'bdt_price'     => floatval($p['bdt_price']),
    ];
}
asort($providers);
jsonResponse(true, 'OK', ['packages'=>$formatted,'providers'=>$providers]);
