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

header('Content-Type: application/json');
set_time_limit(300); // 5 minutes
$db = getDB();

$action = sanitize($_POST['action'] ?? $_GET['action'] ?? 'sync');

// ===== SYNC COUNTRIES =====
if ($action === 'sync_countries') {
    $result = dingGetCountries();
    if (!isset($result['ResultCode']) || $result['ResultCode'] != 1) {
        echo json_encode(['success'=>false,'message'=>'Countries API failed']);
        exit;
    }
    $items = $result['Items'] ?? [];
    $count = 0;
    $stmt  = $db->prepare("INSERT INTO intl_countries (iso,name,dial_code) VALUES (?,?,?) ON DUPLICATE KEY UPDATE name=VALUES(name),dial_code=VALUES(dial_code)");
    foreach ($items as $c) {
        $iso  = $c['CountryIso']  ?? '';
        $name = $c['CountryName'] ?? '';
        $dial = '';
        if (!empty($c['InternationalDialingInformation'])) {
            $dial = $c['InternationalDialingInformation'][0]['DialingCode'] ?? '';
        }
        if (!$iso || !$name) continue;
        $stmt->execute([$iso, $name, $dial]);
        $count++;
    }
    echo json_encode(['success'=>true,'message'=>"✅ $count দেশ sync হয়েছে!",'count'=>$count]);
    exit;
}

