<?php

define('GITHUB_TOKEN', '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');
define('GITHUB_OWNER', 'Ameer0011');
define('GITHUB_REPO', 'bluesport');
define('FILE_PATH', 'data/api.json');
define('BRANCH', 'main');

// ✅ روابط القنوات محددة مسبقاً (بدون إدخال يدوي)
$CHANNELS = [
    1 => ['name' => 'BLUE SPORT 1', 'url' => 'https://bluesport.fun/live/blue_sport_1/index.m3u8'],
    2 => ['name' => 'BLUE SPORT 2', 'url' => 'https://bluesport.fun/live/blue_sport_2/index.m3u8'],
    3 => ['name' => 'BLUE SPORT 3', 'url' => 'https://bluesport.fun/live/blue_sport_3/index.m3u8'],
];

function github_get_file() {
    $url = "https://api.github.com/repos/" . GITHUB_OWNER . "/" . GITHUB_REPO . "/contents/" . FILE_PATH;
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: token " . GITHUB_TOKEN,
            "User-Agent: PHP"
        ]
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

function github_update_file($content, $sha) {
    $url = "https://api.github.com/repos/" . GITHUB_OWNER . "/" . GITHUB_REPO . "/contents/" . FILE_PATH;
    $data = [
        "message" => "update streams",
        "content" => base64_encode($content),
        "sha" => $sha,
        "branch" => BRANCH
    ];
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => "PUT",
        CURLOPT_HTTPHEADER => [
            "Authorization: token " . GITHUB_TOKEN,
            "User-Agent: PHP",
            "Content-Type: application/json"
        ],
        CURLOPT_POSTFIELDS => json_encode($data)
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

function extract_streams($m3u8, $baseUrl) {
    $streams = [];
    preg_match_all('/RESOLUTION=(\d+x\d+).*?\n(.*?)($|\n)/s', $m3u8, $matches, PREG_SET_ORDER);
    foreach ($matches as $item) {
        $res = explode('x', $item[1]);
        $height = (int)$res[1];
        $url = trim($item[2]);
        if (strpos($url, 'http') !== 0) {
            $url = $baseUrl . $url;
        }
        if ($height == 1080) $label = "1080p";
        elseif ($height == 720) $label = "720p";
        elseif ($height == 480) $label = "480p";
        elseif ($height == 320) $label = "360p";
        else $label = $height . "p";
        $streams[] = ["label" => $label, "url" => $url];
    }
    return $streams;
}

$message = "";
$error = "";

if (isset($_POST['update_channel'])) {
    $channel_id = (int)$_POST['channel_id'];
    
    // التحقق من صحة القناة
    if (!isset($CHANNELS[$channel_id])) {
        $error = "قناة غير صالحة";
    } else {
        // ✅ الرابط يتم تعبئته تلقائياً من المصفوفة أعلاه
        $url = $CHANNELS[$channel_id]['url'];
        $channel_name = $CHANNELS[$channel_id]['name'];
        
        // جلب ملف M3U8
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_USERAGENT => 'Mozilla/5.0',
            CURLOPT_TIMEOUT => 30
        ]);
        
        $m3u8 = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
        curl_close($ch);
        
        if ($httpCode !== 200 || !$m3u8) {
            $error = "فشل في جلب ملف M3U8 للقناة: $channel_name (HTTP $httpCode)";
        } else {
            $parts = parse_url($finalUrl);
            $baseUrl = $parts['scheme'] . "://" . $parts['host'];
            $streams = extract_streams($m3u8, $baseUrl);
            
            // إضافة خيار AUTO
            $auto = ["label" => "AUTO", "url" => $finalUrl];
            array_unshift($streams, $auto);
            
            // تحديث ملف GitHub
            $file = github_get_file();
            if (!$file || !isset($file['content'])) {
                $error = "خطأ في تحميل ملف api.json من GitHub";
            } else {
                $json = json_decode(base64_decode($file['content']), true);
                if (!$json) {
                    $error = "خطأ في فك ترميز ملف api.json";
                } else {
                    $found = false;
                    foreach ($json['channels'] as &$channel) {
                        if ($channel['id'] == $channel_id) {
                            $channel['servers'] = $streams;
                            $found = true;
                            break;
                        }
                    }
                    if (!$found) {
                        $error = "لم يتم العثور على القناة بالرقم: $channel_id";
                    } else {
                        $newContent = json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
                        $update = github_update_file($newContent, $file['sha']);
                        $updateResult = json_decode($update, true);
                        if (isset($updateResult['content'])) {
                            $message = "✅ تم تحديث القناة $channel_name بنجاح ورفع البيانات إلى GitHub";
                        } else {
                            $error = "فشل رفع التحديث إلى GitHub: " . ($updateResult['message'] ?? 'خطأ غير معروف');
                        }
                    }
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>محدث قنوات Blue Sport</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            background: linear-gradient(135deg, #0f172a 0%, #1e1b4b 100%);
            color: #f1f5f9;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            min-height: 100vh;
            padding: 1.5rem;
        }
        .container { max-width: 600px; margin: 0 auto; }
        .header { text-align: center; margin-bottom: 2rem; padding: 1rem; }
        .header h1 {
            font-size: 1.8rem;
            background: linear-gradient(135deg, #38bdf8, #a78bfa);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            margin-bottom: 0.5rem;
        }
        .header p { color: #94a3b8; font-size: 0.9rem; }
        .card {
            background: rgba(30, 41, 59, 0.8);
            backdrop-filter: blur(10px);
            border-radius: 1.5rem;
            padding: 1.8rem;
            box-shadow: 0 20px 35px -10px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.05);
            margin-bottom: 1.5rem;
        }
        .channel-grid { display: flex; flex-direction: column; gap: 1rem; margin-bottom: 1.5rem; }
        .channel-option {
            background: rgba(15, 23, 42, 0.7);
            border-radius: 1rem;
            padding: 1rem;
            cursor: pointer;
            transition: all 0.2s ease;
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        .channel-option.selected { background: #1e293b; border-color: #3b82f6; }
        .channel-option:hover { background: #1e293b; transform: translateY(-2px); }
        .channel-info { display: flex; align-items: center; gap: 1rem; }
        .channel-icon {
            width: 48px; height: 48px;
            background: linear-gradient(135deg, #3b82f6, #8b5cf6);
            border-radius: 1rem;
            display: flex; align-items: center; justify-content: center;
            font-size: 1.5rem; font-weight: bold;
        }
        .channel-details { flex: 1; }
        .channel-name { font-size: 1.1rem; font-weight: 600; margin-bottom: 0.25rem; }
        .channel-url { font-size: 0.7rem; color: #64748b; word-break: break-all; }
        .radio-input {
            appearance: none; width: 20px; height: 20px;
            border: 2px solid #475569; border-radius: 50%;
            margin: 0; cursor: pointer;
        }
        .radio-input:checked { border-color: #3b82f6; background: #3b82f6; box-shadow: inset 0 0 0 4px #0f172a; }
        .update-btn {
            width: 100%; padding: 1rem;
            background: linear-gradient(135deg, #22c55e, #16a34a);
            border: none; border-radius: 1rem; color: white;
            font-size: 1.1rem; font-weight: 600; cursor: pointer;
            display: flex; align-items: center; justify-content: center; gap: 0.5rem;
        }
        .update-btn:hover { transform: scale(1.02); box-shadow: 0 10px 20px -5px rgba(34, 197, 94, 0.3); }
        .update-btn:active { transform: scale(0.98); }
        .update-btn:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }
        .message { padding: 1rem; border-radius: 1rem; margin-bottom: 1.5rem; font-size: 0.9rem; }
        .message.success { background: rgba(34, 197, 94, 0.15); border-right: 4px solid #22c55e; color: #4ade80; }
        .message.error { background: rgba(239, 68, 68, 0.15); border-right: 4px solid #ef4444; color: #f87171; }
        .loading { display: none; text-align: center; margin-top: 1rem; color: #94a3b8; }
        .loading.active { display: block; }
        .spinner {
            display: inline-block; width: 20px; height: 20px;
            border: 2px solid #3b82f6; border-top-color: transparent;
            border-radius: 50%; animation: spin 0.8s linear infinite;
            vertical-align: middle; margin-left: 8px;
        }
        @keyframes spin { to { transform: rotate(360deg); } }
        footer { text-align: center; font-size: 0.75rem; color: #475569; margin-top: 2rem; }
        @media (max-width: 480px) {
            body { padding: 1rem; }
            .card { padding: 1.2rem; }
            .channel-icon { width: 40px; height: 40px; font-size: 1.2rem; }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>🎬 Blue Sport Updater</h1>
        <p>اختر القناة وقم بتحديث روابط الجودات تلقائياً</p>
    </div>

    <?php if ($message): ?>
        <div class="message success"><?php echo htmlspecialchars($message); ?></div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="message error">⚠️ <?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <div class="card">
        <form method="POST" id="updateForm">
            <div class="channel-grid">
                <?php foreach ($CHANNELS as $id => $channel): ?>
                <label class="channel-option" data-channel-id="<?php echo $id; ?>">
                    <div class="channel-info">
                        <div class="channel-icon"><?php echo $id; ?></div>
                        <div class="channel-details">
                            <div class="channel-name"><?php echo htmlspecialchars($channel['name']); ?></div>
                            <div class="channel-url"><?php echo htmlspecialchars($channel['url']); ?></div>
                        </div>
                        <input type="radio" name="channel_id" value="<?php echo $id; ?>" class="radio-input" <?php echo ($id == 1) ? 'checked' : ''; ?>>
                    </div>
                </label>
                <?php endforeach; ?>
            </div>
            <button type="submit" name="update_channel" class="update-btn" id="submitBtn">
                <span>🔄</span> تحديث القناة المحددة
            </button>
            <div id="loading" class="loading">
                <div class="spinner"></div> جاري تحديث القناة...
            </div>
        </form>
    </div>
    <footer>يتم تحديث الجودات (AUTO, 1080p, 720p, 480p, 360p) من ملف M3U8 المباشر للقناة</footer>
</div>

<script>
    document.querySelectorAll('.channel-option').forEach(option => {
        const radio = option.querySelector('.radio-input');
        option.addEventListener('click', (e) => {
            if (e.target !== radio) radio.checked = true;
            document.querySelectorAll('.channel-option').forEach(opt => opt.classList.remove('selected'));
            option.classList.add('selected');
        });
        if (radio.checked) option.classList.add('selected');
    });
    
    document.getElementById('updateForm').addEventListener('submit', function(e) {
        if (!document.querySelector('input[name="channel_id"]:checked')) {
            e.preventDefault();
            alert('الرجاء اختيار قناة أولاً');
            return;
        }
        document.getElementById('submitBtn').disabled = true;
        document.getElementById('loading').classList.add('active');
    });
</script>
</body>
</html>