<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Timezone set karo
date_default_timezone_set('Asia/Kolkata');

// Current domain dynamically fetch karo
$domain = $_SERVER['HTTP_HOST']; 

// Function to execute cron job using wget
function runCronJob($scriptPath) {
    global $domain;
    $url = "https://$domain$scriptPath";
    $command = "wget --spider -O - \"$url\" > /dev/null 2>&1";
    shell_exec($command);
}

// Log file to track last execution times
$logFile = __DIR__ . '/cron_log.json';

// Read log file safely
if (file_exists($logFile)) {
    $lastRuns = json_decode(file_get_contents($logFile), true);
    if (!is_array($lastRuns)) {
        $lastRuns = [];
    }
} else {
    $lastRuns = [];
}

// Current time
$currentTime = time();

// Cron jobs with specific intervals (in minutes)
$cronJobs = [
    5 => [  // Ye wale jobs **har 5 minute** chalenge
        "/cronjobs/dripfeed.php",
        "/crons/cronjobs/autoreply.php",
        "/cronjobs/payments.php",
        "/cronjobs/refill.php",
        "/cronjobs/average.php",
        "/cronjobs/autolike.php"
    ],
    1 => [  // Ye wale jobs **har 1 minute** chalenge
        "/cronjobs/orders.php",
        "/cronjobs/resend_orders.php",
        "/cronjobs/seller-sync.php",
        "/cronjobs/referral_commission.php"
    ]
];

// Execute cron jobs based on timing
foreach ($cronJobs as $interval => $scripts) {
    foreach ($scripts as $job) {
        $lastRun = isset($lastRuns[$job]) ? (int) $lastRuns[$job] : 0;

        if (($currentTime - $lastRun) >= ($interval * 60)) { 
            runCronJob($job);
            $lastRuns[$job] = $currentTime; // Update last execution time
        }
    }
}

// Save updated execution times safely
file_put_contents($logFile, json_encode($lastRuns, JSON_PRETTY_PRINT));

echo "✅ Cron jobs executed successfully on $domain!";
?>
