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

if (!dingIsConfigured()) {
    jsonResponse(false, '❌ API credentials নেই!');
}

// Bangladesh country ISO
$result = dingGetProducts('BD');

if (isset($result['error'])) {
    jsonResponse(false, '❌ API Error: ' . $result['error']);
}

$products = $result['products'] ?? $result ?? [];
if (empty($products)) {
    jsonResponse(false, '❌ কোনো product পাওয়া যায়নি। Response: ' . json_encode(array_slice((array)$result, 0, 3)));
}

$db = getDB();
$count = 0;

// Get or create a "DingConnect" operator
$opStmt = $db->query("SELECT id FROM operators WHERE code='DING'");
$op = $opStmt->fetch();
if (!$op) {
    $db->prepare("INSERT INTO operators (name,code,prefix,commission_percent,charge,charge_type,status) VALUES (?,?,?,?,?,?,?)")
       ->execute(['DingConnect (Intl)','DING','[]',0,0,'flat','active']);
    $op_id = $db->lastInsertId();
} else {
    $op_id = $op['id'];
}

foreach ($products as $p) {
    $sku      = $p['sku_code'] ?? '';
    $name     = $p['default_display_text'] ?? ($p['description'] ?? $sku);
    $min      = $p['minimum']['send_value'] ?? 0;
    $max      = $p['maximum']['send_value'] ?? 0;
    $validity = $p['validity_period_iso'] ?? '';
    $benefits = implode(', ', $p['benefits'] ?? []);
    $comm     = $p['commission_rate'] ?? 0;
    $sell     = $max > 0 ? $max : $min;

    if (!$sku || !$name) continue;

    // Check if exists
    $exists = $db->prepare("SELECT id FROM packages WHERE api_package_id=? AND operator_id=?");
    $exists->execute([$sku, $op_id]);
    if ($exists->fetch()) {
        $db->prepare("UPDATE packages SET name=?,sell_price=?,cost_price=?,validity=?,description=? WHERE api_package_id=? AND operator_id=?")
           ->execute([$name,$sell,$sell*(1-$comm/100),$validity,$benefits,$sku,$op_id]);
    } else {
        $db->prepare("INSERT INTO packages (operator_id,name,type,amount,validity,description,cost_price,sell_price,reseller_price,api_package_id,status) VALUES (?,?,?,?,?,?,?,?,?,?,'active')")
           ->execute([$op_id,$name,'data',$sell,$validity,$benefits,$sell*(1-$comm/100),$sell,$sell,$sku]);
    }
    $count++;
}

jsonResponse(true, "✅ {$count} টি International product sync হয়েছে! Admin → Packages এ দেখুন।");
