<?php
// اجرای هر 15 الی 30 دقیقه

include "../config.php";
error_reporting(0);
date_default_timezone_set('Asia/Tehran');

// تابع فراخوانی API
function call_callinoo_api($endpoint, $method = 'GET', $data_array = null, $auth_type = 'url') {
    global $callinoo_api_key, $callinoo_base_url;

    $url = $callinoo_base_url;
    $headers = [
        'Content-Type: application/json',
        'Accept: application/json'
    ];

    if ($auth_type === 'bearer') {
        $url .= $endpoint;
        $headers[] = 'Authorization: Bearer ' . $callinoo_api_key;
    } else {
        $endpoint_with_token = str_replace('{token}', $callinoo_api_key, $endpoint);
        $url .= $endpoint_with_token;
    }

    $ch = curl_init();

    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($data_array) {
            $payload = json_encode($data_array);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
            $headers[] = 'Content-Length: ' . strlen($payload);
        }
    }

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    $response_raw = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);

    if ($curl_error) return ['_http_code' => 503, 'success' => false, 'error' => 'Curl Error: ' . $curl_error];

    $response_json = json_decode($response_raw, true);
    if ($response_json === null) return ['_http_code' => $http_code, 'success' => false, 'error' => 'Invalid JSON response', 'raw' => $response_raw];

    $response_json['_http_code'] = $http_code;
    return $response_json;
}


echo "Cron Job Started: Updating Service Prices...\n";


$settings_res = $connect->query("SELECT * FROM settings LIMIT 1");
$settings = $settings_res->fetch_assoc();

$prices_res_ton = $connect->query("SELECT price FROM crypto_prices WHERE symbol = 'TON_IRT' LIMIT 1");
$ton_irt_price = (float)($prices_res_ton->fetch_assoc()['price'] ?? 0);
if ($ton_irt_price == 0) echo "Warning: TON_IRT price is zero.\n";


