<?php
// WordPress'i yükle (direkt erişim için)
$wp_load_path = '../../../../../wp-load.php';
if (file_exists($wp_load_path)) {
    require_once($wp_load_path);
} else {
    // Dinamik olarak WordPress kök dizinini bulmaya çalış
    $dir = dirname(__FILE__);
    do {
        if (file_exists($dir . '/wp-load.php')) {
            require_once($dir . '/wp-load.php');
            break;
        }
    } while ($dir = dirname($dir));
}

// WordPress yüklü değilse çık
if (!defined('ABSPATH')) {
    die('WordPress yüklenemedi. Bu dosyaya direkt erişim yasak.');
}

// API sabitleri tanımlı değilse hata ver
if (!defined('KAN_API_URL') || !defined('KAN_API_KEY')) {
    error_log('Kanews API: API URL veya KEY tanımlı değil');
    return;
}

/**
 * Sports Data Fetcher
 * Fetches and saves league standings data from a single API source
 */

// Single API endpoint for all leagues
$apiEndpoint = 'https://api-three-chi-43.vercel.app/api/sports';

// League IDs to fetch
$leagueIds = [
    // Soccer leagues
    'super-lig',
    'sampiyonlar-ligi',
    'avrupa-ligi',
    'konferans-ligi',
    'almanya-bundesliga',
    'ingiltere-premier-ligi',
    'italya-serie-a',
    'fransa-ligue-1',
    'tff-1-lig',
    'ispanya-la-liga',
    
    // Volleyball leagues
    'efeler-ligi',
    'sultanlar-ligi',
    
    // Basketball leagues
    'erkek-basketbol',
    'euroleague',
    'kadin-basketbol'
];

// Common headers for all requests
$commonHeaders = [
    'Content-Type: application/json',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36'
];

/**
 * Check if a string is valid JSON
 * 
 * @param string $raw_json The JSON string to validate
 * @return bool True if valid JSON, false otherwise
 */
function is_valid_json($raw_json) {
    return (json_decode($raw_json, true) == NULL) ? false : true;
}

/**
 * Ensure directory exists and is writable
 * 
 * @param string $dir Directory path
 * @return bool True if directory exists and is writable, false otherwise
 */
function ensure_directory_exists($dir) {
    if (!file_exists($dir)) {
        return mkdir($dir, 0755, true);
    }
    return is_writable($dir);
}

/**
 * Fetch data for a specific league and save to file
 * 
 * @param string $leagueId The ID of the league
 * @return void
 */
function fetchLeagueData($leagueId) {
    global $commonHeaders;
    
    // Create the full URL with query parameters
    $url = KAN_API_URL . '/sports/?api_key='.KAN_API_KEY;
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com.tr');
    
    // Set up headers
    curl_setopt($ch, CURLOPT_HTTPHEADER, $commonHeaders);
    
    // Set request method to GET
    curl_setopt($ch, CURLOPT_HTTPGET, true);
    
    // Execute request
    $result = curl_exec($ch);
    
    // Debug information
    $debug_info = [
        'league' => $leagueId,
        'url' => $url,
        'curl_error' => curl_error($ch),
        'curl_errno' => curl_errno($ch),
        'http_code' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
        'is_valid_json' => is_valid_json($result),
        'result_length' => strlen($result)
    ];
    
    // Save data if successful
    if (!curl_errno($ch) && is_valid_json($result)) {
        // Process the response to match the expected format
        $response = json_decode($result, true);
        
        // Check if the response has the expected structure
        if (isset($response[$leagueId]['initialData'])) {
            // Get theme directory for saving files
            $theme_dir = get_template_directory();
            $json_dir = $theme_dir . '/inc/api/standings';
            $json_file = $json_dir . '/' . $leagueId . '.json';
            
            // Ensure directory exists
            if (!ensure_directory_exists($json_dir)) {
                error_log('Kanews Standings API Error: Directory not writable - ' . $json_dir);
                echo "Hata: Dizin yazılabilir değil: " . $json_dir . "<br>";
                return;
            }
            
            // Save the processed data
            $write_result = file_put_contents($json_file, json_encode($response[$leagueId]));
            
            if ($write_result === false) {
                // Detailed error checking
                $error = error_get_last();
                error_log('Kanews Standings API Error: File write failed - ' . json_encode([
                    'path' => $json_file,
                    'error' => $error,
                    'writable' => is_writable(dirname($json_file))
                ]));
                echo "Hata: Dosya yazılamadı: " . $json_file . "<br>";
            } else {
                // Successfully written
                echo "Başarılı: " . $leagueId . " verisi kaydedildi. Dosya: " . $json_file . "<br>";
                
                if (defined('DOING_AJAX') && DOING_AJAX) {
                    wp_send_json_success(array(
                        'message' => 'Lig verileri güncellendi',
                        'league' => $leagueId,
                        'bytes_written' => $write_result,
                        'file_path' => $json_file,
                        'timestamp' => current_time('mysql')
                    ));
                }
            }
        } else {
            error_log('Kanews Standings API Error: Invalid data format for ' . $leagueId);
            echo "Hata: " . $leagueId . " için geçersiz veri formatı<br>";
        }
    } else {
        error_log('Kanews Standings API Error: ' . json_encode($debug_info));
        echo "Hata: " . $leagueId . " verisi alınamadı. Detaylar: " . json_encode($debug_info) . "<br>";
    }
    
    curl_close($ch);
}

// Fetch data for all leagues
foreach ($leagueIds as $leagueId) {
    fetchLeagueData($leagueId);
}

// If not AJAX, show completion message
if (!defined('DOING_AJAX') || !DOING_AJAX) {
    echo "Tüm lig verileri güncellendi. Zaman: " . current_time('mysql');
}