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

$api_key    = getSetting('successtopup_key');
$api_secret = getSetting('successtopup_secret');

if (!$api_key || !$api_secret) {
    jsonResponse(false, '❌ SuccessTopUp API Key/Secret নেই!');
}

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

// সব operator এর জন্য loop করো, অথবা নির্দিষ্ট একটা
$stToOurCode = ['GP'=>'GP','RB'=>'ROBI','AT'=>'ROBI','BL'=>'BL','TT'=>'TT','SK'=>'GP','BT'=>'BT'];
$allST       = ['GP','RB','AT','BL','TT','BT'];
$toSync      = $operator ? [$operator] : $allST;

// DB operator map
$opMap = [];
foreach ($db->query("SELECT id,code FROM operators")->fetchAll() as $op) {
    $opMap[strtoupper($op['code'])] = $op['id'];
}

$added = $updated = $skipped = 0;
$errors = [];

foreach ($toSync as $stOp) {
    $ch = curl_init('https://api.successtopup.com/api/drives');
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode([
            'successtopup_key'    => $api_key,
            'successtopup_secret' => $api_secret,
            'operator'            => $stOp,
        ]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
    ]);
    $res = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($res, true);
    if (!$result || !($result['result'] ?? false)) {
        $errors[] = $stOp . ': ' . ($result['message'] ?? 'Unknown error');
        continue;
    }

    $ourCode = $stToOurCode[$stOp] ?? $stOp;
    $op_id   = $opMap[$ourCode] ?? null;
    if (!$op_id) { $errors[] = $stOp . ': Operator not found in DB'; continue; }

    foreach ($result['drives'] ?? [] as $drive) {
        $driveId  = (string)($drive['driveId']   ?? '');
        $title    = $drive['title']     ?? '';
        $price    = floatval($drive['price']      ?? 0);
        $commAmt  = floatval($drive['commission'] ?? 0);
        $duration = intval($drive['duration']     ?? 0);

        if (!$driveId || !$title || $price <= 0) { $skipped++; continue; }

        $costPrice  = max(0, $price - $commAmt);
        $validity   = $duration > 0 ? $duration . ' Days' : '';
        $commPct    = $price > 0 ? round(($commAmt/$price)*100,2) : 0;

        $ex = $db->prepare("SELECT id FROM packages WHERE api_package_id=? AND operator_id=?");
        $ex->execute([$driveId, $op_id]);
        if ($ex->fetch()) {
            $db->prepare("UPDATE packages SET name=?,amount=?,validity=?,cost_price=?,sell_price=?,reseller_price=?,status='active' WHERE api_package_id=? AND operator_id=?")
               ->execute([$title,$price,$validity,$costPrice,$price,round($price*0.97,2),$driveId,$op_id]);
            $updated++;
        } 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,$title,'drive',$price,$validity,'Commission: '.$commPct.'%',$costPrice,$price,round($price*0.97,2),$driveId]);
            $added++;
        }
    }
}

$msg = "✅ Sync সম্পন্ন! যোগ: {$added} | আপডেট: {$updated} | Skip: {$skipped}";
if ($errors) $msg .= "\n⚠️ " . implode(', ', $errors);
jsonResponse(true, $msg, ['added'=>$added,'updated'=>$updated]);
