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

// Cron Job: Sync SMM Services & Recalculate Rates Every Hour
// Run: Every hour via cron: php /home/yourusername/public_html/admin/cron/sync_smm_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);

// Load JAP class
$jap_path = dirname(__DIR__) . '/include/JAP.php';
if (!file_exists($jap_path)) {
    die("JAP.php not found");
}
require_once $jap_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: Sync SMM Services & Recalculate Rates ===");

    // Get settings
    $site = $pdo->query("SELECT * FROM settings WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
    
    if (empty($site['jap_api_key'])) {
        cron_log("WARNING: JAP API key not configured, skipping sync");
        return;
    }

    $api_key  = $site['jap_api_key'];
    $api_url  = $site['jap_api_url'] ?? 'https://the-owlet.com/api/v2';
    $markup   = (float)($site['smm_markup'] ?? 30);

    cron_log("JAP API Key: " . substr($api_key, 0, 10) . "...");
    cron_log("Markup: {$markup}%");

    // ── 1. Get Exchange Rates ──────────────────��──────────────
    $er_raw  = '';
    $ch = curl_init('https://open.er-api.com/v6/latest/USD');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $er_raw = curl_exec($ch);
    curl_close($ch);

    $er_data = json_decode($er_raw, true);
    $rub_to_ngn = 0.0;

    if (is_array($er_data) && isset($er_data['result'], $er_data['rates']['NGN'], $er_data['rates']['RUB']) &&
        $er_data['result'] === 'success' && (float)$er_data['rates']['RUB'] > 0) {
        $rub_to_ngn = (float)$er_data['rates']['NGN'] / (float)$er_data['rates']['RUB'];
        cron_log("Fetched live rates: RUB->NGN = {$rub_to_ngn}");

        // Cache rates
        try {
            $pdo->prepare(
                "INSERT INTO price_settings (setting_key, setting_value, updated_at)
                   VALUES ('rub_to_ngn', :rtn, NOW())
                 ON DUPLICATE KEY UPDATE setting_value = :rtn2, updated_at = NOW()"
            )->execute([':rtn' => round($rub_to_ngn, 6), ':rtn2' => round($rub_to_ngn, 6)]);
        } catch (PDOException $e) {
            cron_log("WARNING: Could not cache rates: " . $e->getMessage());
        }
    } else {
        cron_log("WARNING: Could not fetch live rates, using cached value");
        $ps_rows = $pdo->query("SELECT setting_value FROM price_settings WHERE setting_key='rub_to_ngn'")
            ->fetch(PDO::FETCH_ASSOC);
        $rub_to_ngn = $ps_rows ? (float)$ps_rows['setting_value'] : 0.0;
        if ($rub_to_ngn <= 0) {
            $rub_to_ngn = 1600.0 / 88.0; // Fallback
            cron_log("Using fallback rate: {$rub_to_ngn}");
        }
    }

    // ── 2. Fetch JAP Services ────────────────────────────────
    $jap = new JAP($api_key, $api_url);
    $res = $jap->getServices();

    if (!$res['success']) {
        cron_log("ERROR: JAP API Error: " . ($res['error'] ?? 'Unknown'));
        return;
    }

    $services = $res['data'];
    if (empty($services) || !is_array($services)) {
        cron_log("ERROR: No services returned from JAP");
        return;
    }

    cron_log("Fetched " . count($services) . " services from JAP");

    // ── 3. Upsert Services ──────────────────────────────────
    $inserted = 0;
    $updated  = 0;

    foreach ($services as $s) {
        $jap_rate = (float)($s['rate'] ?? 0);
        $our_rate = round($jap_rate * (1 + $markup / 100), 2);
        $jap_id   = (int)($s['service'] ?? 0);
        $category = $s['category'] ?? 'General';
        $name     = $s['name'] ?? '';
        $type     = $s['type'] ?? 'Default';
        $min      = (int)($s['min'] ?? 10);
        $max      = (int)($s['max'] ?? 1000000);
        $refill   = !empty($s['refill']) ? 1 : 0;
        $cancel   = !empty($s['cancel']) ? 1 : 0;

        if (!$jap_id || empty($name)) continue;

        try {
            $exists = $pdo->prepare("SELECT id FROM smm_services WHERE jap_service_id = :jid LIMIT 1");
            $exists->execute([':jid' => $jap_id]);
            $row = $exists->fetch();

            if ($row) {
                $pdo->prepare("UPDATE smm_services SET category=:cat, name=:name, type=:type, jap_rate=:jrate, our_rate=:orate,
                    min_quantity=:min, max_quantity=:max, refill=:refill, cancel=:cancel, updated_at=NOW()
                    WHERE jap_service_id=:jid")
                    ->execute(['cat'=>$category,'name'=>$name,'type'=>$type,'jrate'=>$jap_rate,'orate'=>$our_rate,
                               'min'=>$min,'max'=>$max,'refill'=>$refill,'cancel'=>$cancel,'jid'=>$jap_id]);
                $updated++;
            } else {
                $pdo->prepare("INSERT INTO smm_services
                    (jap_service_id,category,name,type,jap_rate,our_rate,min_quantity,max_quantity,refill,cancel,status)
                    VALUES(:jid,:cat,:name,:type,:jrate,:orate,:min,:max,:refill,:cancel,1)")
                    ->execute(['jid'=>$jap_id,'cat'=>$category,'name'=>$name,'type'=>$type,
                               'jrate'=>$jap_rate,'orate'=>$our_rate,'min'=>$min,'max'=>$max,
                               'refill'=>$refill,'cancel'=>$cancel]);
                $inserted++;
            }
        } catch (PDOException $e) {
            cron_log("ERROR processing service {$jap_id}: " . $e->getMessage());
        }
    }

    cron_log("SMM Services: {$inserted} inserted, {$updated} updated");

    // ── 4. Recalculate All Rates ────────────────────────────
    try {
        $all = $pdo->query("SELECT id, jap_rate FROM smm_services")->fetchAll(PDO::FETCH_ASSOC);
        $count = 0;
        foreach ($all as $s) {
            $new_rate = round((float)$s['jap_rate'] * (1 + $markup / 100), 2);
            $pdo->prepare("UPDATE smm_services SET our_rate=:r WHERE id=:id")
                ->execute([':r' => $new_rate, ':id' => $s['id']]);
            $count++;
        }
        cron_log("Recalculated {$count} SMM service prices");
    } catch (PDOException $e) {
        cron_log("ERROR recalculating rates: " . $e->getMessage());
    }

    cron_log("=== CRON SUCCESS ===\n");

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