<?php
require_once __DIR__ . '/bootstrap.php';
$pageTitle = 'History';
include 'partials/head.php';
?>

<div class="flex h-full min-h-screen">
    <?php include 'partials/sidebar.php'; ?>

    <main class="flex-1 lg:ml-48 pb-16 lg:pb-0">
        <!-- Header -->
        <header class="sticky top-0 bg-white/80 backdrop-blur border-b border-slate-200 px-4 lg:px-5 py-3 z-20">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-base font-semibold">History</h1>
                    <p class="text-xs text-slate-400">Sent notifications log</p>
                </div>
            </div>
        </header>

        <div class="p-4 lg:p-5 space-y-6">
            <!-- Stats -->
            <div class="grid grid-cols-2 lg:grid-cols-4 gap-3">
                <div class="bg-white rounded-xl p-4 border border-slate-200 shadow-sm">
                    <div class="text-2xl font-semibold" id="stat-total">0</div>
                    <div class="text-xs text-slate-400 mt-0.5">Total Sent</div>
                </div>
                <div class="bg-white rounded-xl p-4 border border-slate-200 shadow-sm">
                    <div class="text-2xl font-semibold text-indigo-500" id="stat-subsequents">0</div>
                    <div class="text-xs text-slate-400 mt-0.5">Follow-ups</div>
                </div>
                <div class="bg-white rounded-xl p-4 border border-slate-200 shadow-sm">
                    <div class="text-2xl font-semibold text-red-500" id="stat-failed">0</div>
                    <div class="text-xs text-slate-400 mt-0.5">Failed Jobs</div>
                </div>
                <div class="bg-white rounded-xl p-4 border border-slate-200 shadow-sm">
                    <div class="text-2xl font-semibold text-amber-500" id="stat-pending">0</div>
                    <div class="text-xs text-slate-400 mt-0.5">Pending Jobs</div>
                </div>
            </div>

            <!-- Sent History -->
            <section>
                <div class="flex items-center justify-between mb-3">
                    <h2 class="text-sm font-medium text-slate-700">Sent History</h2>
                    <div class="relative" id="date-dropdown">
                        <button type="button" class="h-7 px-2 pr-7 bg-slate-100 hover:bg-slate-200 rounded-md text-xs flex items-center gap-1.5 transition-colors" onclick="toggleDropdown('date')">
                            <span id="date-label">All Time</span>
                            <svg class="w-3.5 h-3.5 absolute right-2 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                        </button>
                        <div id="date-options" class="hidden absolute top-full left-0 mt-1 bg-white rounded-lg shadow-lg border border-slate-200 py-1 min-w-[120px] z-30">
                            <button class="w-full px-3 py-1.5 text-left text-xs hover:bg-slate-50" onclick="selectDate('', 'All Time')">All Time</button>
                            <button class="w-full px-3 py-1.5 text-left text-xs hover:bg-slate-50" onclick="selectDate('today', 'Today')">Today</button>
                            <button class="w-full px-3 py-1.5 text-left text-xs hover:bg-slate-50" onclick="selectDate('week', 'This Week')">This Week</button>
                            <button class="w-full px-3 py-1.5 text-left text-xs hover:bg-slate-50" onclick="selectDate('month', 'This Month')">This Month</button>
                        </div>
                    </div>
                </div>

                <!-- Empty State -->
                <div id="history-empty" class="hidden text-center py-16">
                    <div class="w-14 h-14 bg-slate-100 rounded-xl flex items-center justify-center mx-auto mb-4">
                        <svg class="w-7 h-7 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                        </svg>
                    </div>
                    <p class="text-sm font-medium text-slate-700 mb-1">No history yet</p>
                    <p class="text-xs text-slate-400">Sent notifications will appear here</p>
                </div>

                <!-- History List -->
                <div id="history-container" class="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
                    <div id="history-list" class="divide-y divide-slate-100">
                        <!-- Populated by JS -->
                    </div>
                </div>

                <div class="flex justify-center mt-3">
                    <button id="load-more-btn" onclick="loadMoreHistory()" class="hidden h-8 px-4 bg-slate-100 hover:bg-slate-200 rounded-lg text-xs font-medium transition-colors">Load More</button>
                </div>
            </section>

            <!-- Failed / Pending Jobs -->
            <section>
                <div class="flex items-center justify-between mb-3">
                    <h2 class="text-sm font-medium text-slate-700">Failed / Pending</h2>
                    <button onclick="refreshJobs()" class="h-7 px-2.5 bg-slate-100 hover:bg-slate-200 rounded-lg text-xs font-medium transition-colors">Refresh</button>
                </div>

                <div id="jobs-empty" class="hidden text-center py-10">
                    <p class="text-xs text-slate-400">No failed or pending jobs</p>
                </div>

                <div id="jobs-container" class="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
                    <div id="jobs-list" class="divide-y divide-slate-100">
                        <!-- Populated by JS -->
                    </div>
                </div>
            </section>
        </div>
    </main>
