<?php
session_start();
include __DIR__ . '/config.php';
include __DIR__ . '/logger.php';

if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: index.php');
    exit;
}

event_log('view', 'Oyun Çek sayfası görüntülendi', ['admin' => $_SESSION['admin_user'] ?? 'unknown']);
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Oyun Çek | Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <?php include __DIR__ . '/sidebar.php'; ?>

        <div class="col-md-10 p-4">
            <?php include __DIR__ . '/topbar.php'; ?>

            <div class="d-flex align-items-center mb-3">
                <h2 class="mb-0">Oyun Çek</h2>
                <span class="ms-2 badge bg-secondary">API'den oyunları veritabanına al</span>
            </div>

            <div class="card mb-3">
                <div class="card-body">
                    <p class="text-muted">Butona bastığınızda arka planda <code>oyuncek.php</code> tetiklenecek ve yeni oyunlar çekilmeye çalışılacaktır. Çıktı aşağıda gösterilir.</p>

                    <div class="row g-3 align-items-end">
                        <div class="col-auto d-flex gap-2">
                            <button id="fetchBtn" class="btn btn-primary">
                                <i class="bi bi-download"></i> Oyunları Çek
                            </button>
                            <button id="cancelBtn" class="btn btn-outline-warning" disabled>
                                <i class="bi bi-x-circle"></i> İptal Et
                            </button>
                            <button id="clearBtn" class="btn btn-outline-secondary">
                                <i class="bi bi-trash"></i> Çıktıyı Temizle
                            </button>
                        </div>
                        <div class="col-auto form-check">
                            <input class="form-check-input" type="checkbox" id="toggleRaw" checked>
                            <label class="form-check-label" for="toggleRaw">Ham çıktıyı göster</label>
                        </div>
                        <div class="col-auto d-flex gap-2">
                            <button id="copyBtn" class="btn btn-outline-light btn-sm" disabled>
                                <i class="bi bi-clipboard"></i> Kopyala
                            </button>
                            <button id="downloadBtn" class="btn btn-outline-light btn-sm" disabled>
                                <i class="bi bi-file-earmark-arrow-down"></i> İndir (HTML)
                            </button>
                        </div>
                    </div>

                    <div class="mt-3 small text-muted" id="status">Hazır</div>
                    <div class="progress my-2 d-none" id="progressWrap" style="height: 6px;">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 100%"></div>
                    </div>

                    <div class="row g-3 mt-2" id="summaryRow" style="display:none;">
                        <div class="col-auto">
                            <div class="badge bg-success" id="sumNew">Yeni: 0</div>
                        </div>
                        <div class="col-auto">
                            <div class="badge bg-secondary" id="sumExisting">Mevcut: 0</div>
                        </div>
                        <div class="col-auto">
                            <div class="badge bg-info text-dark" id="sumTotal">Toplam: 0</div>
                        </div>
                        <div class="col-auto">
                            <div class="badge bg-dark" id="sumDuration">Süre: 0.0 sn</div>
                        </div>
                        <div class="col-12">
                            <div class="small text-muted" id="lastRun">Son çalıştırma: -</div>
                        </div>
                    </div>

 <div id="result" class="border rounded p-3 mt-2" style="min-height: 200px; background: var(--surface); color: var(--text); overflow:auto;"></div>
                </div>
            </div>

            <div class="alert alert-info mt-3">
                <div class="fw-bold">İpucu</div>
                <ul class="mb-0">
                    <li>İşlem birkaç saniye sürebilir. Lütfen bekleyin.</li>
                    <li>Tekrar çalıştırmadan önce çıktıyı temizleyebilirsiniz.</li>
                </ul>
            </div>

            <!-- Görsel Aynalama -->
            <div class="card mt-4">
                <div class="card-body">
                    <div class="d-flex align-items-center mb-2">
                        <h4 class="mb-0">Görselleri İndir ve Lokalize Et</h4>
                        <span class="ms-2 badge bg-secondary">cover/banner URL'lerini yerel dosyalara taşır</span>
                    </div>
                    <div class="row g-3 align-items-end">
                        <div class="col-auto">
                            <label for="imgLimit" class="form-label">Limit</label>
                            <input id="imgLimit" type="number" min="1" value="50" class="form-control" style="width:120px;">
                        </div>
                        <div class="col-auto">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="imgCover" checked>
                                <label class="form-check-label" for="imgCover">Cover</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="imgBanner" checked>
                                <label class="form-check-label" for="imgBanner">Banner</label>
                            </div>
                        </div>
                        <div class="col-auto">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="imgDry">
                                <label class="form-check-label" for="imgDry">Dry-run (yazma yok)</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="imgForce">
                                <label class="form-check-label" for="imgForce">Force (varsa yeniden indir)</label>
                            </div>
                        </div>
                        <div class="col-auto">
                            <label for="imgCc" class="form-label">Eşzamanlı (cc)</label>
                            <input id="imgCc" type="number" min="1" max="12" value="8" class="form-control" style="width:120px;">
                        </div>
                        <div class="col-auto d-flex gap-2">
                            <button id="imgRunBtn" class="btn btn-primary">
                                <i class="bi bi-image"></i> Görselleri İşle
                            </button>
                            <button id="imgClearBtn" class="btn btn-outline-secondary">
                                <i class="bi bi-trash"></i> Çıktıyı Temizle
                            </button>
                        </div>
                    </div>

                    <div class="mt-3 small text-muted" id="imgStatus">Hazır</div>
                    <div class="progress my-2 d-none" id="imgProgress" style="height: 6px;">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 100%"></div>
                    </div>
 <div id="imgResult" class="border rounded p-3 mt-2" style="height: 200px; background: var(--surface); color: var(--text); overflow:auto;"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const fetchBtn = document.getElementById('fetchBtn');
    const cancelBtn = document.getElementById('cancelBtn');
    const clearBtn = document.getElementById('clearBtn');
    const copyBtn = document.getElementById('copyBtn');
    const downloadBtn = document.getElementById('downloadBtn');
    const toggleRaw = document.getElementById('toggleRaw');
    const resultEl = document.getElementById('result');
    const statusEl = document.getElementById('status');
    const progressWrap = document.getElementById('progressWrap');
    const summaryRow = document.getElementById('summaryRow');
    const sumNew = document.getElementById('sumNew');
    const sumExisting = document.getElementById('sumExisting');
    const sumTotal = document.getElementById('sumTotal');
    const sumDuration = document.getElementById('sumDuration');
    const lastRun = document.getElementById('lastRun');

    let controller = null;
    let lastText = '';

    function resetUI() {
        statusEl.textContent = 'Hazır';
        resultEl.innerHTML = '';
        progressWrap.classList.add('d-none');
        summaryRow.style.display = 'none';
        copyBtn.disabled = true;
        downloadBtn.disabled = true;
    }

    function setInProgress() {
        progressWrap.classList.remove('d-none');
        statusEl.textContent = 'Oyun çekme başlatıldı...';
        fetchBtn.disabled = true;
        cancelBtn.disabled = false;
        fetchBtn.classList.add('disabled');
    }

    function setDone(ok, message) {
        progressWrap.classList.add('d-none');
        fetchBtn.disabled = false;
        cancelBtn.disabled = true;
        fetchBtn.classList.remove('disabled');
        statusEl.textContent = ok ? (message || 'Tamamlandı') : (message || 'Hata');
    }

    function parseSummaryFromHtml(htmlText) {
        const doc = new DOMParser().parseFromString(htmlText, 'text/html');
        const getNum = (label) => {
            const p = Array.from(doc.querySelectorAll('p')).find(el => el.textContent.includes(label));
            if (!p) return 0;
            const m = p.textContent.match(/(\d+)/);
            return m ? parseInt(m[1], 10) : 0;
        };
        const newCount = getNum('Yeni eklenen oyun sayısı');
        const existingCount = getNum('Zaten veritabanında bulunan oyunlar');
        const total = getNum('Toplam işlenen oyun');
        let newGames = [];
        const h4 = Array.from(doc.querySelectorAll('h4')).find(h => h.textContent.toLowerCase().includes('yeni eklenen oyunlar'));
        if (h4) {
            const ul = h4.nextElementSibling && h4.nextElementSibling.tagName === 'UL' ? h4.nextElementSibling : null;
            if (ul) newGames = Array.from(ul.querySelectorAll('li')).map(li => li.textContent.trim());
        }
        return { newCount, existingCount, total, newGames };
    }

    async function runFetch() {
        resetUI();
        setInProgress();
        controller = new AbortController();
        const started = performance.now();
        try {
            const resp = await fetch('../oyuncek.php', { method: 'GET', headers: { 'X-Requested-With': 'fetch' }, signal: controller.signal });
            const text = await resp.text();
            lastText = text;
            if (toggleRaw.checked) {
                resultEl.innerHTML = text;
            } else {
                resultEl.textContent = '[Ham çıktı gizlendi]';
            }
            // Summary parse
            const { newCount, existingCount, total } = parseSummaryFromHtml(text);
            sumNew.textContent = `Yeni: ${newCount}`;
            sumExisting.textContent = `Mevcut: ${existingCount}`;
            sumTotal.textContent = `Toplam: ${total}`;
            const seconds = ((performance.now() - started) / 1000).toFixed(1);
            sumDuration.textContent = `Süre: ${seconds} sn`;
            lastRun.textContent = `Son çalıştırma: ${new Date().toLocaleString()}`;
            summaryRow.style.display = '';
            copyBtn.disabled = false;
            downloadBtn.disabled = false;
            setDone(resp.ok, resp.ok ? 'Tamamlandı' : `Hata: ${resp.status}`);
        } catch (e) {
            if (e.name === 'AbortError') {
                setDone(false, 'İşlem iptal edildi');
            } else {
                setDone(false, 'İstek hatası: ' + e.message);
            }
        } finally {
            controller = null;
        }
    }

    clearBtn.addEventListener('click', resetUI);
    fetchBtn.addEventListener('click', runFetch);
    cancelBtn.addEventListener('click', () => {
        if (controller) controller.abort();
    });
    toggleRaw.addEventListener('change', () => {
        if (!lastText) return;
        if (toggleRaw.checked) {
            resultEl.innerHTML = lastText;
        } else {
            resultEl.textContent = '[Ham çıktı gizlendi]';
        }
    });
    copyBtn.addEventListener('click', async () => {
        if (!lastText) return;
        try {
            await navigator.clipboard.writeText(lastText);
            statusEl.textContent = 'Çıktı panoya kopyalandı';
        } catch (_) {
            statusEl.textContent = 'Kopyalama başarısız';
        }
    });
    downloadBtn.addEventListener('click', () => {
        if (!lastText) return;
        const blob = new Blob([lastText], { type: 'text/html;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'oyuncek_cikti.html';
        a.click();
        URL.revokeObjectURL(url);
    });

    // Görsel aynalama
    const imgRunBtn = document.getElementById('imgRunBtn');
    const imgClearBtn = document.getElementById('imgClearBtn');
    const imgStatus = document.getElementById('imgStatus');
    const imgResult = document.getElementById('imgResult');
    const imgProgress = document.getElementById('imgProgress');
    const imgLimit = document.getElementById('imgLimit');
    const imgCover = document.getElementById('imgCover');
    const imgBanner = document.getElementById('imgBanner');
    const imgDry = document.getElementById('imgDry');
    const imgForce = document.getElementById('imgForce');
    const imgCc = document.getElementById('imgCc');

    function imgReset() {
        imgStatus.textContent = 'Hazır';
        imgResult.innerHTML = '';
        imgProgress.classList.add('d-none');
    }
    imgClearBtn.addEventListener('click', imgReset);
    imgRunBtn.addEventListener('click', async () => {
        imgProgress.classList.remove('d-none');
        imgStatus.textContent = 'Görseller işleniyor...';
        imgResult.innerHTML = '';
        imgRunBtn.disabled = true;
        try {
            const cols = [imgCover.checked ? 'cover' : null, imgBanner.checked ? 'banner' : null].filter(Boolean).join(',');
            const params = new URLSearchParams({
                limit: String(Math.max(1, parseInt(imgLimit.value || '50', 10))),
                cols,
                dry: imgDry.checked ? '1' : '0',
                force: imgForce.checked ? '1' : '0',
                cc: String(Math.max(1, Math.min(12, parseInt(imgCc.value || '8', 10))))
            });
            const resp = await fetch(`api/mirror_images.php?${params.toString()}`, { headers: { 'X-Requested-With': 'fetch' } });
            if (!resp.ok) {
                throw new Error(`HTTP ${resp.status}`);
            }
            // Akışlı okuma: parça parça gelen HTML'i hemen göster
            const reader = resp.body?.getReader();
            const decoder = new TextDecoder('utf-8');
            if (!reader) {
                // Tarayıcı akışı desteklemiyorsa fallback: tüm metni al
                const html = await resp.text();
                imgResult.innerHTML = html;
            } else {
                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;
                    const chunk = decoder.decode(value, { stream: true });
                    if (chunk) {
                        imgResult.insertAdjacentHTML('beforeend', chunk);
                        imgResult.scrollTop = imgResult.scrollHeight;
                    }
                }
            }
            imgStatus.textContent = 'Tamamlandı';
        } catch (e) {
            imgStatus.textContent = 'İstek hatası: ' + e.message;
        } finally {
            imgRunBtn.disabled = false;
            imgProgress.classList.add('d-none');
        }
    });
});
</script>
</body>
</html>