<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

// Cron Job: Resync All Service Prices Every Hour
// Run: Every hour via cron: php /home/yourusername/public_html/admin/cron/resync_prices_cron.php

define('VALID_ACCESS', true);

// Load config
$config_path = dirname(__DIR__) . '/include/config.php';
if (!file_exists($config_path)) {
    die("Configuration file not found");
}
include($config_path);

// Log function
function cron_log($message) {
    $log_file = dirname(__DIR__) . '/admin/cron/cron.log';
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($log_file, "[{$timestamp}] {$message}\n", FILE_APPEND);
}

try {
    cron_log("=== CRON START: Resync All Prices ===");

    // Load all active servers grouped by api_id
    $servers = $pdo->query("SELECT * FROM otp_server WHERE status='1'")->fetchAll(PDO::FETCH_ASSOC);
    cron_log("Found " . count($servers) . " active servers");

    // Load RUB->NGN rate + markup
    $ps_rows = $pdo->query("SELECT setting_key, setting_value FROM price_settings")
        ->fetchAll(PDO::FETCH_KEY_PAIR);

    $markup_pct = isset($ps_rows['markup_percent']) ? (float)$ps_rows['markup_percent'] : 35.0;
    $rub_to_ngn = isset($ps_rows['rub_to_ngn']) ? (float)$ps_rows['rub_to_ngn'] : 0.0;
    
    if ($rub_to_ngn <= 0) {
        $usd = isset($ps_rows['usd_to_ngn']) ? (float)$ps_rows['usd_to_ngn'] : 1600.0;
        $rub_to_ngn = $usd / 88.0;
    }

    cron_log("Using rates: RUB->NGN = {$rub_to_ngn}, Markup = {$markup_pct}%");

    $total_updated = 0;

    foreach ($servers as $server) {
        try {
            $api = $pdo->prepare("SELECT * FROM api_detail WHERE id=:id LIMIT 1");
            $api->execute([':id' => $server['api_id']]);
            $api_data = $api->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            cron_log("ERROR loading API {$server['api_id']}: " . $e->getMessage());
            continue;
        }
        
        if (!$api_data) {
            cron_log("WARNING: API {$server['api_id']} not found");
            continue;
        }

        $country_code = $server['server_code'];
        $price_url = rtrim($api_data['api_url'], '/') .
            '/stubs/handler_api.php?action=getPrices' .
            '&api_key=' . urlencode($api_data['api_key']) .
            '&country=' . urlencode($country_code);

        // Fetch prices
        $ch = curl_init($price_url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 15,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $raw = curl_exec($ch);
        curl_close($ch);

        $pdata = json_decode($raw, true);
        if (!is_array($pdata)) {
            cron_log("WARNING: Invalid price data for country {$country_code}");
            continue;
        }

        // Flatten to svc_code => rub_price
        $price_map = [];
        foreach ($pdata as $outer_key => $outer_val) {
            if (!is_array($outer_val)) continue;
            $first = reset($outer_val);
            if (is_array($first) && isset($first['cost'])) {
                if ((string)$outer_key === (string)$country_code || $outer_key === '0') {
                    foreach ($outer_val as $sc => $info) {
                        if (isset($info['cost']) && (float)$info['cost'] > 0) {
                            $price_map[$sc] = (float)$info['cost'];
                        }
                    }
                }
            } elseif (isset($outer_val['cost'])) {
                if ((float)$outer_val['cost'] > 0) {
                    $price_map[$outer_key] = (float)$outer_val['cost'];
                }
            }
        }

        // Update services
        try {
            $svcs = $pdo->prepare("SELECT id, service_id FROM service WHERE server_id = :sid");
            $svcs->execute([':sid' => $server['id']]);
            $svc_rows = $svcs->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            cron_log("ERROR loading services for server {$server['id']}: " . $e->getMessage());
            continue;
        }

        $server_updated = 0;
        foreach ($svc_rows as $svc) {
            $rub = $price_map[$svc['service_id']] ?? 0.0;
            if ($rub <= 0) continue;
            
            $naira = round($rub * $rub_to_ngn * (1 + $markup_pct / 100), 2);
            
            try {
                $pdo->prepare("UPDATE service SET service_price = :p WHERE id = :id")
                    ->execute([':p' => (string)$naira, ':id' => $svc['id']]);
                $server_updated++;
                $total_updated++;
            } catch (PDOException $e) {
                cron_log("ERROR updating service {$svc['id']}: " . $e->getMessage());
            }
        }

        cron_log("Server {$server['server_name']}: {$server_updated} services updated");
    }

    cron_log("=== CRON SUCCESS: {$total_updated} total service prices updated ===\n");

} catch (Exception $e) {
    cron_log("=== CRON FAILED: " . $e->getMessage() . " ===\n");
}
?>