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

header('Content-Type: application/json');

$sku = sanitize($_GET['sku'] ?? '');
if(!$sku){ echo json_encode(['error'=>'SKU required']); exit; }

// Get product details with SettingDefinitions
$result = _dingCall('GetProducts', ['sku_codes' => $sku]);
$items = $result['Items'] ?? [];

if(empty($items)){
    echo json_encode(['error'=>'Product not found','raw'=>$result]);
    exit;
}

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

echo json_encode([
    'sku'              => $p['SkuCode'] ?? '',
    'provider'         => $p['ProviderCode'] ?? '',
    'country'          => $p['RegionCode'] ?? '',
    'validation_regex' => $regex,
    'setting_defs'     => $settings,
], JSON_PRETTY_PRINT);