// ===== SYNC PRODUCTS (by country or all) =====
if ($action === 'sync_products') {
    $country  = strtoupper(sanitize($_POST['country'] ?? ''));
    $usdRate  = floatval($db->query("SELECT value FROM settings WHERE `key`='intl_usd_rate'")->fetchColumn() ?: 110);

    // পুরনো data delete করে fresh sync করো
    if ($country) {
        $db->prepare("DELETE FROM intl_products WHERE country_iso=?")->execute([$country]);
    }

    // GetProviders for names
    $provParams = $country ? ['country_isos' => $country] : [];
    $provResult = _dingCall('GetProviders', $provParams);
    $provMap    = [];
    if (isset($provResult['Items'])) {
        foreach ($provResult['Items'] as $pv) {
            $code = $pv['ProviderCode'] ?? '';
            if ($code) $provMap[$code] = [
                'name' => $pv['Name']    ?? $code,
                'logo' => $pv['LogoUrl'] ?? '',
            ];
        }
    }

    // GetProducts
    $prodParams = $country ? ['country_isos' => $country] : [];
    $prodResult = _dingCall('GetProducts', $prodParams);
    if (!isset($prodResult['ResultCode']) || $prodResult['ResultCode'] != 1) {
        echo json_encode(['success'=>false,'message'=>'Products API failed: '.json_encode($prodResult['ErrorCodes']??[])]);
        exit;
    }

    $products  = $prodResult['Items'] ?? [];
    $inserted  = 0;
    $updated   = 0;

    $stmt = $db->prepare("INSERT INTO intl_products
        (sku_code,provider_code,provider_name,provider_logo,country_iso,country_name,
         product_type,display_text,send_value,send_currency,recv_value,recv_currency,
         bdt_price,usd_rate,validation_regex,pay_type,is_active)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1)
        ON DUPLICATE KEY UPDATE
            provider_name=VALUES(provider_name),
            provider_logo=VALUES(provider_logo),
            display_text=VALUES(display_text),
            send_value=VALUES(send_value),
            recv_value=VALUES(recv_value),
            recv_currency=VALUES(recv_currency),
            bdt_price=VALUES(bdt_price),
            usd_rate=VALUES(usd_rate),
            is_active=1,
            synced_at=NOW()");

    // Get country names from DB
    $countryNames = [];
    foreach ($db->query("SELECT iso,name FROM intl_countries")->fetchAll() as $cn) {
        $countryNames[$cn['iso']] = $cn['name'];
    }

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

        if (!$sku) continue;

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

        // Product type - Final classification
        $benefitStr = implode(',', $benefits);
        $hasMobile  = stripos($benefitStr, 'Mobile')  !== false;
        $hasData    = stripos($benefitStr, 'Data')    !== false;
        $hasMinutes = stripos($benefitStr, 'Minutes') !== false;

        if ($mechanism === 'Pin' || in_array('CallingCard', $benefits)) {
            // Explicit PIN
            $type = 'pin';
        } elseif ($mechanism === 'Immediate' && ($hasMobile || $hasData || $hasMinutes)) {
            // Immediate + Mobile/Data/Minutes = সরাসরি recharge
            $type = 'recharge';
        } elseif ($mechanism === 'ReadReceipt' && ($hasMobile || $hasData || $hasMinutes)) {
            // ReadReceipt + Mobile/Data/Minutes = Recharge PIN (user কিনে phone এ dial করে)
            $type = 'pin';
        } elseif (in_array('DigitalProduct', $benefits)) {
            // Digital only = voucher (Roblox, gift cards)
            $type = 'voucher';
        } elseif ($mechanism === 'Immediate') {
            $type = 'recharge';
        } else {
            $type = 'voucher';
        }

        $prov      = $provMap[$pCode] ?? ['name'=>$pCode,'logo'=>''];
        $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'] ?? '';
        $dispText  = $p['DefaultDisplayText'] ?? '';
        $payTypes  = implode(',', $p['PaymentTypes'] ?? []);
        $bdtPrice  = round($sendVal * $usdRate, 2);
        $cName     = $countryNames[$region] ?? $region;

        if ($sendVal <= 0) continue;

        // Extract AccountNumber regex from SettingDefinitions
        $regex = '';
        $settings = $p['SettingDefinitions'] ?? [];
        foreach ($settings as $sd) {
            if (($sd['Name'] ?? '') === 'AccountNumber' || ($sd['SettingDefinitionType'] ?? '') === 'AccountNumber') {
                $regex = $sd['ValidationRegex'] ?? $sd['Regex'] ?? '';
                break;
            }
        }

        $stmt->execute([
            $sku, $pCode, $prov['name'], $prov['logo'],
            $region, $cName, $type, $dispText,
            $sendVal, $sendCur, $recvVal, $recvCur,
            $bdtPrice, $usdRate, $regex, $payTypes
        ]);

        if ($db->lastInsertId() > 0) $inserted++;
        else $updated++;
    }

    // Update sync time
    $db->prepare("INSERT INTO settings (`key`,`value`) VALUES ('intl_last_sync',?) ON DUPLICATE KEY UPDATE `value`=?")->execute([date('Y-m-d H:i:s'), date('Y-m-d H:i:s')]);

    $label = $country ?: 'সব দেশ';
    echo json_encode(['success'=>true,'message'=>"✅ $label: $inserted নতুন, $updated আপডেট",'inserted'=>$inserted,'updated'=>$updated]);
    exit;
}

// ===== UPDATE RATE ONLY =====
if ($action === 'update_rate') {
    $rate = floatval($_POST['rate'] ?? 0);
    if ($rate < 50 || $rate > 500) {
        echo json_encode(['success'=>false,'message'=>'Rate 50-500 এর মধ্যে হতে হবে']);
        exit;
    }
    $db->prepare("UPDATE intl_products SET bdt_price=ROUND(send_value*?,2), usd_rate=?")->execute([$rate, $rate]);
    $db->prepare("INSERT INTO settings (`key`,`value`) VALUES ('intl_usd_rate',?) ON DUPLICATE KEY UPDATE `value`=?")->execute([$rate, $rate]);
    $count = $db->query("SELECT COUNT(*) FROM intl_products")->fetchColumn();
    echo json_encode(['success'=>true,'message'=>"✅ Rate $rate টাকা সেট হয়েছে। $count products আপডেট!"]);
    exit;
}

echo json_encode(['success'=>false,'message'=>'Unknown action']);
