<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/classes/SMSPoolAPI.php';

// CRITICAL: Increase timeout for this script (1 hour)
set_time_limit(3600);
ini_set('max_execution_time', 3600);

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

// Check admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';

$api = new SMSPoolAPI();
$pdo = getDBConnection();

// Get profit margin
$margin = 20;
try {
    $stmt = $pdo->query("SELECT setting_value FROM site_settings WHERE setting_key = 'sms_profit_margin'");
    $row = $stmt->fetch();
    if ($row) $margin = floatval($row['setting_value']);
} catch (Exception $e) {}

if ($action === 'sync_batch') {
    $offset = intval($_GET['offset'] ?? 0);
    $limit = intval($_GET['limit'] ?? 5);
    
    try {
        $result = syncPricesBatch($api, $pdo, $offset, $limit, $margin);
        echo json_encode($result);
    } catch (Exception $e) {
        echo json_encode([
            'error' => $e->getMessage(),
            'offset' => $offset,
            'can_retry' => true
        ]);
    }
    exit;
}

if ($action === 'get_total') {
    $countries = $pdo->query("SELECT COUNT(*) FROM sms_countries WHERE status = 'active'")->fetchColumn();
    $services = $pdo->query("SELECT COUNT(*) FROM sms_services WHERE status = 'active'")->fetchColumn();
    
    echo json_encode([
        'total' => $countries * $services,
        'countries' => $countries,
        'services' => $services
    ]);
    exit;
}

echo json_encode(['error' => 'Invalid action']);

function syncPricesBatch($api, $pdo, $offset, $limit, $profitMargin) {
    $countries = $pdo->query("SELECT id, api_country_id FROM sms_countries WHERE status = 'active' ORDER BY id")->fetchAll();
    $services = $pdo->query("SELECT id, api_service_id FROM sms_services WHERE status = 'active' ORDER BY id")->fetchAll();
    
    if (empty($countries) || empty($services)) {
        return ['error' => 'No countries or services. Sync them first.'];
    }
    
    $combinations = [];
    foreach ($countries as $country) {
        foreach ($services as $service) {
            $combinations[] = ['country' => $country, 'service' => $service];
        }
    }
    
    $total = count($combinations);
    
    if ($offset >= $total) {
        return ['success' => true, 'done' => true, 'total' => $total, 'count' => 0, 'progress' => 100];
    }
    
    $batch = array_slice($combinations, $offset, $limit);
    $count = 0;
    $skipped = 0;
    $errors = 0;
    
    foreach ($batch as $combo) {
        try {
            $result = $api->getPrice($combo['country']['api_country_id'], $combo['service']['api_service_id']);
            
            if (isset($result['price']) && floatval($result['price']) > 0) {
                $apiPrice = floatval($result['price']);
                $customPrice = round($apiPrice * (1 + $profitMargin / 100), 4);
                
                $stmt = $pdo->prepare("
                    INSERT INTO sms_pricing (country_id, service_id, api_price, custom_price, status) 
                    VALUES (?, ?, ?, ?, 'active') 
                    ON DUPLICATE KEY UPDATE api_price = ?, custom_price = ?, status = 'active'
                ");
                $stmt->execute([
                    $combo['country']['id'],
                    $combo['service']['id'],
                    $apiPrice,
                    $customPrice,
                    $apiPrice,
                    $customPrice
                ]);
                $count++;
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO sms_pricing (country_id, service_id, api_price, custom_price, status) 
                    VALUES (?, ?, 0, 0, 'inactive') 
                    ON DUPLICATE KEY UPDATE status = 'inactive'
                ");
                $stmt->execute([$combo['country']['id'], $combo['service']['id']]);
                $skipped++;
            }
        } catch (Exception $e) {
            $errors++;
        }
        
        usleep(300000); // 0.3s delay to avoid rate limit
    }
    
    $nextOffset = $offset + $limit;
    $done = $nextOffset >= $total;
    
    return [
        'success' => true,
        'count' => $count,
        'skipped' => $skipped,
        'errors' => $errors,
        'offset' => $offset,
        'total' => $total,
        'next_offset' => $done ? null : $nextOffset,
        'done' => $done,
        'progress' => min(100, round(($nextOffset / $total) * 100))
    ];
}