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

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

// GetProducts থেকে unique providers বের করো
$result = dingGetProducts($country);

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

$products = $result['Items'] ?? [];
if (empty($products)) {
    jsonResponse(false, 'এই দেশে কোনো অপারেটর নেই');
}

// Debug: first product keys
$firstKeys = array_keys($products[0] ?? []);

// Unique providers বের করো
$providers = [];
foreach ($products as $p) {
    // সব possible provider code/name keys
    $code = $p['ProviderCode'] ?? $p['provider_code'] ?? '';
    $name = $p['ProviderName'] ?? $p['provider_name'] ?? '';

    if (!$code) continue;
    if (!isset($providers[$code])) {
        $providers[$code] = [
            'provider_code' => $code,
            'name'          => $name ?: $code, // name না থাকলে code দেখাও
            'debug_keys'    => $firstKeys,      // debug এর জন্য
        ];
    }
}

$formatted = array_values($providers);

if (empty($formatted)) {
    jsonResponse(false, 'Provider parse failed. Product keys: ' . json_encode($firstKeys) . ' | Sample: ' . json_encode(array_slice($products[0] ?? [], 0, 5)));
}

usort($formatted, function($a,$b){ return strcmp($a['name'], $b['name']); });

// debug_keys সরাও
foreach ($formatted as &$f) unset($f['debug_keys']);

jsonResponse(true, 'OK', ['providers' => $formatted]);
