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

$type    = sanitize($_GET['type']    ?? 'calling');
$country = strtoupper(sanitize($_GET['country'] ?? ''));

// ✅ Step 1: সব Providers আনো (Name + Logo সহ)
$provResult = _dingCall('GetProviders', $country ? ['country_isos' => $country] : []);
$provMap = [];
if (isset($provResult['Items'])) {
    foreach ($provResult['Items'] as $pv) {
        $code = $pv['ProviderCode'] ?? '';
        if (!$code) continue;
        $provMap[$code] = [
            'name'    => $pv['Name']    ?? $code,
            'country' => $pv['CountryIso'] ?? '',
            'logo'    => $pv['LogoUrl']  ?? '',
            'regex'   => $pv['ValidationRegex'] ?? '',
        ];
    }
}

// ✅ Step 2: Products আনো
$params = [];
if ($country) $params['country_isos'] = $country;
$result = _dingCall('GetProducts', $params);

if (isset($result['error'])) jsonResponse(false, $result['error']);
if (!isset($result['ResultCode']) || $result['ResultCode'] != 1) {
    jsonResponse(false, 'API Error');
}

$products = $result['Items'] ?? [];

// Country flag map
$flagMap = [
    'BD'=>'🇧🇩','IN'=>'🇮🇳','PK'=>'🇵🇰','SA'=>'🇸🇦','AE'=>'🇦🇪',
    'MY'=>'🇲🇾','US'=>'🇺🇸','GB'=>'🇬🇧','AU'=>'🇦🇺','KW'=>'🇰🇼',
    'QA'=>'🇶🇦','OM'=>'🇴🇲','BH'=>'🇧🇭','MX'=>'🇲🇽','NG'=>'🇳🇬',
    'GH'=>'🇬🇭','KE'=>'🇰🇪','ZA'=>'🇿🇦','PH'=>'🇵🇭','ID'=>'🇮🇩',
    'EG'=>'🇪🇬','CN'=>'🇨🇳','JP'=>'🇯🇵','KR'=>'🇰🇷','TR'=>'🇹🇷',
    'BR'=>'🇧🇷','NP'=>'🇳🇵','LK'=>'🇱🇰','MM'=>'🇲🇲','SG'=>'🇸🇬',
    'CA'=>'🇨🇦','FR'=>'🇫🇷','DE'=>'🇩🇪','IT'=>'🇮🇹','ES'=>'🇪🇸',
    'EC'=>'🇪🇨','JM'=>'🇯🇲','TT'=>'🇹🇹','RW'=>'🇷🇼','UG'=>'🇺🇬',
    'TZ'=>'🇹🇿','MW'=>'🇲🇼','ZM'=>'🇿🇲','ZW'=>'🇿🇼','SN'=>'🇸🇳',
    'CI'=>'🇨🇮','CM'=>'🇨🇲','CD'=>'🇨🇩','ET'=>'🇪🇹','MA'=>'🇲🇦',
];

$formatted = [];

foreach ($products as $p) {
    $mechanism = $p['RedemptionMechanism'] ?? '';
    $benefits  = $p['Benefits']           ?? [];
    $region    = $p['RegionCode']         ?? '';
    $pCode     = $p['ProviderCode']       ?? '';

    // Type filter
    $isCalling = in_array('CallingCard', $benefits);
    $isDigital = in_array('DigitalProduct', $benefits) || $mechanism === 'Pin';
    if ($type === 'calling'       && !$isCalling) continue;
    if ($type === 'international' && !$isDigital) continue;

    // Country filter
    if ($country && $region && strtoupper($region) !== $country) continue;

    $sku      = $p['SkuCode']      ?? '';
    $dispText = $p['DefaultDisplayText'] ?? '';
    $sendVal  = floatval($p['Maximum']['SendValue']    ?? $p['Minimum']['SendValue']    ?? 0);
    $recvVal  = floatval($p['Maximum']['ReceiveValue'] ?? $p['Minimum']['ReceiveValue'] ?? 0);
    $sendCur  = $p['Maximum']['SendCurrencyIso']    ?? 'USD';
    $recvCur  = $p['Maximum']['ReceiveCurrencyIso'] ?? '';
    if (!$sku || $sendVal <= 0) continue;

    // Provider info
    $prov     = $provMap[$pCode] ?? ['name'=>$pCode,'country'=>$region,'logo'=>''];
    $provName = $prov['name'];
    $provLogo = $prov['logo'];
    $cFlag    = $flagMap[$region] ?? ($flagMap[$prov['country']] ?? '🌍');

    // Card full name: Provider Name + Amount
    // যেমন: "bKash Bangladesh — BDT 100.00"
    $cardTitle = $provName . ' — ' . $dispText;

    // Type label
    if ($isCalling)                              $typeLabel = '📞 Calling Card';
    elseif (in_array('DigitalProduct',$benefits)) $typeLabel = '🎁 Digital Card';
    else                                          $typeLabel = '💳 Card';

    $formatted[] = [
        'sku_code'      => $sku,
        'title'         => $cardTitle,
        'provider_name' => $provName,
        'provider_logo' => $provLogo,
        'display_text'  => $dispText,
        'type_label'    => $typeLabel,
        'country_flag'  => $cFlag,
        'region'        => $region,
        'send_value'    => $sendVal,
        'currency'      => $sendCur,
        'recv_value'    => $recvVal,
        'recv_currency' => $recvCur,
        'bdt_price'     => round($sendVal * 110),
        'validation_regex' => $prov['regex'],
    ];
}

usort($formatted, function($a,$b){
    $c = strcmp($a['provider_name'], $b['provider_name']);
    return $c !== 0 ? $c : ($a['recv_value'] - $b['recv_value']);
});

jsonResponse(true, 'OK', ['cards' => $formatted, 'total' => count($formatted)]);