</div>

<?php include 'partials/mobile-nav.php'; ?>

<?php include 'partials/scripts.php'; ?>
<script>
    let allHistory = [];
    let filteredHistory = [];
    let failedJobs = [];
    let pendingJobs = [];
    let currentPage = 1;
    let hasMore = true;
    let loadingHistory = false;
    let dateFilter = '';
    const PER_PAGE = 20;

    // Custom dropdown functions
    function toggleDropdown(type) {
        const options = document.getElementById(type + '-options');
        const isHidden = options.classList.contains('hidden');

        // Close all dropdowns first
        document.querySelectorAll('[id$="-options"]').forEach(el => el.classList.add('hidden'));

        if (isHidden) {
            options.classList.remove('hidden');
        }
    }

    function selectDate(value, label) {
        dateFilter = value;
        document.getElementById('date-label').textContent = label;
        document.getElementById('date-options').classList.add('hidden');
        applyFilters();
    }

    // Close dropdowns when clicking outside
    document.addEventListener('click', (e) => {
        if (!e.target.closest('#date-dropdown')) {
            document.querySelectorAll('[id$="-options"]').forEach(el => el.classList.add('hidden'));
        }
    });

    async function init() {
        await loadHistory(true);
        await loadJobs();
    }

    function escapeHtml(str) {
        if (!str) return '';
        return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
    }

    function getFilteredHistory() {
        let history = [...allHistory];

        if (dateFilter) {
            const now = new Date();
            let startDate;
            if (dateFilter === 'today') startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            else if (dateFilter === 'week') startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
            else if (dateFilter === 'month') startDate = new Date(now.getFullYear(), now.getMonth(), 1);
            if (startDate) history = history.filter(h => new Date(h.sent_at) >= startDate);
        }

        return history.sort((a, b) => new Date(b.sent_at) - new Date(a.sent_at));
    }

    function applyFilters() {
        filteredHistory = getFilteredHistory();
        renderHistory();
    }

    function updateStats() {
        document.getElementById('stat-total').textContent = allHistory.length;
        document.getElementById('stat-subsequents').textContent = allHistory.filter(h => Number(h.is_subsequent) === 1).length;
        document.getElementById('stat-failed').textContent = failedJobs.length;
        document.getElementById('stat-pending').textContent = pendingJobs.length;
    }

    function normalizeUtc(dateStr) {
        if (!dateStr) return null;
        if (dateStr.includes('T')) {
            return dateStr.endsWith('Z') ? dateStr : `${dateStr}Z`;
        }
        return dateStr.replace(' ', 'T') + 'Z';
    }

    function formatDateTime(dateStr) {
        const iso = normalizeUtc(dateStr);
        if (!iso) return '—';
        return DateUtils.formatDateTime(iso);
    }

    function renderHistory() {
        const list = document.getElementById('history-list');
        const container = document.getElementById('history-container');
        const emptyState = document.getElementById('history-empty');
        const loadMoreBtn = document.getElementById('load-more-btn');

        if (filteredHistory.length === 0) {
            container.classList.add('hidden');
            emptyState.classList.remove('hidden');
            loadMoreBtn.classList.add('hidden');
            return;
        }

        container.classList.remove('hidden');
        emptyState.classList.add('hidden');

        list.innerHTML = filteredHistory.map(h => {
            const title = h.notification_title || 'Unknown';
            const date = formatDateTime(h.sent_at);
            const isSubsequent = Number(h.is_subsequent) === 1;
            const subIndex = h.subsequent_index !== null && h.subsequent_index !== undefined
                ? Number(h.subsequent_index) + 1
                : null;
            const badge = isSubsequent
                ? `<span class="text-[11px] font-medium px-2 py-0.5 rounded-full bg-amber-100 text-amber-600">Follow-up${subIndex ? ` #${subIndex}` : ''}</span>`
                : '';

            return `
                <div class="px-4 py-3 flex items-center gap-3 hover:bg-slate-50 transition-colors">
                    <div class="flex-1 min-w-0">
                        <div class="font-medium text-sm truncate">${escapeHtml(title)}</div>
                        <div class="text-xs text-slate-400">${date}</div>
                    </div>
                    <div class="flex items-center gap-2">
                        ${badge}
                    </div>
                </div>
            `;
        }).join('');

        loadMoreBtn.classList.toggle('hidden', !hasMore);
        loadMoreBtn.disabled = loadingHistory;
        loadMoreBtn.textContent = loadingHistory ? 'Loading...' : 'Load More';
    }

    async function loadHistory(reset = false) {
        if (loadingHistory) return;
        loadingHistory = true;

        const list = document.getElementById('history-list');
        const container = document.getElementById('history-container');
        const emptyState = document.getElementById('history-empty');

        if (reset) {
            currentPage = 1;
            hasMore = true;
            allHistory = [];
            container.classList.remove('hidden');
            emptyState.classList.add('hidden');
            list.innerHTML = '<div class="px-4 py-8 text-center text-slate-400 text-sm">Loading...</div>';
        }

        try {
            const result = await Api.getHistory(currentPage, PER_PAGE);
            const pageItems = result.history || [];
            allHistory = reset ? pageItems : allHistory.concat(pageItems);
            hasMore = pageItems.length === PER_PAGE;
            currentPage += 1;
            applyFilters();
            updateStats();
        } catch (error) {
            list.innerHTML = `<div class="px-4 py-8 text-center text-red-500 text-sm">Failed to load history: ${escapeHtml(error.message)}</div>`;
            Toast.error('Error', 'Failed to load history');
        } finally {
            loadingHistory = false;
            const loadMoreBtn = document.getElementById('load-more-btn');
            loadMoreBtn.disabled = false;
            loadMoreBtn.textContent = 'Load More';
        }
    }

    function loadMoreHistory() {
        if (!hasMore) return;
        loadHistory(false);
    }

    async function loadJobs() {
        const list = document.getElementById('jobs-list');
        const container = document.getElementById('jobs-container');
        const emptyState = document.getElementById('jobs-empty');

        container.classList.remove('hidden');
        emptyState.classList.add('hidden');
        list.innerHTML = '<div class="px-4 py-8 text-center text-slate-400 text-sm">Loading...</div>';

        try {
            const [failed, pending] = await Promise.all([
                Api.getFailedJobs(),
                Api.getPendingJobs()
            ]);
            failedJobs = failed || [];
            pendingJobs = pending || [];
            renderJobs();
            updateStats();
        } catch (error) {
            list.innerHTML = `<div class="px-4 py-8 text-center text-red-500 text-sm">Failed to load jobs: ${escapeHtml(error.message)}</div>`;
            Toast.error('Error', 'Failed to load jobs');
        }
    }

    function refreshJobs() {
        loadJobs();
    }

    function renderJobs() {
        const list = document.getElementById('jobs-list');
        const container = document.getElementById('jobs-container');
        const emptyState = document.getElementById('jobs-empty');

        const jobs = [...failedJobs, ...pendingJobs];

        if (jobs.length === 0) {
            container.classList.add('hidden');
            emptyState.classList.remove('hidden');
            return;
        }

        container.classList.remove('hidden');
        emptyState.classList.add('hidden');

        jobs.sort((a, b) => {
            const aTime = normalizeUtc(a.next_attempt_at || a.scheduled_for || a.created_at) || '';
            const bTime = normalizeUtc(b.next_attempt_at || b.scheduled_for || b.created_at) || '';
            return new Date(aTime).getTime() - new Date(bTime).getTime();
        });

        list.innerHTML = jobs.map(job => {
            const title = job.notification_title || 'Unknown';
            const statusText = job.status === 'failed' ? 'Failed' : (job.status === 'retrying' ? 'Retrying' : 'Pending');
            const statusColor = job.status === 'failed'
                ? 'bg-red-100 text-red-600'
                : (job.status === 'retrying' ? 'bg-amber-100 text-amber-600' : 'bg-blue-100 text-blue-600');
            const scheduledAt = formatDateTime(job.scheduled_for);
            const nextAttempt = job.status === 'retrying' ? formatDateTime(job.next_attempt_at) : null;
            const attempts = job.attempt_count !== undefined ? job.attempt_count : 0;
            const error = job.last_error ? escapeHtml(job.last_error) : '';
            const canRetry = ['failed', 'retrying', 'pending'].includes(job.status);
            const retryButton = canRetry
                ? `<button onclick="retryJob(${job.id})" class="h-7 px-2.5 bg-slate-100 hover:bg-slate-200 rounded-lg text-xs font-medium transition-colors">Retry now</button>`
                : '';

            return `
                <div class="px-4 py-3">
                    <div class="flex items-start gap-3">
                        <div class="flex-1 min-w-0">
                            <div class="font-medium text-sm truncate">${escapeHtml(title)}</div>
                            <div class="text-xs text-slate-400 mt-0.5">Scheduled: ${scheduledAt}</div>
                            ${nextAttempt ? `<div class="text-xs text-slate-400">Next attempt: ${nextAttempt}</div>` : ''}
                            <div class="text-xs text-slate-400">Attempts: ${attempts}</div>
                            ${error ? `<div class="text-xs text-red-500 mt-1 truncate" title="${error}">Error: ${error}</div>` : ''}
                        </div>
                        <div class="flex flex-col items-end gap-2">
                            <span class="text-[11px] font-medium px-2 py-0.5 rounded-full ${statusColor}">${statusText}</span>
                            ${retryButton}
                        </div>
                    </div>
                </div>
            `;
        }).join('');
    }

    async function retryJob(jobId) {
        try {
            await Api.retryJob(jobId);
            Toast.success('Queued', 'Retry scheduled');
            await loadJobs();
        } catch (error) {
            Toast.error('Error', error.message);
        }
    }

    init();
</script>
</body>
</html>
