<?php
require 'config.php';
$ip = $_SERVER['REMOTE_ADDR'];
$endpoint = 'page.reports'; // ganti nama sesuai file
if (!checkRateLimitApi($pdo, $ip, $endpoint, 120, 60)) {
    http_response_code(429);
    die('<div style="text-align:center;padding:50px;"><h1>429 Too Many Requests</h1><p>Terlalu banyak permintaan. Silakan coba lagi setelah 1 menit.</p></div>');
}
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    header('Location: index.php');
    exit;
}
$adminName = $_SESSION['username'];
$defaultStoreUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan Harian - FIFA World Cup 2026</title>
    <meta name="csrf-token" content="<?php echo $_SESSION['csrf_token']; ?>">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap"
        rel="stylesheet">
    <style>
        body {
            background: #030610;
            font-family: 'Inter', sans-serif;
        }

        .glass-card {
            background: rgba(255, 255, 255, 0.02);
            backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.05);
            border-radius: 2rem;
            transition: all 0.3s;
        }

        .glass-card:hover {
            background: rgba(255, 255, 255, 0.04);
            border-color: rgba(255, 255, 255, 0.1);
        }

        .stat-number {
            font-size: 2rem;
            font-weight: 800;
            background: linear-gradient(135deg, #f59e0b, #ffcc00);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
        }

        .toast {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: #1e293b;
            backdrop-filter: blur(12px);
            border: 1px solid #f59e0b;
            border-radius: 2rem;
            padding: 0.75rem 1.5rem;
            color: white;
            z-index: 1000;
            font-weight: bold;
        }
    </style>
</head>

<body class="min-h-screen text-white">

    <nav class="sticky top-0 z-50 px-4 pt-4">
        <div class="max-w-7xl mx-auto glass-card rounded-[40px] px-5 sm:px-10 h-20 flex items-center justify-between">
            <div class="flex items-center gap-2 cursor-pointer" onclick="window.location.href='index.php'">
                <img src="fifa-world-cup-2026-logo-white.png" alt="Logo" class="h-10 w-auto">
                <span class="text-xs font-black text-white tracking-wider">WORLD CUP 2026</span>
            </div>
            <div class="flex items-center gap-4">
                <a href="admin_panel.php"
                    class="bg-white/10 px-4 py-2 rounded-full text-xs font-black hover:bg-white/20 transition">Admin
                    Panel</a>
                <a href="auth.php?action=logout"
                    class="bg-red-500/20 px-4 py-2 rounded-full text-xs font-black hover:bg-red-500/40">Logout</a>
            </div>
        </div>
    </nav>

    <main class="max-w-7xl mx-auto px-4 py-8">
        <div class="text-center mb-8">
            <h1 class="text-4xl md:text-6xl font-black uppercase tracking-tighter">Laporan <span
                    class="text-amber-500">Harian</span></h1>
            <p class="text-slate-400 text-sm mt-2">Generate & kelola laporan statistik harian turnamen dan pengguna</p>
        </div>

        <div class="glass-card p-6 rounded-3xl mb-8">
            <div class="flex flex-wrap gap-4 items-end">
                <div>
                    <label class="text-xs font-black text-slate-500 uppercase">Pilih Tanggal</label>
                    <input type="date" id="report-date"
                        class="bg-white/5 border border-white/10 rounded-xl px-4 py-2 text-white"
                        value="<?php echo date('Y-m-d'); ?>">
                </div>
                <div>
                    <label class="text-xs font-black text-slate-500 uppercase">Link Website (Nama Toko)</label>
                    <input type="url" id="store-name"
                        class="bg-white/5 border border-white/10 rounded-xl px-4 py-2 text-white"
                        placeholder="https://..." value="<?php echo htmlspecialchars($defaultStoreUrl); ?>">
                    <p class="text-[9px] text-slate-500 mt-1">* Akan disimpan sebagai link website toko</p>
                </div>
                <button id="generate-btn"
                    class="bg-amber-500 text-black px-6 py-2 rounded-xl text-sm font-black">Generate Laporan</button>
                <button id="refresh-btn"
                    class="bg-white/10 hover:bg-white/20 text-white px-6 py-2 rounded-xl text-sm font-black">Refresh</button>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <!-- Laporan Turnamen -->
            <div class="glass-card p-6 rounded-3xl">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-black text-white uppercase tracking-tight flex items-center gap-2">🏟️
                        Laporan Turnamen</h2>
                    <button id="export-tournament-csv"
                        class="bg-green-500/20 hover:bg-green-500/30 text-green-400 px-3 py-1 rounded-xl text-xs font-black flex items-center gap-1">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                        </svg>
                        Export CSV
                    </button>
                </div>
                <div id="tournament-report" class="space-y-4">
                    <div class="text-slate-400 text-center py-8">Pilih tanggal dan klik Generate atau Refresh</div>
                </div>
                <div class="mt-4">
                    <textarea id="tournament-notes" rows="3"
                        class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2 text-white placeholder-slate-500"
                        placeholder="Catatan tambahan..."></textarea>
                    <button id="save-tournament-notes"
                        class="mt-2 bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-4 py-2 rounded-xl text-xs font-black w-full">Simpan
                        Catatan</button>
                </div>
            </div>

            <!-- Laporan User -->
            <div class="glass-card p-6 rounded-3xl">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-black text-white uppercase tracking-tight flex items-center gap-2">👥
                        Laporan Pengguna</h2>
                    <button id="export-user-csv"
                        class="bg-green-500/20 hover:bg-green-500/30 text-green-400 px-3 py-1 rounded-xl text-xs font-black flex items-center gap-1">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                        </svg>
                        Export CSV
                    </button>
                </div>
                <div id="user-report" class="space-y-4">
                    <div class="text-slate-400 text-center py-8">Pilih tanggal dan klik Generate atau Refresh</div>
                </div>
                <div class="mt-4">
                    <textarea id="user-notes" rows="3"
                        class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2 text-white placeholder-slate-500"
                        placeholder="Catatan tambahan..."></textarea>
                    <button id="save-user-notes"
                        class="mt-2 bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-4 py-2 rounded-xl text-xs font-black w-full">Simpan
                        Catatan</button>
                </div>
            </div>
        </div>

        <div class="mt-8 text-center text-slate-500 text-xs">
            <p>Laporan turnamen berisi statistik ringkasan. Laporan pengguna menyertakan daftar user yang melakukan
                claim tiket, menggunakan poin, dan riwayat prediksi untuk pertandingan yang sudah selesai pada tanggal
                tersebut.</p>
        </div>
    </main>

    <div id="toast" class="toast hidden"></div>

    <script>
        const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
        let currentTournamentData = null;
        let currentUserData = null;

        function showToast(msg, isError = false) {
            const toast = document.getElementById('toast');
            toast.textContent = msg;
            toast.classList.remove('hidden', 'bg-red-600/90', 'bg-green-600/90');
            toast.classList.add(isError ? 'bg-red-600/90' : 'bg-green-600/90');
            setTimeout(() => toast.classList.add('hidden'), 4000);
        }

        async function loadReport(date) {
            try {
                const res = await fetch(`api.php?action=get_daily_report&date=${date}`, { headers: { 'X-CSRF-TOKEN': csrfToken } });
                const data = await res.json();
                currentTournamentData = data.tournament;
                currentUserData = data.user;
                renderTournamentReport(currentTournamentData);
                renderUserReport(currentUserData);
                document.getElementById('tournament-notes').value = currentTournamentData?.notes || '';
                document.getElementById('user-notes').value = currentUserData?.notes || '';
            } catch (err) {
                showToast('Gagal memuat laporan', true);
            }
        }

        function renderTournamentReport(data) {
            const container = document.getElementById('tournament-report');
            if (!data) {
                container.innerHTML = '<div class="text-slate-400 text-center py-8">Belum ada laporan untuk tanggal ini. Klik Generate.</div>';
                return;
            }
            const storeLink = data.store_name ? `<a href="${escapeHtml(data.store_name)}" target="_blank" class="text-amber-500 hover:underline break-all">${escapeHtml(data.store_name)}</a>` : '-';
            container.innerHTML = `
            <div class="grid grid-cols-2 gap-4">
                <div class="bg-white/5 rounded-xl p-4 text-center">
                    <div class="text-slate-400 text-xs uppercase">Total Register</div>
                    <div class="stat-number text-3xl">${data.total_register}</div>
                </div>
                <div class="bg-white/5 rounded-xl p-4 text-center">
                    <div class="text-slate-400 text-xs uppercase">Total Prediksi</div>
                    <div class="stat-number text-3xl">${data.total_predictions}</div>
                </div>
                <div class="bg-white/5 rounded-xl p-4 text-center">
                    <div class="text-slate-400 text-xs uppercase">Prediksi Grup</div>
                    <div class="stat-number text-3xl">${data.total_group_predictions || 0}</div>
                </div>
                <div class="bg-white/5 rounded-xl p-4 text-center">
                    <div class="text-slate-400 text-xs uppercase">Prediksi Knockout</div>
                    <div class="stat-number text-3xl">${data.total_knockout_predictions || 0}</div>
                </div>
                <div class="bg-white/5 rounded-xl p-4 text-center">
                    <div class="text-slate-400 text-xs uppercase">Claim Daily</div>
                    <div class="stat-number text-3xl">${data.total_claim_daily}</div>
                </div>
                <div class="bg-white/5 rounded-xl p-4 text-center">
                    <div class="text-slate-400 text-xs uppercase">Claim Kode Tiket</div>
                    <div class="stat-number text-3xl">${data.total_claim_ticket}</div>
                </div>
            </div>
            <div class="bg-white/5 rounded-xl p-4">
                <div class="text-amber-500 text-xs uppercase mb-1">Link Website (Nama Toko)</div>
                <div class="text-white break-all">${storeLink}</div>
            </div>
        `;
        }

        function renderUserReport(data) {
            const container = document.getElementById('user-report');
            if (!data) {
                container.innerHTML = '<div class="text-slate-400 text-center py-8">Belum ada laporan untuk tanggal ini. Klik Generate.</div>';
                return;
            }
            // Jika tidak ada data, tampilkan '0'
            const claimTicket = (data.users_claim_ticket && data.users_claim_ticket.trim() !== '') ? escapeHtml(data.users_claim_ticket) : '0';
            const usingPoint = (data.users_using_point && data.users_using_point.trim() !== '') ? escapeHtml(data.users_using_point) : '0';
            container.innerHTML = `
            <div class="bg-white/5 rounded-xl p-4">
                <div class="flex justify-between"><span class="text-slate-400">User Baru</span><span class="text-white font-bold">${data.new_users_count}</span></div>
            </div>
            <div class="bg-white/5 rounded-xl p-4">
                <div class="text-amber-500 text-xs uppercase mb-1">User Claim Kode Tiket</div>
                <div class="text-white text-sm break-words">${claimTicket}</div>
            </div>
            <div class="bg-white/5 rounded-xl p-4">
                <div class="text-amber-500 text-xs uppercase mb-1">User Menggunakan Poin</div>
                <div class="text-white text-sm break-words">${usingPoint}</div>
            </div>
            <div class="bg-white/5 rounded-xl p-4">
                <div class="text-amber-500 text-xs uppercase mb-1">Riwayat Prediksi (Pertandingan Selesai)</div>
                <div class="text-white text-xs whitespace-pre-wrap break-words max-h-60 overflow-y-auto">${data.prediction_history ? escapeHtml(data.prediction_history) : '-'}</div>
            </div>
        `;
        }

        async function generateReport(date, storeName) {
            const formData = new FormData();
            formData.append('date', date);
            formData.append('store_name', storeName);
            try {
                const res = await fetch('api.php?action=generate_daily_report', {
                    method: 'POST',
                    body: formData,
                    headers: { 'X-CSRF-TOKEN': csrfToken }
                });
                const result = await res.json();
                if (result.status === 'success') {
                    showToast('Laporan berhasil digenerate');
                    loadReport(date);
                } else {
                    showToast(result.error || 'Gagal generate laporan', true);
                }
            } catch (err) {
                showToast('Terjadi kesalahan jaringan', true);
            }
        }

        async function saveNotes(date, type, notes) {
            const formData = new FormData();
            formData.append('date', date);
            if (type === 'tournament') formData.append('tournament_notes', notes);
            else formData.append('user_notes', notes);
            try {
                const res = await fetch('api.php?action=update_report_notes', {
                    method: 'POST',
                    body: formData,
                    headers: { 'X-CSRF-TOKEN': csrfToken }
                });
                const result = await res.json();
                if (result.status === 'success') showToast('Catatan disimpan');
                else showToast(result.error || 'Gagal simpan catatan', true);
            } catch (err) {
                showToast('Terjadi kesalahan', true);
            }
        }

        function exportTournamentToCSV() {
            if (!currentTournamentData) {
                showToast('Tidak ada data laporan turnamen untuk diekspor', true);
                return;
            }
            const date = document.getElementById('report-date').value;
            const data = currentTournamentData;
            const rows = [
                ['Tanggal Laporan', date],
                ['Link Website (Nama Toko)', data.store_name || ''],
                ['Total Register', data.total_register],
                ['Total Prediksi', data.total_predictions],
                ['Prediksi Grup', data.total_group_predictions || 0],
                ['Prediksi Knockout', data.total_knockout_predictions || 0],
                ['Claim Daily', data.total_claim_daily],
                ['Claim Kode Tiket', data.total_claim_ticket],
                ['Catatan', data.notes || '']
            ];
            const csvContent = rows.map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(',')).join('\n');
            downloadCSV(csvContent, `laporan_turnamen_${date}.csv`);
        }

        function exportUserToCSV() {
            if (!currentUserData) {
                showToast('Tidak ada data laporan pengguna untuk diekspor', true);
                return;
            }
            const date = document.getElementById('report-date').value;
            const data = currentUserData;

            // Jika kosong, ganti dengan '0'
            const claimTicket = (data.users_claim_ticket && data.users_claim_ticket.trim() !== '') ? data.users_claim_ticket : '0';
            const usingPoint = (data.users_using_point && data.users_using_point.trim() !== '') ? data.users_using_point : '0';

            const mainRows = [
                ['Tanggal Laporan', date],
                ['Link Website (Nama Toko)', data.store_name || ''],
                ['User Baru', data.new_users_count],
                ['User Claim Kode Tiket', claimTicket],
                ['User Menggunakan Poin', usingPoint],
                ['Catatan', data.notes || '']
            ];

            const predictionHistory = data.prediction_history || '';
            const predictionLines = predictionHistory.split(/\r?\n/);
            const csvRows = [];
            mainRows.forEach(row => csvRows.push(row));
            csvRows.push(['Riwayat Prediksi:']);
            if (predictionLines.length > 0 && predictionLines[0] !== '') {
                predictionLines.forEach(line => {
                    csvRows.push([line]);
                });
            } else {
                csvRows.push(['-']);
            }

            const csvContent = csvRows.map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(',')).join('\n');
            downloadCSV(csvContent, `laporan_pengguna_${date}.csv`);
        }

        function downloadCSV(csv, filename) {
            const blob = new Blob(["\uFEFF" + csv], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.href = url;
            link.setAttribute('download', filename);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
        }

        function escapeHtml(str) { if (!str) return ''; return str.replace(/[&<>]/g, m => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[m])); }

        document.getElementById('generate-btn').addEventListener('click', () => {
            const date = document.getElementById('report-date').value;
            const storeName = document.getElementById('store-name').value;
            if (!date) return;
            if (!storeName) {
                showToast('Link website tidak boleh kosong', true);
                return;
            }
            generateReport(date, storeName);
        });
        document.getElementById('refresh-btn').addEventListener('click', () => {
            const date = document.getElementById('report-date').value;
            if (date) loadReport(date);
        });
        document.getElementById('save-tournament-notes').addEventListener('click', () => {
            const date = document.getElementById('report-date').value;
            const notes = document.getElementById('tournament-notes').value;
            saveNotes(date, 'tournament', notes);
        });
        document.getElementById('save-user-notes').addEventListener('click', () => {
            const date = document.getElementById('report-date').value;
            const notes = document.getElementById('user-notes').value;
            saveNotes(date, 'user', notes);
        });
        document.getElementById('export-tournament-csv').addEventListener('click', exportTournamentToCSV);
        document.getElementById('export-user-csv').addEventListener('click', exportUserToCSV);

        // Load default today
        loadReport(document.getElementById('report-date').value);
    </script>
</body>

</html>