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

// === AUTO CREATE LOG FOLDER AND FILE ===
$logDir = __DIR__ . '/logs';
$logFile = $logDir . '/cron_log.txt';

// Create logs directory if not exists
if (!is_dir($logDir)) {
    mkdir($logDir, 0755, true);
}

// Create or open log file for appending
$logHandle = fopen($logFile, 'a');
if (!$logHandle) {
    die("❌ Failed to open log file.\n");
}

// Helper function to log output
function logMsg($msg) {
    global $logHandle;
    $timestamp = date('[Y-m-d H:i:s]');
    fwrite($logHandle, "$timestamp $msg\n");
    echo "$timestamp $msg\n"; // Optional: remove this if you only want file logging
}

// === START LOGGING ===
logMsg("🔄 Cron started");

require_once __DIR__ . '/src/Database.php';
$mysqli = Database::getInstance();

$clientId = 'app.6814bcb5627763.66194477';
$clientSecret = 'RMsbzWZSuGq7t98LVA0WgrgoHnyXv1ZPsY3VYaYUOJ32nej2up';

// Get all rows from bitrix24_token table
$sql = "SELECT * FROM bitrix24_token";
$result = $mysqli->query($sql);

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $domain = $row['domain'];
        $refreshToken = $row['refresh_token'];

        // Refresh token API URL
        $refreshUrl = "https://oauth.bitrix.info/oauth/token/?" . http_build_query([
            'grant_type' => 'refresh_token',
            'client_id' => $clientId,
            'client_secret' => $clientSecret,
            'refresh_token' => $refreshToken
        ]);

        // Call Bitrix24 token refresh API
        $response = file_get_contents($refreshUrl);

        if ($response === false) {
            logMsg("❌ HTTP request failed for domain: $domain");
            continue;
        }

        $data = json_decode($response, true);

        if (isset($data['access_token']) && isset($data['refresh_token'])) {
            $newAccessToken = $data['access_token'];
            $newRefreshToken = $data['refresh_token'];

            $update = $mysqli->prepare("UPDATE bitrix24_token SET acsess_token = ?, refresh_token = ? WHERE domain = ?");
            if ($update) {
                $update->bind_param("sss", $newAccessToken, $newRefreshToken, $domain);
                $update->execute();
                logMsg("✅ Updated tokens for domain: $domain");
            } else {
                logMsg("❌ Failed to prepare update statement for domain: $domain");
            }
        } else {
            logMsg("❌ Failed to refresh token for domain: $domain");
            logMsg("Response: " . print_r($data, true));
        }
    }
} else {
    logMsg("ℹ️ No tokens found in the table or query failed.");
}

$mysqli->close();
logMsg("✅ Cron finished");

// Close log file
fclose($logHandle);
?>
