<?php
session_start();
$loggedIn = isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;

$user_agent = $_SERVER['HTTP_USER_AGENT'];
if (strpos($user_agent, 'iPhone') !== false) {
    $default_per_page = 200;
} elseif (strpos($user_agent, 'Android') !== false) {
    $default_per_page = 100;
} else {
    $default_per_page = 500;
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Topup Orders Dashboard</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    
    <style>
        :root {
            --bg-color: #e0e7ff; 
            --window-bg: rgba(255, 255, 255, 0.85);
            --text-main: #1e293b;
            --text-muted: #64748b;
            --border-color: rgba(0, 0, 0, 0.08);
            
            --tag-blue: #e0f2fe; --tag-blue-text: #0369a1;
            --tag-green: #dcfce7; --tag-green-text: #15803d;
            --tag-yellow: #fef9c3; --tag-yellow-text: #a16207;
            --tag-red: #fee2e2; --tag-red-text: #b91c1c;
        }

        * { font-family: 'Inter', sans-serif; box-sizing: border-box; }

        body { 
            background: linear-gradient(45deg, #ff9a9e 0%, #fecfef 99%, #fecfef 100%);
            background-attachment: fixed;
            min-height: 100vh; 
            padding: 2vh 1vw; 
            color: var(--text-main);
            font-size: 13px; 
        }

        .os-window {
            max-width: 1350px;
            margin: 0 auto;
            background: var(--window-bg);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-radius: 16px;
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25), 0 0 0 1px rgba(255,255,255,0.3) inset;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            min-height: 90vh;
        }

        .window-header {
            background: rgba(255, 255, 255, 0.4);
            padding: 12px 20px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .traffic-lights { display: flex; gap: 8px; }
        .dot { width: 12px; height: 12px; border-radius: 50%; }
        .dot.red { background: #ff5f56; }
        .dot.yellow { background: #ffbd2e; }
        .dot.green { background: #27c93f; }
        
        .window-title { font-weight: 600; color: #475569; font-size: 14px; }
        .btn-logout { background: transparent; border: none; color: #ef4444; font-weight: 600; font-size: 13px; text-decoration: none;}

        .window-content { padding: 20px; flex-grow: 1; }

        .os-tabs {
            background: rgba(0,0,0,0.05);
            padding: 4px;
            border-radius: 8px;
            display: inline-flex;
            gap: 2px;
            margin-bottom: 15px;
        }
        .os-tabs .nav-link {
            padding: 6px 16px;
            border-radius: 6px;
            color: var(--text-muted);
            font-weight: 500;
            font-size: 13px;
            border: none;
            transition: 0.2s;
        }
        .os-tabs .nav-link.active { background: white; color: var(--text-main); box-shadow: 0 2px 5px rgba(0,0,0,0.05); }

        .stats-bar { display: flex; gap: 15px; margin-bottom: 15px; flex-wrap: wrap; }
        .stat-badge {
            background: white; padding: 8px 15px; border-radius: 8px;
            border: 1px solid var(--border-color); font-weight: 600; display: flex; align-items: center; gap: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.02);
        }

        .table-responsive {
            background: white;
            border-radius: 10px;
            border: 1px solid var(--border-color);
            overflow: hidden;
        }
        .compact-table { margin: 0; width: 100%; border-collapse: collapse; }
        .compact-table th {
            background: #f8fafc; color: #94a3b8; font-size: 11px; text-transform: uppercase;
            font-weight: 700; padding: 10px 15px; border-bottom: 1px solid var(--border-color);
        }
        .compact-table td {
            padding: 8px 15px; vertical-align: middle; border-bottom: 1px solid var(--border-color);
            color: var(--text-main); font-size: 13px;
        }
        .compact-table tr:last-child td { border-bottom: none; }
        .compact-table tr:hover { background: #f8fafc; }

        .color-tag { padding: 3px 8px; border-radius: 4px; font-size: 11px; font-weight: 600; display: inline-block;}
        .tag-success { background: var(--tag-green); color: var(--tag-green-text); }
        .tag-pending { background: var(--tag-yellow); color: var(--tag-yellow-text); }
        .tag-danger { background: var(--tag-red); color: var(--tag-red-text); }
        
        .action-cell { white-space: nowrap; }

        .mobile-list { display: none; }
        .mobile-item {
            background: white; border: 1px solid var(--border-color);
            border-radius: 10px; padding: 12px; margin-bottom: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.02);
        }
        .mobile-item-header { display: flex; justify-content: space-between; margin-bottom: 8px; border-bottom: 1px dashed var(--border-color); padding-bottom: 8px;}
        .mobile-row { display: flex; justify-content: space-between; margin-bottom: 4px; }
        .mobile-label { color: var(--text-muted); font-size: 11px; }
        .mobile-value { font-weight: 500; font-size: 13px; text-align: right;}

        @media (max-width: 768px) {
            .table-responsive { display: none; } 
            .mobile-list { display: block; } 
            body { padding: 0; }
            .os-window { border-radius: 0; min-height: 100vh; }
            .window-header { padding: 15px; }
            .stats-bar { flex-direction: column; gap: 8px; }
            .os-tabs { width: 100%; overflow-x: auto; white-space: nowrap; }
        }

        .login-box { max-width: 320px; margin: 100px auto; text-align: center; }
        .login-box input { width: 100%; padding: 10px 15px; margin-bottom: 15px; border-radius: 8px; border: 1px solid var(--border-color); outline: none; }
        .login-box button { width: 100%; background: #3b82f6; color: white; border: none; padding: 10px; border-radius: 8px; font-weight: 600; }

        .pagination-compact { display: flex; justify-content: center; gap: 5px; margin-top: 20px; }
        .pagination-compact button { border: 1px solid var(--border-color); background: white; padding: 5px 12px; border-radius: 6px; font-size: 13px; cursor: pointer; }
        .pagination-compact button.active { background: #3b82f6; color: white; border-color: #3b82f6; }
        .pagination-compact button:disabled { opacity: 0.5; cursor: not-allowed; }

        /* Highlight UID */
        .uid-box { background: #f1f5f9; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 13px; color: #0284c7; border: 1px dashed #cbd5e1;}
    </style>
</head>
<body>

<div class="toast-container position-fixed bottom-0 end-0 p-3" style="z-index: 9999;">
    <div id="liveToast" class="toast border-0 shadow-sm" role="alert">
        <div class="toast-body fw-bold rounded" id="toastMessage" style="font-size: 13px; background: white;"></div>
    </div>
</div>

<div class="os-window">
    <div class="window-header">
        <div class="traffic-lights">
            <div class="dot red"></div><div class="dot yellow"></div><div class="dot green"></div>
        </div>
        <div class="window-title">Topup Orders Management</div>
        <?php if ($loggedIn): ?>
            <a href="?logout=1" class="btn-logout"><i class="fas fa-power-off"></i></a>
        <?php else: ?>
            <div></div>
        <?php endif; ?>
    </div>

    <div class="window-content">
        <?php if (!$loggedIn): ?>
            <div class="login-box">
                <i class="fas fa-gamepad fa-3x mb-3" style="color: #3b82f6;"></i>
                <h5 class="mb-4">System Authentication</h5>
                <form id="loginForm">
                    <input type="text" id="adminUsername" placeholder="Username" required>
                    <input type="password" id="adminPassword" placeholder="Password" required>
                    <button type="submit">Unlock System</button>
                </form>
            </div>
        <?php else: ?>
            
            <div id="ordersStats" class="stats-bar"></div>

            <div class="os-tabs" id="statusTabs">
                <button class="nav-link active" data-status="">All</button>
                <button class="nav-link" data-status="Pending">Pending</button>
                <button class="nav-link" data-status="Success">Success</button>
                <button class="nav-link" data-status="Failed">Failed</button>
            </div>

            <!-- Desktop Table -->
            <div class="table-responsive">
                <table class="compact-table" id="desktopTable">
                    <thead>
                        <tr>
                            <th>ID & Date</th>
                            <th>Customer</th>
                            <th>Topup Info (UID)</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <tr><td colspan="6" class="text-center py-4 text-muted">Loading data...</td></tr>
                    </tbody>
                </table>
            </div>

            <!-- Mobile Compact List -->
            <div class="mobile-list" id="mobileList"></div>
            
            <div class="pagination-compact" id="ordersPagination"></div>

        <?php endif; ?>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
$(document).ready(function() {

    const DEFAULT_PER_PAGE = <?php echo json_encode($default_per_page); ?>;
    let currentPage = 1;
    let lastPage = 1;
    let currentStatus = '';
    const API_URL = 'topup_orders_api.php'; // Updated API file name

    function showToast(message, type = 'success') {
        const toastEl = $('#liveToast');
        const body = $('#toastMessage');
        if (type === 'success') body.html(`✅ ${message}`).css('color', '#15803d');
        else body.html(`❌ ${message}`).css('color', '#b91c1c');
        new bootstrap.Toast(toastEl, { delay: 3000 }).show();
    }

    $('#loginForm').on('submit', function(e) {
        e.preventDefault();
        const btn = $(this).find('button');
        btn.text('Unlocking...');
        $.post(API_URL, {
            type: 'get_all',
            admin_username: $('#adminUsername').val(),
            admin_password: $('#adminPassword').val()
        }, function(response) {
            if (response.status === 'success') location.reload();
            else { showToast('Invalid Credentials', 'error'); btn.text('Unlock System'); }
        }).fail(() => { showToast('Server Error', 'error'); btn.text('Unlock System'); });
    });

    function processUsername(username) {
        if (!username || username.trim() === '') return '<span class="text-danger fw-bold">N/A</span>';
        if (username.length > 25 && !username.includes(' ')) return '<span class="text-danger fw-bold">Hidden Token</span>';
        if (username.length > 20) return username.substring(0, 20) + '...';
        return username;
    }

    function truncateText(text, limit = 20) {
        if (!text) return '';
        return text.length > limit ? text.substring(0, limit) + '...' : text;
    }

    function renderStats(data) {
        const totalAmount = data.reduce((sum, row) => sum + (parseFloat(row.discount_price) || 0), 0);
        $('#ordersStats').html(`
            <div class="stat-badge"><i class="fas fa-layer-group" style="color:#3b82f6"></i> Total Orders: ${data.length}</div>
            <div class="stat-badge"><i class="fas fa-wallet" style="color:#10b981"></i> Value: ৳${totalAmount.toLocaleString()}</div>
        `);
    }

    function renderUI(data, pageNum) {
        const tbody = $('#tableBody');
        const mlist = $('#mobileList');
        
        if (data.length === 0) {
            const emptyHtml = `<div class="text-center py-4 text-muted">No topup orders found</div>`;
            tbody.html(`<tr><td colspan="6">${emptyHtml}</td></tr>`);
            mlist.html(emptyHtml);
            return;
        }

        let desktopHtml = '';
        let mobileHtml = '';

        data.forEach((row, index) => {
            const serial = (pageNum - 1) * DEFAULT_PER_PAGE + index + 1;
            const statusLower = (row.status || '').toLowerCase();
            
            let tagClass = 'tag-pending';
            if(statusLower === 'success') tagClass = 'tag-success';
            if(statusLower === 'failed') tagClass = 'tag-danger';

            const displayUser = processUsername(row.username);
            const displayTitle = truncateText(row.product_title, 25);
            const formattedDate = row.order_date ? new Date(row.order_date).toLocaleString('en-US', {month:'short', day:'numeric', hour:'2-digit', minute:'2-digit'}) : 'N/A';

            // 100% Working Button Action logic (with loading spinner integration)
            const actions = statusLower === 'pending' ? `
                <div class="d-flex gap-1 justify-content-end justify-content-md-start">
                    <button class="btn btn-success btn-sm fw-bold action-process-btn" data-id="${row.id}" data-type="complete" style="font-size: 11px; padding: 4px 8px;">
                        <i class="fas fa-check"></i> Success
                    </button>
                    <button class="btn btn-danger btn-sm fw-bold action-process-btn" data-id="${row.id}" data-type="fail" style="font-size: 11px; padding: 4px 8px;">
                        <i class="fas fa-times"></i> Failed
                    </button>
                </div>
            ` : `<span class="badge bg-secondary text-light fw-normal p-2"><i class="fas fa-lock"></i> Locked</span>`;

            // Desktop Table UI
            desktopHtml += `
                <tr>
                    <td><strong>#${row.id}</strong><br><span class="text-muted" style="font-size:10px;">${formattedDate}</span></td>
                    <td>
                        <div style="font-weight:600;">${displayUser}</div>
                        <div class="text-muted" style="font-size:11px;">${row.email || 'No email'}</div>
                    </td>
                    <td>
                        <div class="mb-1" style="font-weight:600;">${displayTitle || 'Unknown Product'}</div>
                        <span class="uid-box">UID: ${row.topup_uid || 'N/A'}</span>
                    </td>
                    <td>
                        <strong style="color:var(--tag-green-text); font-size:14px;">৳${row.discount_price || 0}</strong><br>
                        <span class="text-muted" style="font-size:11px;"><del>৳${row.product_price || 0}</del></span>
                    </td>
                    <td><span class="color-tag ${tagClass}">${row.status}</span></td>
                    <td class="action-cell">${actions}</td>
                </tr>
            `;

            // Mobile List UI
            mobileHtml += `
                <div class="mobile-item">
                    <div class="mobile-item-header">
                        <div><strong>#${row.id}</strong> <span class="text-muted" style="font-size:10px;">(${formattedDate})</span></div>
                        <span class="color-tag ${tagClass}">${row.status}</span>
                    </div>
                    <div class="mobile-row"><span class="mobile-label">User:</span> <span class="mobile-value">${displayUser}</span></div>
                    <div class="mobile-row"><span class="mobile-label">Product:</span> <span class="mobile-value">${displayTitle}</span></div>
                    <div class="mobile-row align-items-center mt-1 mb-2">
                        <span class="mobile-label">Game UID:</span> 
                        <span class="uid-box">${row.topup_uid || 'N/A'}</span>
                    </div>
                    <div class="mobile-row"><span class="mobile-label">Paid Amount:</span> <span class="mobile-value" style="color:#15803d; font-size:14px;">৳${row.discount_price || 0}</span></div>
                    <div class="mt-2 pt-2 border-top">${actions}</div>
                </div>
            `;
        });

        tbody.html(desktopHtml);
        mlist.html(mobileHtml);
    }

    function fetchOrders(status = '', page = 1) {
        $('#tableBody').html('<tr><td colspan="6" class="text-center py-4 text-muted">Loading...</td></tr>');
        $('#mobileList').html('<div class="text-center py-4 text-muted">Loading...</div>');
        
        $.post(API_URL, {
            type: 'get_all', status: status, page: page, per_page: DEFAULT_PER_PAGE
        }, function(response) {
            if (response.status === 'success') {
                currentPage = response.current_page;
                lastPage = response.last_page;
                renderStats(response.data);
                renderUI(response.data, currentPage);
                renderPagination();
            } else {
                showToast(response.message, 'error');
            }
        });
    }

    function renderPagination() {
        let html = '';
        html += `<button ${currentPage <= 1 ? 'disabled' : ''} onclick="changePage(${currentPage-1})">Prev</button>`;
        html += `<button class="active">${currentPage}</button>`;
        html += `<button ${currentPage >= lastPage ? 'disabled' : ''} onclick="changePage(${currentPage+1})">Next</button>`;
        $('#ordersPagination').html(html);
    }

    window.changePage = function(page) {
        if (page >= 1 && page <= lastPage) {
            fetchOrders(currentStatus, page);
        }
    };

    // 100% Working Button Event Logic using Delegation
    $(document).on('click', '.action-process-btn', function() {
        const id = $(this).data('id');
        const actionType = $(this).data('type');
        const msg = actionType === 'complete' ? 'Accept this Topup and mark as Success?' : 'Reject, refund amount and mark as Failed?';
        
        if (!confirm(msg)) return;
        
        const btn = $(this);
        btn.html('<i class="fas fa-spinner fa-spin"></i> Wait...');
        btn.prop('disabled', true);

        $.ajax({
            url: API_URL,
            type: 'POST',
            data: { type: actionType, id: id },
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    showToast(response.message, 'success');
                    fetchOrders(currentStatus, currentPage);
                } else {
                    showToast(response.message || 'Error occurred', 'error');
                    fetchOrders(currentStatus, currentPage);
                }
            },
            error: function() {
                showToast('Server Error! Check API File.', 'error');
                fetchOrders(currentStatus, currentPage);
            }
        });
    });

    $('.os-tabs .nav-link').on('click', function() {
        $('.os-tabs .nav-link').removeClass('active');
        $(this).addClass('active');
        currentStatus = $(this).data('status');
        fetchOrders(currentStatus, 1);
    });

    <?php if (isset($_GET['logout'])): session_destroy(); echo "window.location.href='?';"; endif; ?>
    <?php if ($loggedIn): ?> fetchOrders('', 1); <?php endif; ?>

});
</script>
</body>
</html>