<?php
ob_start();
require_once '../../includes/config.php';
require_once '../../includes/dingconnect.php';
requireAdmin();
ob_clean();
header('Content-Type: application/json');
set_time_limit(120);
ini_set('memory_limit','256M');

$db  = getDB();
$iso = strtoupper(sanitize($_GET['iso'] ?? $_POST['iso'] ?? ''));

// Add column if missing
try { $db->query("SELECT validation_regex FROM intl_products LIMIT 1"); }
catch(Exception $e) {
    try { $db->exec("ALTER TABLE intl_products ADD COLUMN validation_regex VARCHAR(500) DEFAULT NULL"); }
    catch(Exception $e2){}
}

// Single country mode
if($iso){
    $result = _dingCall('GetProducts', ['country_isos' => $iso]);
    if(!isset($result['ResultCode']) || $result['ResultCode'] != 1){
        echo json_encode(['success'=>false,'message'=>"$iso API failed: ".json_encode($result['ErrorCodes']??[])]);
        exit;
    }
    $updated = 0;
    foreach($result['Items'] ?? [] as $p){
        $sku = $p['SkuCode'] ?? ''; if(!$sku) continue;
        $regex = '';
        foreach($p['SettingDefinitions'] ?? [] as $sd){
            if(stripos($sd['Name']??'','account')!==false || stripos($sd['SettingDefinitionType']??'','account')!==false){
                $regex = $sd['ValidationRegex'] ?? $sd['Regex'] ?? '';
                break;
            }
        }
        try{ $db->prepare("UPDATE intl_products SET validation_regex=? WHERE sku_code=?")->execute([$regex,$sku]); $updated++; }catch(Exception $e){}
    }
    echo json_encode(['success'=>true,'message'=>"✅ $iso: $updated products updated",'done'=>true]);
    exit;
}

// Return list of enabled countries to process one by one
$countries = [];
try{ $countries = $db->query("SELECT iso FROM intl_countries WHERE is_enabled=1 ORDER BY iso")->fetchAll(PDO::FETCH_COLUMN); }
catch(Exception $e){ echo json_encode(['success'=>false,'message'=>$e->getMessage()]); exit; }

echo json_encode(['success'=>true,'countries'=>$countries,'message'=>count($countries).' countries to process']);
