<?php
require_once '../includes/config.php';
requireLogin();
$db = getDB();

// is_enabled column আছে কিনা check করো
$hasEnabledCol = false;
try {
    $db->query("SELECT is_enabled FROM intl_countries LIMIT 1");
    $hasEnabledCol = true;
} catch(Exception $e) {
    // Column নেই — add করো
    try {
        $db->exec("ALTER TABLE intl_countries ADD COLUMN is_enabled TINYINT(1) DEFAULT 0");
        $db->exec("ALTER TABLE intl_countries ADD COLUMN sort_order INT DEFAULT 0");
        // Popular countries enable করো
        $popular = "'BD','IN','PK','SA','AE','MY','KW','QA','OM','BH','GB','US','AU','NG','GH','KE','ZA','EG','PH','ID','NP','LK','SG','JP','TR','BR'";
        $db->exec("UPDATE intl_countries SET is_enabled=1 WHERE iso IN ($popular)");
        $hasEnabledCol = true;
    } catch(Exception $e2) {}
}

// Countries fetch
$rows = [];
try {
    if ($hasEnabledCol) {
        $rows = $db->query("SELECT iso, name, dial_code FROM intl_countries WHERE is_enabled=1 ORDER BY sort_order, name")->fetchAll();
    } else {
        $rows = $db->query("SELECT iso, name, dial_code FROM intl_countries ORDER BY name")->fetchAll();
    }
} catch(Exception $e) {}

if (empty($rows)) {
    // enabled=0 মানে admin সব disable করেছেন — empty দেখাও
    // শুধু is_enabled column না থাকলে বা intl_countries table খালি হলে fallback করো
    $totalCountries = 0;
    try {
        $totalCountries = $db->query("SELECT COUNT(*) FROM intl_countries")->fetchColumn();
    } catch(Exception $e) {}

    if ($totalCountries > 0) {
        jsonResponse(false, 'No countries enabled. Admin panel থেকে countries enable করুন।');
    }

    // Table খালি — DingConnect থেকে আনো
    require_once '../includes/dingconnect.php';
    $result = dingGetCountries();
    
    if (!isset($result['ResultCode']) || $result['ResultCode'] != 1) {
        // DingConnect fail — hardcoded popular countries দাও
        $hardcoded = [
            ['iso'=>'BD','name'=>'Bangladesh','dial_code'=>'880'],
            ['iso'=>'IN','name'=>'India','dial_code'=>'91'],
            ['iso'=>'PK','name'=>'Pakistan','dial_code'=>'92'],
            ['iso'=>'SA','name'=>'Saudi Arabia','dial_code'=>'966'],
            ['iso'=>'AE','name'=>'United Arab Emirates','dial_code'=>'971'],
            ['iso'=>'MY','name'=>'Malaysia','dial_code'=>'60'],
            ['iso'=>'KW','name'=>'Kuwait','dial_code'=>'965'],
            ['iso'=>'QA','name'=>'Qatar','dial_code'=>'974'],
            ['iso'=>'OM','name'=>'Oman','dial_code'=>'968'],
            ['iso'=>'BH','name'=>'Bahrain','dial_code'=>'973'],
            ['iso'=>'GB','name'=>'United Kingdom','dial_code'=>'44'],
            ['iso'=>'US','name'=>'United States','dial_code'=>'1'],
            ['iso'=>'AU','name'=>'Australia','dial_code'=>'61'],
            ['iso'=>'CA','name'=>'Canada','dial_code'=>'1'],
            ['iso'=>'NG','name'=>'Nigeria','dial_code'=>'234'],
            ['iso'=>'GH','name'=>'Ghana','dial_code'=>'233'],
            ['iso'=>'KE','name'=>'Kenya','dial_code'=>'254'],
            ['iso'=>'ZA','name'=>'South Africa','dial_code'=>'27'],
            ['iso'=>'EG','name'=>'Egypt','dial_code'=>'20'],
            ['iso'=>'PH','name'=>'Philippines','dial_code'=>'63'],
            ['iso'=>'ID','name'=>'Indonesia','dial_code'=>'62'],
            ['iso'=>'NP','name'=>'Nepal','dial_code'=>'977'],
            ['iso'=>'LK','name'=>'Sri Lanka','dial_code'=>'94'],
            ['iso'=>'MM','name'=>'Myanmar','dial_code'=>'95'],
            ['iso'=>'SG','name'=>'Singapore','dial_code'=>'65'],
            ['iso'=>'CN','name'=>'China','dial_code'=>'86'],
            ['iso'=>'JP','name'=>'Japan','dial_code'=>'81'],
            ['iso'=>'KR','name'=>'South Korea','dial_code'=>'82'],
            ['iso'=>'TR','name'=>'Turkey','dial_code'=>'90'],
            ['iso'=>'BR','name'=>'Brazil','dial_code'=>'55'],
        ];
        $formatted = [];
        foreach ($hardcoded as $c) {
            $formatted[] = ['iso'=>$c['iso'],'name'=>$c['name'],'flag'=>'🌍','dial_code'=>'+'.$c['dial_code']];
        }
        usort($formatted, function($a,$b){ return strcmp($a['name'],$b['name']); });
        jsonResponse(true, 'OK', ['countries'=>$formatted]);
    }

    // DingConnect থেকে পেয়েছি — DB তে save করো
    $items = $result['Items'] ?? [];
    try {
        $stmt = $db->prepare("INSERT IGNORE INTO intl_countries (iso,name,dial_code) VALUES (?,?,?)");
        foreach ($items as $c) {
            $iso  = $c['CountryIso']  ?? '';
            $name = $c['CountryName'] ?? '';
            $dial = $c['InternationalDialingInformation'][0]['DialingCode'] ?? '';
            if ($iso && $name) $stmt->execute([$iso,$name,$dial]);
        }
        $rows = $db->query("SELECT iso,name,dial_code FROM intl_countries ORDER BY name")->fetchAll();
    } catch(Exception $e) {
        // DB save fail হলেও response দাও
        $formatted = [];
        foreach ($items as $c) {
            $iso  = $c['CountryIso']  ?? '';
            $name = $c['CountryName'] ?? '';
            if ($iso && $name) $formatted[] = ['iso'=>$iso,'name'=>$name,'flag'=>'🌍','dial_code'=>''];
        }
        usort($formatted, function($a,$b){ return strcmp($a['name'],$b['name']); });
        jsonResponse(true, 'OK', ['countries'=>$formatted]);
    }
}

$formatted = [];
foreach ($rows as $c) {
    $formatted[] = [
        'iso'      => $c['iso'],
        'name'     => $c['name'],
        'flag'     => '🌍',
        'dial_code'=> $c['dial_code'] ? '+'.$c['dial_code'] : '',
    ];
}

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