if ($settings['order_mode_premium'] === 'auto') {
    echo "Premium Mode is AUTO. Updating from API...\n";
    $api_endpoint_prem = "/telegram-services/premium/";
    $prices_response_prem = call_callinoo_api($api_endpoint_prem, 'GET', null, 'bearer');

    if (isset($prices_response_prem['status']) && $prices_response_prem['status'] === true && isset($prices_response_prem['data'])) {
        
        $fee_multiplier_prem = 1 + (($settings['feepremium'] ?? 0) / 100);
        $updated_count = 0;

        $stmt_prem = $connect->prepare("
            INSERT INTO premium_packages (id, name, price_irt, price_ton, status)
            VALUES (?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
            name = VALUES(name),
            price_irt = VALUES(price_irt),
            price_ton = VALUES(price_ton),
            status = VALUES(status),
            last_updated = NOW()
        ");

        foreach ($prices_response_prem['data'] as $pkg) {
            if (isset($pkg['id']) && isset($pkg['package']) && isset($pkg['price'])) {
                
                $base_price = (int)$pkg['price'];
                $final_price_irt = (int)round($base_price * $fee_multiplier_prem);
                $status = (int)$pkg['status'];

                $final_price_ton = ($ton_irt_price > 0) ? ($final_price_irt / $ton_irt_price) : 0.0;
                
                $stmt_prem->bind_param("isidi", $pkg['id'], $pkg['package'], $final_price_irt, $final_price_ton, $status);
                if($stmt_prem->execute()) $updated_count++;
            }
        }
        $stmt_prem->close();
        echo "Premium Updated: $updated_count items.\n";
    } else {
        echo "Failed to fetch Premium API.\n";
    }
} else {
    echo "Premium Mode is MANUAL. Skipping API update.\n";
}

if ($settings['order_mode_star'] === 'auto') {
    echo "Stars Mode is AUTO. Updating from API...\n";
    $api_endpoint_stars = "/telegram-services/stars/";
    $prices_response_stars = call_callinoo_api($api_endpoint_stars, 'GET', null, 'bearer');

    if (isset($prices_response_stars['status']) && $prices_response_stars['status'] === true && isset($prices_response_stars['data'])) {

        $fee_multiplier_stars = 1 + (($settings['fee_stars'] ?? 0) / 100);
        $updated_count = 0;

        $stmt_stars = $connect->prepare("
            INSERT INTO star_packages (id, name, `count`, price_irt, price_ton, status)
            VALUES (?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
            name = VALUES(name),
            `count` = VALUES(`count`),
            price_irt = VALUES(price_irt),
            price_ton = VALUES(price_ton),
            status = VALUES(status),
            last_updated = NOW()
        ");

        foreach ($prices_response_stars['data'] as $pkg) {
            if (isset($pkg['id']) && isset($pkg['count']) && isset($pkg['price'])) {
                
                $base_price = (int)$pkg['price'];
                $final_price_irt = (int)round($base_price * $fee_multiplier_stars);
                $status = (int)$pkg['status'];
                $count = (int)$pkg['count'];
                $final_price_ton = ($ton_irt_price > 0) ? ($final_price_irt / $ton_irt_price) : 0.0;
                
                $stmt_stars->bind_param("isiidi", $pkg['id'], $pkg['package'], $count, $final_price_irt, $final_price_ton, $status);
                if($stmt_stars->execute()) $updated_count++;
            }
        }
        $stmt_stars->close();
        echo "Stars Updated: $updated_count items.\n";
    } else {
        echo "Failed to fetch Stars API.\n";
    }
} else {
    echo "Stars Mode is MANUAL. Skipping API update.\n";
}

echo "Updating Virtual Number Prices...\n";

$existing_fees = [];
$fee_res = $connect->query("SELECT `range`, `fee_percent` FROM `virtual_numbers_prices`");
if ($fee_res) {
    while ($row = $fee_res->fetch_assoc()) {
        $existing_fees[$row['range']] = (int)$row['fee_percent'];
    }
}

$api_endpoint_vnum = "/web/{token}/get-prices/1"; 
$prices_response_vnum = call_callinoo_api($api_endpoint_vnum, 'GET', null, 'url');

if (isset($prices_response_vnum['_http_code']) && $prices_response_vnum['_http_code'] == 200 && is_array($prices_response_vnum)) {
    
    $stmt_vnum = $connect->prepare("
     INSERT INTO virtual_numbers_prices (country_name, price_irt, price_ton, `range`, count_status, emoji, fee_percent, status, provider_status)
     VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?)
     ON DUPLICATE KEY UPDATE
     country_name = VALUES(country_name),
     price_irt = VALUES(price_irt),
     price_ton = VALUES(price_ton),
     count_status = VALUES(count_status),
     emoji = VALUES(emoji),
     provider_status = VALUES(provider_status),
     last_updated = NOW()
    ");

    foreach ($prices_response_vnum as $item) {
        if (isset($item['country'])) {
            $range = (string)$item['range'];
            $base_price = (int)$item['price'];
            $fee_percent = $existing_fees[$range] ?? 10;
            $fee_multiplier = 1 + ($fee_percent / 100);
            
            $final_price_irt = (int)round($base_price * $fee_multiplier);
            $final_price_ton = ($ton_irt_price > 0) ? ($final_price_irt / $ton_irt_price) : 0.0;
            
            $emoji = $item['emoji'] ?? null;
            if ($emoji === null && preg_match('/(\p{So})/u', $item['country'], $emoji_match)) {
                $emoji = $emoji_match[0];
            }

            $count_status_text = $item['count'];
            $provider_is_available = (strpos($count_status_text, 'ناموجود') !== false || strpos($count_status_text, '❌') !== false) ? 0 : 1;

            $stmt_vnum->bind_param("sidsssii", $item['country'], $final_price_irt, $final_price_ton, $range, $count_status_text, $emoji, $fee_percent, $provider_is_available);
            $stmt_vnum->execute();
        }
    }
    $stmt_vnum->close();
    echo "Virtual Numbers Updated.\n";
}

echo "Updating Manual Premium Packages based on USD...\n";

$rates_res = $connect->query("SELECT symbol, price FROM crypto_prices WHERE symbol IN ('TON_USDT', 'USDT_IRT')");
$rates = [];
while($row = $rates_res->fetch_assoc()){
    $rates[$row['symbol']] = (float)$row['price'];
}

$usdt_irt = $rates['USDT_IRT'] ?? 0;
$ton_usdt = $rates['TON_USDT'] ?? 0;

if($usdt_irt > 0 && $ton_usdt > 0) {

    $manual_pkgs = $connect->query("SELECT id, price_usd FROM premium_packages_manual WHERE price_usd > 0");
    
    $updated_manual = 0;
    $stmt_upd_manual = $connect->prepare("UPDATE premium_packages_manual SET price_irt = ?, price_ton = ? WHERE id = ?");
    
    while($mp = $manual_pkgs->fetch_assoc()) {
        $usd_price = (float)$mp['price_usd'];
        
        // محاسبه جدید
        $new_price_irt = (int)($usd_price * $usdt_irt);
        $new_price_ton = ($usd_price / $ton_usdt); 
        
        $stmt_upd_manual->bind_param("idi", $new_price_irt, $new_price_ton, $mp['id']);
        if($stmt_upd_manual->execute()) {
            $updated_manual++;
        }
    }
    $stmt_upd_manual->close();
    echo "Manual Premium Packages Updated: $updated_manual items.\n";
} else {
    echo "Skipping Manual Update: Exchange rates not found or zero.\n";
}

if ($settings['order_mode_star'] === 'manual') {
    echo "Updating Manual Stars Price based on USD...\n";
    
    $base_usd = (float)($settings['iStar_star_price_per_one_usd'] ?? 0);

    if ($base_usd > 0 && $usdt_irt > 0 && $ton_usdt > 0) {
        
        $new_price_irt = (int)($base_usd * $usdt_irt);
        $new_price_ton = ($base_usd / $ton_usdt);
        
        $connect->query("UPDATE settings SET iStar_star_price_per_one_ton = '$new_price_ton' WHERE botid = '{$settings['botid']}'");
        
        $connect->query("UPDATE star_packages SET price_ton = '$new_price_ton', price_irt = '$new_price_irt' WHERE count = 1");
        
        echo "Manual Stars Price Updated: $base_usd USD -> $new_price_ton TON / $new_price_irt IRT\n";
    } else {
        echo "Skipping Stars Update: Base USD price is 0 or rates missing.\n";
    }
}
$connect->close();
echo "Cron Job Completed.\n";
?>