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

// Device Detection for Per-Page Limit
$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; // Computer / Others
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bunasex Payment Manager</title>
    <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">
    <link href="https://fonts.googleapis.com/css2?family=Inter:opsz@14..32&display=swap" rel="stylesheet">
    <style>
        * { font-family: 'Inter', sans-serif; }
        body {
            background: #f4f6fa;
            min-height: 100vh;
            padding: 20px 0;
        }
        .container { max-width: 1400px; }

        .main-card {
            border-radius: 28px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.06);
            border: none;
            overflow: hidden;
            background: #ffffff;
        }

        .card-header-custom {
            background: linear-gradient(135deg, #7c3aed, #4f46e5);
            padding: 18px 25px;
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            align-items: center;
            border-bottom: none;
        }
        .card-header-custom h4 {
            color: #fff;
            font-weight: 700;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 1.3rem;
        }
        .btn-soft-light {
            background: rgba(255,255,255,0.15);
            border: 1px solid rgba(255,255,255,0.25);
            color: #fff;
            border-radius: 50px;
            padding: 6px 18px;
            font-weight: 500;
            transition: 0.3s;
            text-decoration: none;
        }
        .btn-soft-light:hover {
            background: #fff;
            color: #4f46e5;
        }

        .total-unpaid {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            color: #fff;
            border-radius: 20px;
            padding: 6px 20px;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-size: 0.95rem;
            white-space: nowrap;
        }

        .nav-tabs-custom .nav-link {
            border: none;
            border-radius: 50px;
            padding: 8px 20px;
            font-weight: 600;
            color: #6b7280;
            transition: 0.3s;
        }
        .nav-tabs-custom .nav-link.active {
            background: #4f46e5;
            color: #fff;
        }

        .table-custom {
            margin-bottom: 0;
            font-size: 0.9rem;
            min-width: 700px; /* সব কলাম মোবাইলে স্ক্রল করতে সাহায্য করে */
        }
        .table-custom thead th {
            background: #f8faff;
            color: #1f2937;
            font-weight: 600;
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-bottom: 2px solid #e5e7eb;
            padding: 12px 10px;
            white-space: nowrap;
        }
        .table-custom tbody td {
            padding: 12px 10px;
            vertical-align: middle;
            border-bottom: 1px solid #f1f3f5;
            color: #1f2937;
            word-break: break-word;
        }
        .table-custom tbody tr:hover {
            background: #f8faff;
        }

        .badge-status {
            padding: 5px 12px;
            border-radius: 30px;
            font-weight: 600;
            font-size: 0.75rem;
        }
        .badge-pending { background: #fef3c7; color: #b45309; }
        .badge-success { background: #d1fae5; color: #065f46; }
        .badge-failed { background: #fee2e2; color: #b91c1c; }

        .action-btn {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border: none;
            font-size: 0.85rem;
            transition: 0.2s;
            margin: 0 2px;
        }
        .btn-success-custom { background: #d1fae5; color: #065f46; }
        .btn-success-custom:hover { background: #a7f3d0; }
        .btn-danger-custom { background: #fee2e2; color: #b91c1c; }
        .btn-danger-custom:hover { background: #fca5a5; }

        .pagination-custom .page-link {
            border-radius: 50px !important;
            margin: 0 4px;
            color: #4f46e5;
            border: 1px solid #e5e7eb;
        }
        .pagination-custom .page-item.active .page-link {
            background: #4f46e5;
            border-color: #4f46e5;
            color: #fff;
        }

        .login-container {
            max-width: 400px;
            margin: 80px auto;
            padding: 30px;
            background: #fff;
            border-radius: 28px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.08);
        }
        .login-container .form-control {
            border-radius: 50px;
            padding: 12px 20px;
        }
        .login-container .btn-login {
            border-radius: 50px;
            padding: 12px;
            background: #4f46e5;
            color: #fff;
            font-weight: 600;
            border: none;
            width: 100%;
        }
        .login-container .btn-login:hover {
            background: #7c3aed;
        }

        .toast-container-custom {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
        }
        .toast-custom {
            border-radius: 16px;
            box-shadow: 0 12px 30px rgba(0,0,0,0.12);
            border: none;
        }
        .spinner-overlay {
            display: none;
            position: fixed;
            top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.25);
            z-index: 9998;
            justify-content: center;
            align-items: center;
        }
        .spinner-overlay.show { display: flex; }
        .spinner-overlay .spinner-border { width: 3rem; height: 3rem; color: #4f46e5; }

        /* মোবাইলের জন্য বাড়তি সুন্দর্য */
        @media (max-width: 768px) {
            .card-header-custom { flex-direction: column; align-items: stretch; gap: 12px; }
            .card-header-custom h4 { font-size: 1.1rem; }
            .total-unpaid { font-size: 0.8rem; padding: 4px 14px; }
            .table-custom { font-size: 0.75rem; min-width: 650px; }
            .table-custom thead th, .table-custom tbody td { padding: 6px 8px; }
            .action-btn { width: 28px; height: 28px; font-size: 0.7rem; }
            .nav-tabs-custom .nav-link { padding: 6px 12px; font-size: 0.8rem; }
        }
        @media (max-width: 480px) {
            .container { padding: 0 8px; }
            .table-custom { font-size: 0.7rem; min-width: 580px; }
        }
    </style>
</head>
<body>

<!-- Loading Spinner -->
<div class="spinner-overlay" id="loadingSpinner">
    <div class="spinner-border" role="status"><span class="visually-hidden">Loading...</span></div>
</div>

<!-- Toast -->
<div class="toast-container-custom">
    <div id="liveToast" class="toast toast-custom" role="alert">
        <div class="toast-header" id="toastHeader">
            <strong id="toastTitle">Notification</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body" id="toastMessage">Message</div>
    </div>
</div>

<div class="container">
    <?php if (!$loggedIn): ?>
        <!-- Login Form -->
        <div class="login-container">
            <h4 class="text-center mb-4"><i class="fas fa-lock me-2"></i>Admin Login</h4>
            <form id="loginForm">
                <div class="mb-3">
                    <input type="text" class="form-control" id="adminUsername" placeholder="Username" required>
                </div>
                <div class="mb-3">
                    <input type="password" class="form-control" id="adminPassword" placeholder="Password" required>
                </div>
                <button type="submit" class="btn-login">Login</button>
            </form>
        </div>
    <?php else: ?>
        <!-- Dashboard -->
        <div class="main-card">
            <div class="card-header-custom">
                <h4><i class="fas fa-wallet"></i> Bunasex Payment Manager</h4>
                <div class="d-flex gap-2 align-items-center flex-wrap">
                    <span class="total-unpaid" id="totalUnpaid">
                        <i class="fas fa-coins"></i> Unpaid: <span id="unpaidAmount">0</span> ৳
                    </span>
                    <a href="?logout=1" class="btn-soft-light"><i class="fas fa-sign-out-alt"></i> Logout</a>
                </div>
            </div>

            <div class="card-body p-3">
                <!-- Tabs -->
                <ul class="nav nav-tabs-custom nav-pills mb-3" id="myTab" role="tablist">
                    <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#pendingTab" type="button">Pending</button></li>
                    <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#successTab" type="button">Success</button></li>
                    <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#failedTab" type="button">Failed</button></li>
                </ul>

                <div class="tab-content">
                    <!-- Pending -->
                    <div class="tab-pane fade show active" id="pendingTab">
                        <div class="table-responsive">
                            <table class="table table-custom">
                                <thead><tr>
                                    <th>ID</th>
                                    <th>Email</th>
                                    <th>Method</th>
                                    <th>Amount</th>
                                    <th>TrxID</th>
                                    <th>Date</th>
                                    <th>Action</th>
                                </tr></thead>
                                <tbody id="pendingBody"><tr><td colspan="7" class="text-center">Loading...</td></tr></tbody>
                            </table>
                        </div>
                        <div id="pendingPagination" class="d-flex justify-content-center mt-3"></div>
                    </div>

                    <!-- Success -->
                    <div class="tab-pane fade" id="successTab">
                        <div class="table-responsive">
                            <table class="table table-custom">
                                <thead><tr>
                                    <th>ID</th>
                                    <th>Email</th>
                                    <th>Method</th>
                                    <th>Amount</th>
                                    <th>TrxID</th>
                                    <th>Date</th>
                                </tr></thead>
                                <tbody id="successBody"><tr><td colspan="6" class="text-center">Loading...</td></tr></tbody>
                            </table>
                        </div>
                        <div id="successPagination" class="d-flex justify-content-center mt-3"></div>
                    </div>

                    <!-- Failed -->
                    <div class="tab-pane fade" id="failedTab">
                        <div class="table-responsive">
                            <table class="table table-custom">
                                <thead><tr>
                                    <th>ID</th>
                                    <th>Email</th>
                                    <th>Method</th>
                                    <th>Amount</th>
                                    <th>TrxID</th>
                                    <th>Date</th>
                                </tr></thead>
                                <tbody id="failedBody"><tr><td colspan="6" class="text-center">Loading...</td></tr></tbody>
                            </table>
                        </div>
                        <div id="failedPagination" class="d-flex justify-content-center mt-3"></div>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</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); ?>;
    const STATUSES = ['Pending', 'Success', 'Failed'];
    let currentPage = { Pending: 1, Success: 1, Failed: 1 };
    let lastPage = { Pending: 1, Success: 1, Failed: 1 };

    // Toast
    function showToast(message, type = 'success') {
        const header = $('#toastHeader'), title = $('#toastTitle'), body = $('#toastMessage');
        if (type === 'success') { header.removeClass('bg-danger bg-warning').addClass('bg-success text-white'); title.text('✅ Success'); }
        else if (type === 'warning') { header.removeClass('bg-success bg-danger').addClass('bg-warning text-dark'); title.text('⚠️ Warning'); }
        else { header.removeClass('bg-success bg-warning').addClass('bg-danger text-white'); title.text('❌ Error'); }
        body.text(message);
        new bootstrap.Toast($('#liveToast'), { delay: 3500 }).show();
    }

    function showLoading(show) {
        if (show) $('#loadingSpinner').addClass('show');
        else $('#loadingSpinner').removeClass('show');
    }

    // Login
    $('#loginForm').on('submit', function(e) {
        e.preventDefault();
        showLoading(true);
        $.post('bunasex_payment_api.php', {
            type: 'pending',
            admin_username: $('#adminUsername').val(),
            admin_password: $('#adminPassword').val()
        }, function(response) {
            showLoading(false);
            if (response.status === 'success') location.reload();
            else showToast(response.message || 'Login failed', 'error');
        }).fail(() => { showLoading(false); showToast('Server error', 'error'); });
    });

    // Fetch data with pagination
    function fetchData(status, page = 1) {
        showLoading(true);
        $.post('bunasex_payment_api.php', {
            type: 'get_all',
            status: status,
            page: page,
            per_page: DEFAULT_PER_PAGE
        }, function(response) {
            showLoading(false);
            const targetBody = status.toLowerCase() + 'Body';
            const paginationId = status.toLowerCase() + 'Pagination';

            if (response.status === 'success') {
                const data = response.data;
                const total = response.total;
                const current = response.current_page;
                const last = response.last_page;
                currentPage[status] = current;
                lastPage[status] = last;

                let html = '';
                if (data.length === 0) {
                    html = `<tr><td colspan="7" class="text-center text-muted">No records found</td></tr>`;
                } else {
                    data.forEach(row => {
                        // শুধু Pending-এ Action বাটন দেখাবে
                        const actions = (status === 'Pending') ? `
                            <button class="action-btn btn-success-custom approveBtn" data-id="${row.id}" title="Approve"><i class="fas fa-check"></i></button>
                            <button class="action-btn btn-danger-custom rejectBtn" data-id="${row.id}" title="Reject"><i class="fas fa-times"></i></button>
                        ` : '';
                        
                        // Name বাদ দিয়ে বাকি সব কলাম (সব ডিভাইসে দেখাবে)
                        html += `<tr>
                            <td>#${row.id}</td>
                            <td>${row.email}</td>
                            <td>${row.method}</td>
                            <td>${parseInt(row.amount).toLocaleString()} ৳</td>
                            <td>${row.trxid}</td>
                            <td><small>${row.date} ${row.time}</small></td>
                            <td>${actions}</td>
                        </tr>`;
                    });
                }
                $('#' + targetBody).html(html);

                // Pagination Render
                renderPagination(paginationId, status, current, last);
            } else {
                showToast(response.message || 'Failed to load data', 'error');
            }
        }).fail(() => { showLoading(false); showToast('Server error', 'error'); });
    }

    function renderPagination(containerId, status, current, last) {
        let html = `<ul class="pagination pagination-custom">`;
        html += `<li class="page-item ${current <= 1 ? 'disabled' : ''}"><a class="page-link" href="#" data-status="${status}" data-page="${current-1}">Prev</a></li>`;
        let start = Math.max(1, current - 2);
        let end = Math.min(last, current + 2);
        if (start > 1) html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        for (let i = start; i <= end; i++) {
            html += `<li class="page-item ${i === current ? 'active' : ''}"><a class="page-link" href="#" data-status="${status}" data-page="${i}">${i}</a></li>`;
        }
        if (end < last) html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        html += `<li class="page-item ${current >= last ? 'disabled' : ''}"><a class="page-link" href="#" data-status="${status}" data-page="${current+1}">Next</a></li>`;
        html += `</ul>`;
        $('#' + containerId).html(html);
    }

    // Pagination click
    $(document).on('click', '.pagination-custom .page-link', function(e) {
        e.preventDefault();
        const status = $(this).data('status');
        const page = $(this).data('page');
        if (page && page >= 1 && page <= lastPage[status]) {
            fetchData(status, page);
        }
    });

    // Approve
    $(document).on('click', '.approveBtn', function() {
        const id = $(this).data('id');
        if (!confirm('Approve this payment?')) return;
        showLoading(true);
        $.post('bunasex_payment_api.php', { type: 'success', id: id }, function(response) {
            showLoading(false);
            if (response.status === 'success') {
                showToast(response.message, 'success');
                loadAllData();
            } else showToast(response.message, 'error');
        }).fail(() => { showLoading(false); showToast('Server error', 'error'); });
    });

    // Reject
    $(document).on('click', '.rejectBtn', function() {
        const id = $(this).data('id');
        if (!confirm('Mark this payment as failed?')) return;
        showLoading(true);
        $.post('bunasex_payment_api.php', { type: 'failed', id: id }, function(response) {
            showLoading(false);
            if (response.status === 'success') {
                showToast(response.message, 'success');
                loadAllData();
            } else showToast(response.message, 'error');
        }).fail(() => { showLoading(false); showToast('Server error', 'error'); });
    });

    // Load Total Unpaid
    function loadTotalUnpaid() {
        $.post('bunasex_payment_api.php', { type: 'total_unpaid' }, function(response) {
            if (response.status === 'success') $('#unpaidAmount').text(response.total.toLocaleString());
        });
    }

    function loadAllData() {
        fetchData('Pending', currentPage.Pending);
        fetchData('Success', currentPage.Success);
        fetchData('Failed', currentPage.Failed);
        loadTotalUnpaid();
    }

    // Tab switch - sync data
    $('button[data-bs-toggle="tab"]').on('shown.bs.tab', function(e) {
        const target = $(e.target).attr('data-bs-target');
        if (target === '#pendingTab') fetchData('Pending', currentPage.Pending);
        else if (target === '#successTab') fetchData('Success', currentPage.Success);
        else if (target === '#failedTab') fetchData('Failed', currentPage.Failed);
    });

    // Logout
    <?php if (isset($_GET['logout'])): session_destroy(); header('Location: ' . $_SERVER['PHP_SELF']); exit; endif; ?>

    // Initial load
    <?php if ($loggedIn): ?>
        loadAllData();
    <?php endif; ?>
});
</script>
</body>
</html>