<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/session_bootstrap.php';
if (empty($_SESSION['logged_in'])) {
    header('Location: /login/?error=' . urlencode('Zaloguj się, aby zobaczyć swoje mecze.'));
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Moje Mecze | kontakt: wspolpraca@togethere.cloud</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
    <meta name="keywords" content="projekty przyszłości"/>
    <link rel="stylesheet" href="/css/header.css" type="text/css" media="all"/>
    <link rel="stylesheet" href="/css/footer.css" type="text/css" media="all"/>
    <link href="/css/font-awesome.min.css" rel="stylesheet" type="text/css" media="all">
    <link href="//fonts.googleapis.com/css?family=Lato:400,500,600,700,800,900" rel="stylesheet">
    <style>
        nav.navigation { margin-top: 0 !important; }
        .activity-wrap { max-width: 1100px; margin: 0 auto 36px; padding: 0 16px; }
        .activity-head { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-bottom: 16px; flex-wrap: wrap; }
        .activity-head h1 { margin: 0; color: #111; background: #fff; padding: 12px 16px; border-radius: 10px; }
        .activity-toolbar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
        .activity-btn { border: 0; border-radius: 8px; background: #007BFF; color: #fff; padding: 10px 14px; cursor: pointer; font-weight: 700; }
        .activity-btn:disabled { opacity: 0.7; cursor: not-allowed; }
        .activity-btn-secondary { background: #6b7280; }
        .activity-select { border: 1px solid #d1d5db; border-radius: 8px; padding: 10px 12px; font-size: 14px; background: #fff; color: #1f2937; }
        .activity-card { background: #fff; border: 1px solid #dbe3ec; border-radius: 12px; box-shadow: 0 10px 22px rgba(0,0,0,0.08); overflow: hidden; }
        .activity-meta { padding: 12px 14px; font-size: 13px; color: #5d6d7e; border-bottom: 1px solid #eef2f7; display: flex; justify-content: space-between; gap: 8px; flex-wrap: wrap; }
        .activity-error { color: #b42318; font-weight: 700; }
        .activity-table-wrap { width: 100%; overflow: auto; }
        .activity-pagination { display: flex; justify-content: space-between; align-items: center; gap: 8px; padding: 12px 14px; border-top: 1px solid #eef2f7; flex-wrap: wrap; }
        .activity-pageinfo { font-size: 13px; color: #5d6d7e; }
        .activity-pagebtns { display: flex; gap: 8px; }
        table.activity-table { width: 100%; border-collapse: collapse; min-width: 720px; }
        .activity-table th, .activity-table td { padding: 12px 14px; text-align: left; border-bottom: 1px solid #eef2f7; font-size: 14px; }
        .activity-table th { background: #f8fbff; color: #1f2937; }
        .activity-empty { padding: 32px 16px; text-align: center; color: #64748b; }
        .status-badge { display: inline-flex; border-radius: 999px; padding: 4px 10px; font-size: 12px; font-weight: 700; }
        .status-zaplanowany { background: #fff4cc; color: #8a5a00; }
        .status-trwający { background: #dff4ff; color: #0b63a7; }
        .status-zakończony { background: #e8f7e8; color: #166534; }
        @media (max-width: 768px) {
            .activity-wrap { padding: 0 10px; }
            .activity-head h1 { width: 100%; text-align: center; }
            .activity-toolbar { width: 100%; }
            .activity-select, .activity-btn { width: 100%; }
            .activity-pagebtns { width: 100%; }
            .activity-pagebtns .activity-btn { flex: 1 1 auto; }
        }
    </style>
</head>
<body>
    <?php include $_SERVER['DOCUMENT_ROOT'].'/global/navLogined.php'; ?>
    <main>
        <section class="activity-wrap">
            <div class="activity-head">
                <h1>⚽ Moje Mecze</h1>
                <div class="activity-toolbar">
                    <select id="statusFilter" class="activity-select" aria-label="Filtruj po statusie">
                        <option value="all">Wszystkie statusy</option>
                        <option value="zaplanowany">Zaplanowane</option>
                        <option value="trwający">Trwające</option>
                        <option value="zakończony">Zakończone</option>
                    </select>
                    <button type="button" id="reloadBtn" class="activity-btn">Odśwież</button>
                </div>
            </div>
            <div class="activity-card">
                <div class="activity-meta">
                    <span id="summaryText">Ładowanie danych…</span>
                    <span id="errorText" class="activity-error" style="display:none;"></span>
                </div>
                <div class="activity-table-wrap" id="tableWrap"></div>
                <div class="activity-pagination">
                    <span id="pageInfo" class="activity-pageinfo">Strona 1 z 1</span>
                    <div class="activity-pagebtns">
                        <button type="button" id="prevBtn" class="activity-btn activity-btn-secondary">Poprzednia</button>
                        <button type="button" id="nextBtn" class="activity-btn activity-btn-secondary">Następna</button>
                    </div>
                </div>
            </div>
        </section>
    </main>
    <?php include $_SERVER['DOCUMENT_ROOT'].'/global/footerLogined.php'; ?>
    <script>
        (function () {
            var endpoint = '/userApi/my-matches.php';
            var tableWrap = document.getElementById('tableWrap');
            var summaryText = document.getElementById('summaryText');
            var errorText = document.getElementById('errorText');
            var reloadBtn = document.getElementById('reloadBtn');
            var statusFilter = document.getElementById('statusFilter');
            var prevBtn = document.getElementById('prevBtn');
            var nextBtn = document.getElementById('nextBtn');
            var pageInfo = document.getElementById('pageInfo');
            var allRows = [];
            var currentPage = 1;
            var pageSize = 10;

            function escapeHtml(v) {
                return String(v == null ? '' : v)
                    .replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;')
                    .replace(/"/g, '&quot;')
                    .replace(/'/g, '&#039;');
            }

            function fmtDate(v) {
                if (!v) return '—';
                var d = new Date(v);
                if (Number.isNaN(d.getTime())) return escapeHtml(v);
                return d.toLocaleString('pl-PL');
            }

            function badge(status) {
                var s = String(status || '').toLowerCase();
                if (s !== 'zaplanowany' && s !== 'trwający' && s !== 'zakończony') return '<span>' + escapeHtml(status || '—') + '</span>';
                return '<span class="status-badge status-' + s + '">' + escapeHtml(status) + '</span>';
            }

            function normalizeStatus(status) {
                return String(status || '').toLowerCase().trim();
            }

            function renderRows(rows) {
                if (!Array.isArray(rows) || rows.length === 0) {
                    tableWrap.innerHTML = '<div class="activity-empty">Brak meczów do wyświetlenia.</div>';
                    return;
                }

                var html = '<table class="activity-table"><thead><tr><th>ID</th><th>Przeciwnik</th><th>Data</th><th>Status</th><th>Wynik</th><th>Liga / typ</th></tr></thead><tbody>';
                for (var i = 0; i < rows.length; i++) {
                    var r = rows[i] || {};
                    html += '<tr>' +
                        '<td>#' + escapeHtml(r.match_id || r.id || '—') + '</td>' +
                        '<td>' + escapeHtml(r.opponent || r.opponent_name || '—') + '</td>' +
                        '<td>' + fmtDate(r.date || r.match_date || r.created_at) + '</td>' +
                        '<td>' + badge(r.status || r.Status || '') + '</td>' +
                        '<td>' + escapeHtml(r.score || '—') + '</td>' +
                        '<td>' + escapeHtml(r.league || r.league_name || r.match_type || '—') + '</td>' +
                        '</tr>';
                }
                html += '</tbody></table>';
                tableWrap.innerHTML = html;
            }

            function setError(msg) {
                errorText.style.display = 'inline';
                errorText.textContent = msg;
            }

            function clearError() {
                errorText.style.display = 'none';
                errorText.textContent = '';
            }

            function applyFiltersAndPagination() {
                var selectedStatus = statusFilter ? statusFilter.value : 'all';
                var filtered = allRows.filter(function (row) {
                    if (selectedStatus === 'all') return true;
                    return normalizeStatus(row && (row.status || row.Status)) === selectedStatus;
                });

                var totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
                if (currentPage > totalPages) currentPage = totalPages;
                if (currentPage < 1) currentPage = 1;

                var start = (currentPage - 1) * pageSize;
                var pageRows = filtered.slice(start, start + pageSize);

                renderRows(pageRows);
                summaryText.textContent = 'Mecze: ' + filtered.length + ' / ' + allRows.length;
                pageInfo.textContent = 'Strona ' + currentPage + ' z ' + totalPages;
                prevBtn.disabled = currentPage <= 1;
                nextBtn.disabled = currentPage >= totalPages;
            }

            async function loadData() {
                reloadBtn.disabled = true;
                summaryText.textContent = 'Ładowanie danych…';
                clearError();
                try {
                    var res = await fetch(endpoint, { credentials: 'same-origin' });
                    if (res.status === 401) {
                        window.location.href = '/login/?error=' + encodeURIComponent('Sesja wygasła. Zaloguj się ponownie.');
                        return;
                    }
                    var payload = await res.json();
                    if (payload && payload.success === false) {
                        throw new Error(payload.error || 'Nieprawidłowa odpowiedź API');
                    }
                    var data = Array.isArray(payload) ? payload : (Array.isArray(payload.data) ? payload.data : []);
                    allRows = data;
                    currentPage = 1;
                    applyFiltersAndPagination();
                } catch (e) {
                    allRows = [];
                    currentPage = 1;
                    tableWrap.innerHTML = '<div class="activity-empty">Nie udało się pobrać danych.</div>';
                    setError(e && e.message ? e.message : 'Błąd ładowania');
                    summaryText.textContent = 'Wystąpił błąd';
                    pageInfo.textContent = 'Strona 1 z 1';
                    prevBtn.disabled = true;
                    nextBtn.disabled = true;
                } finally {
                    reloadBtn.disabled = false;
                }
            }

            reloadBtn.addEventListener('click', loadData);
            statusFilter.addEventListener('change', function () {
                currentPage = 1;
                applyFiltersAndPagination();
            });
            prevBtn.addEventListener('click', function () {
                if (currentPage > 1) {
                    currentPage -= 1;
                    applyFiltersAndPagination();
                }
            });
            nextBtn.addEventListener('click', function () {
                currentPage += 1;
                applyFiltersAndPagination();
            });
            loadData();
        })();
    </script>
</body>
</html>
