<?php
// File: purge-homepage-cron.php
// Purpose: Cloudflare homepage purge for Satta Matka site (CLI & Browser Friendly)

// ==================== CONFIG ====================
define('CLOUDFLARE_API_TOKEN', 'zF6IwBW48ak9nTGA_RnY777XA_CbQO6sa3Cvy_PN'); // Cloudflare API Token
define('CLOUDFLARE_ZONE_ID', '420575ba8587c1f7eb7886aa714d907b');     // Cloudflare Zone ID
define('HOMEPAGE_URL', 'https://matkaboss.life/');                      // Homepage URL
define('LOG_FILE', __DIR__ . '/cloudflare-purge.log');                  // Log file path
// =================================================

// Optional warning for web users
if (php_sapi_name() !== 'cli') {
    echo "<strong>Notice:</strong> Running via web browser. Check log for results.<br>";
}

// Function to purge homepage cache
function purge_homepage($zone, $token, $url) {
    if (!function_exists('curl_init')) {
        return ['ok' => false, 'error' => 'cURL extension missing'];
    }

    $api_url = "https://api.cloudflare.com/client/v4/zones/{$zone}/purge_cache";
    $payload = json_encode(['files' => [$url]]);

    $ch = curl_init($api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);

    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $errno = curl_errno($ch);
    curl_close($ch);

    if ($errno) return ['ok' => false, 'error' => "cURL error code: $errno"];
    $json = json_decode($response, true);
    return ['ok' => ($http_code >= 200 && $http_code < 300 && ($json['success'] ?? false)), 'http_code' => $http_code, 'response' => $json];
}

// Execute purge
$result = purge_homepage(CLOUDFLARE_ZONE_ID, CLOUDFLARE_API_TOKEN, HOMEPAGE_URL);

// Prepare log line
$log_line = date('Y-m-d H:i:s') . " - " . json_encode($result, JSON_UNESCAPED_SLASHES) . "\n";

// Write log
if (!file_put_contents(LOG_FILE, $log_line, FILE_APPEND)) {
    if (php_sapi_name() !== 'cli') {
        echo "<strong>Error:</strong> Unable to write log. Check file permissions.<br>";
    } else {
        echo "Error: Unable to write log. Check file permissions.\n";
    }
}

// Output result
if (php_sapi_name() === 'cli') {
    echo $log_line;
} else {
    echo "<pre>" . htmlspecialchars($log_line) . "</pre>";
}

exit;
?>
