<?php
// File: fifa_worldcup.php (tanpa autentikasi)

header('Content-Type: text/plain');

// ====================================================================
// --- Konfigurasi ---
// ====================================================================

// Secret Key (Digunakan untuk generate token)
$SECRET_KEY = 'qtvbebek123';

// ====================================================================
// --- Fungsi Generate Token yang Kompatibel ---
// ====================================================================

function base64UrlEncode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function getClientIp() {
    $ip = '';
    $headers = [
        'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED',
        'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP',
        'HTTP_X_REAL_IP'
    ];
    
    foreach ($headers as $header) {
        if (!empty($_SERVER[$header])) {
            $ip = $_SERVER[$header];
            break;
        }
    }
    
    if (empty($ip)) {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
    }
    
    if (strpos($ip, ',') !== false) {
        $ips = explode(',', $ip);
        $ip = trim($ips[0]);
    }
    
    return $ip;
}

function getUserAgent() {
    return $_SERVER['HTTP_USER_AGENT'] ?? 'Mozilla/5.0 (Unknown)';
}

// Fungsi encode JWT yang kompatibel dengan validator
function encodeJWT($payload, $secret) {
    $header = [
        'typ' => 'JWT',
        'alg' => 'HS256'
    ];
    
    $encodedHeader = base64UrlEncode(json_encode($header));
    $encodedPayload = base64UrlEncode(json_encode($payload));
    
    $signature = hash_hmac('sha256', $encodedHeader . '.' . $encodedPayload, $secret, true);
    $encodedSignature = base64UrlEncode($signature);
    
    return $encodedHeader . '.' . $encodedPayload . '.' . $encodedSignature;
}

function generateToken($secretKey) {
    $timestamp = time();
    $expiration = $timestamp + (150 * 60); // 150 menit
    
    $clientIp = getClientIp();
    $userAgent = getUserAgent();
    
    $payload = [
        'iat' => $timestamp,
        'exp' => $expiration,
        'ip' => $clientIp,
        'ua' => base64UrlEncode($userAgent),
        'iss' => 'qtv_service'
    ];
    
    return encodeJWT($payload, $secretKey);
}

// ====================================================================
// --- Fungsi FIFA World Cup Data Fetching ---
// ====================================================================

function fetchFifaWorldCupData() {
    // Set timezone ke WIB
    date_default_timezone_set('Asia/Jakarta');

    $url = "https://www.plus.fifa.com/entertainment/api/v1/showcases/bf0328f5-5a10-41bd-9475-0878fccb34a1/child?limit=50";

    $headers = [
        'x-chili-device-id: eyJhbGciOiJIUzI1NiIsImtpZCI6IjU5NWUyMGJkLWFmMDMtNDVjYi1iMDY1LWVhOTAxYmQwYTU2YiIsInR5cCI6IkpXVCJ9.eyJjcmVhdGVkX2F0IjoiMjAyNS0wNi0xNFQxOToxMDowMy41MTE0NjU4MVoiLCJkaXNwbGF5X25hbWUiOiJcdTAwM2NuaWxcdTAwM2UiLCJpZCI6Ijg0ODg3NWY3LWIzNzYtNDQ1Ni05OTA2LTNjZjI5OTNhMTI4YyIsIm1hbnVmYWN0dXJlciI6Ikdvb2dsZSBJbmMuIiwibW9kZWwiOiJDaHJvbWUiLCJwcm9maWxlIjoiV0VCIn0.xolFFXPmtM9dQ3BQv6eCpAxI4WfNgklRB7EWsSzrrv0',
        'x-chili-device-profile: WEB',
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if (curl_error($ch)) {
        return ['error' => 'Curl error: ' . curl_error($ch)];
    }

    curl_close($ch);

    if ($httpCode === 200 && !empty($response)) {
        $data = json_decode($response, true);
        
        if (json_last_error() === JSON_ERROR_NONE && is_array($data)) {
            return ['success' => true, 'data' => $data];
        } else {
            return ['error' => 'Error decoding JSON response'];
        }
    } else {
        return ['error' => 'HTTP Error: ' . $httpCode];
    }
}

function generateM3UContent($fifaData) {
    if (isset($fifaData['error'])) {
        return "#EXTM3U\n#EXTINF:-1,Error: " . $fifaData['error'] . "\nhttps://example.com\n";
    }

    if (!isset($fifaData['success']) || !$fifaData['success']) {
        return "#EXTM3U\n#EXTINF:-1,No data available\nhttps://example.com\n";
    }

    $content = "#EXTM3U\n";
    
    $liveMatches = [];
    $upcomingMatches = [];
    $currentTime = time();
    
    // Pisahkan match berdasarkan status
    foreach ($fifaData['data'] as $match) {
        if (isset($match['id'], $match['title'], $match['wideCoverUrl'], $match['contentStartDate'])) {
            
            $startTime = strtotime($match['contentStartDate']);
            $endTime = strtotime($match['contentEndDate']);
            
            // Cek status match
            if ($currentTime >= $startTime && $currentTime <= $endTime) {
                $match['status'] = 'LIVE';
                $liveMatches[] = $match;
            } elseif ($currentTime < $startTime) {
                $match['status'] = 'UPCOMING';
                $upcomingMatches[] = $match;
            }
        }
    }
    
    // Generate token untuk URL
    $token = generateToken($GLOBALS['SECRET_KEY']);
    
    // Output LIVE matches
    if (!empty($liveMatches)) {
        $content .= "\n#EXTINF:-1 group-title=\"🔴 LIVE WorldCup U-17\" tvg-logo=\"https://i.ibb.co/1r8L7yH/live.png\",=== 🔴 LIVE MATCHES ===\n";
        $content .= "#https://example.com\n";
        
        foreach ($liveMatches as $match) {
            $startTimeFormatted = date('d/m H:i', strtotime($match['contentStartDate']));
            
            $content .= "#KODIPROP:inputstream.adaptive.license_type=com.widevine.alpha\n";
            $content .= "#KODIPROP:inputstream.adaptive.license_key=https://qtv.my.id/tv_baru/fifap/drm2.php?id={$match['id']}&token=" . $token . "\n";
            $content .= "#EXTINF:-1 group-logo=\"http://qtv.my.id/glogo/fifawc25.png\" group-title=\"🔴 LIVE WorldCup U-17\" tvg-id=\"\" tvg-logo=\"{$match['wideCoverUrl']}\",🔴 LIVE | {$match['title']} | {$startTimeFormatted} WIB\n";
            $content .= "http://qtv.my.id/tv_baru/vidio/fifa.mpd?id={$match['id']}&token=" . $token . "&type=dash\n\n";
        }
    }
    
    // Output UPCOMING matches
    if (!empty($upcomingMatches)) {
        $content .= "\n#EXTINF:-1 group-title=\"📅 Event Upcoming\" tvg-logo=\"https://i.ibb.co/0j7W8y3/upcoming.png\",=== ⏰ UPCOMING MATCHES ===\n";
        $content .= "#https://example.com\n";
        
        foreach ($upcomingMatches as $match) {
            $startTimeFormatted = date('d/m H:i', strtotime($match['contentStartDate']));
            
            $content .= "#KODIPROP:inputstream.adaptive.license_type=com.widevine.alpha\n";
            $content .= "#KODIPROP:inputstream.adaptive.license_key=https://qtv.my.id/tv_baru/fifap/drm2.php?id={$match['id']}&token=" . $token . "\n";
            $content .= "#EXTINF:-1 group-logo=\"http://qtv.my.id/glogo/fifawc25.png\" group-title=\"📅 Event Upcoming\" tvg-id=\"\" tvg-logo=\"{$match['wideCoverUrl']}\",{$match['title']} | {$startTimeFormatted} WIB\n";
            $content .= "http://qtv.my.id/tv_baru/vidio/fifa.mpd?id={$match['id']}&token=" . $token . "&type=dash\n\n";
        }
    }
    
    if (empty($liveMatches) && empty($upcomingMatches)) {
        $content .= "#EXTINF:-1 group-title=\"📅 Event Upcoming\",No matches available\n";
        $content .= "https://example.com\n";
    }
    
    return $content;
}

// ====================================================================
// --- Eksekusi Utama ---
// ====================================================================

// Ambil data FIFA World Cup
$fifaData = fetchFifaWorldCupData();

// Generate konten M3U
$m3uContent = generateM3UContent($fifaData);

// Tampilkan hasil
echo $m3uContent;
?>