<?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>Premium Refund History</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">
    <!-- Modern Premium Font -->
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --primary: #6366f1;
            --primary-hover: #4f46e5;
            --secondary: #8b5cf6;
            --bg-light: #f3f4f6;
            --bg-white: #ffffff;
            --text-main: #0f172a;
            --text-muted: #64748b;
            --success: #10b981;
            --success-bg: #d1fae5;
            --danger: #ef4444;
            --danger-bg: #fee2e2;
            --warning: #f59e0b;
            --warning-bg: #fef3c7;
        }

        * { 
            font-family: 'Plus Jakarta Sans', sans-serif; 
            margin: 0; padding: 0; box-sizing: border-box;
        }
        
        body { 
            background: var(--bg-light); 
            min-height: 100vh; 
            color: var(--text-main);
            padding-bottom: 30px;
        }
        
        .container { 
            max-width: 768px; 
            padding: 0;
        }

        /* Top Header */
        .app-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 18px 24px;
            background: rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            position: sticky;
            top: 0;
            z-index: 100;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.03);
            border-bottom: 1px solid rgba(0,0,0,0.05);
        }
        .app-header h4 {
            margin: 0;
            color: var(--text-main);
            font-size: 20px;
            font-weight: 800;
            margin-left: 16px;
            letter-spacing: -0.5px;
        }
        .app-header .back-btn, .app-header .logout-btn {
            color: var(--text-muted);
            font-size: 20px;
            text-decoration: none;
            transition: 0.3s;
            width: 40px; height: 40px;
            display: flex; align-items: center; justify-content: center;
            border-radius: 50%;
            background: var(--bg-light);
        }
        .app-header .logout-btn:hover {
            color: var(--danger);
            background: var(--danger-bg);
        }

        /* Tabs Container */
        .tabs-wrapper {
            display: flex;
            justify-content: center;
            padding: 20px;
        }
        .nav-tabs-custom {
            background: var(--bg-white);
            border-radius: 100px;
            padding: 6px;
            display: inline-flex;
            box-shadow: 0 4px 15px rgba(0,0,0,0.04);
            border: 1px solid rgba(0,0,0,0.02);
            width: 100%;
            max-width: 500px;
        }
        .nav-tabs-custom .nav-item {
            flex: 1;
            list-style: none;
        }
        .nav-tabs-custom .nav-link {
            border-radius: 100px;
            color: var(--text-muted);
            background: transparent;
            border: none;
            padding: 12px 0;
            font-weight: 600;
            font-size: 15px;
            width: 100%;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .nav-tabs-custom .nav-link:hover {
            color: var(--primary);
        }
        .nav-tabs-custom .nav-link.active {
            background: var(--primary);
            color: #fff;
            box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
        }

        /* Card Animations */
        @keyframes slideUpFade {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* Premium Card Styles */
        .custom-refund-card {
            background: var(--bg-white);
            border-radius: 24px;
            margin: 0 20px 24px 20px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
            border: 1px solid rgba(0,0,0,0.03);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            animation: slideUpFade 0.4s ease forwards;
        }
        .custom-refund-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.08);
        }
        
        /* Card Top (Gradient) */
        .card-top {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            padding: 20px;
            display: flex;
            align-items: flex-start;
            position: relative;
        }
        .serial-badge {
            background: rgba(255, 255, 255, 0.2);
            backdrop-filter: blur(8px);
            color: #fff;
            font-weight: 800;
            width: 48px;
            height: 48px;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 14px;
            margin-right: 16px;
            flex-shrink: 0;
            font-size: 18px;
            border: 1px solid rgba(255,255,255,0.3);
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
        }
        .match-info {
            flex-grow: 1;
            padding-right: 10px;
        }
        .match-title {
            color: #fff;
            font-weight: 700;
            font-size: 16px;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            margin-bottom: 4px;
        }
        .match-id {
            color: rgba(255, 255, 255, 0.85);
            font-size: 13px;
            font-weight: 500;
            display: inline-block;
            background: rgba(0,0,0,0.15);
            padding: 2px 8px;
            border-radius: 6px;
        }
        .amount-badge-top {
            background: #fff;
            color: var(--primary);
            padding: 8px 16px;
            border-radius: 100px;
            font-weight: 800;
            font-size: 14px;
            white-space: nowrap;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }

        /* Card Body */
        .card-body-custom {
            padding: 20px;
        }
        .info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
        }
        .time-badge {
            background: var(--bg-light);
            color: var(--text-muted);
            padding: 6px 12px;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .status-badge {
            background: var(--danger-bg);
            color: var(--danger);
            padding: 6px 14px;
            border-radius: 100px;
            font-size: 12px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .action-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #f8fafc;
            padding: 12px;
            border-radius: 16px;
            border: 1px dashed #cbd5e1;
            margin-bottom: 16px;
        }
        .btn-refunded-by {
            background: #fff;
            color: var(--primary);
            border: 1px solid #e2e8f0;
            padding: 6px 16px;
            border-radius: 100px;
            font-weight: 700;
            font-size: 13px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.02);
        }
        .moderator-tag {
            background: var(--success-bg);
            color: var(--success);
            padding: 6px 14px;
            border-radius: 100px;
            font-size: 13px;
            font-weight: 700;
        }
        .amount-text {
            color: var(--success);
            font-weight: 800;
            font-size: 17px;
            display: flex;
            align-items: center;
            gap: 8px;
            padding-bottom: 8px;
        }
        .amount-icon {
            background: var(--success-bg);
            width: 32px; height: 32px;
            display: flex; justify-content: center; align-items: center;
            border-radius: 50%;
        }

        /* Card Footer sections */
        .email-section {
            background: #fff8f1;
            color: #ea580c;
            padding: 14px 20px;
            font-weight: 600;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 12px;
            border-top: 1px solid #ffedd5;
            cursor: pointer;
            transition: background 0.2s;
        }
        .email-section:hover {
            background: #ffedd5;
        }
        .footer-section {
            background: #f8fafc;
            color: var(--text-muted);
            padding: 14px 20px;
            font-weight: 600;
            font-size: 13px;
            display: flex;
            align-items: center;
            gap: 10px;
            border-top: 1px solid #f1f5f9;
        }

        /* Pagination Setup */
        .pagination-wrapper {
            padding: 0 20px 40px 20px;
        }
        .pagination-custom .page-link {
            border-radius: 12px !important;
            margin: 0 4px;
            background: var(--bg-white);
            border: 1px solid #e2e8f0;
            color: var(--text-main);
            font-weight: 600;
            padding: 8px 16px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.02);
            transition: all 0.2s;
        }
        .pagination-custom .page-item.active .page-link {
            background: var(--primary);
            border-color: var(--primary);
            color: #fff;
            box-shadow: 0 4px 10px rgba(99, 102, 241, 0.3);
        }
        .pagination-custom .page-link:hover:not(.active) {
            background: #f1f5f9;
            transform: translateY(-1px);
        }

        /* Premium Login Form */
        .login-wrapper {
            min-height: calc(100vh - 100px);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .login-card {
            width: 100%;
            max-width: 420px;
            background: var(--bg-white);
            border-radius: 28px;
            padding: 40px 30px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.06);
            border: 1px solid rgba(0,0,0,0.03);
            text-align: center;
        }
        .login-icon {
            width: 70px; height: 70px;
            background: var(--bg-light);
            color: var(--primary);
            border-radius: 20px;
            display: inline-flex;
            justify-content: center;
            align-items: center;
            font-size: 30px;
            margin-bottom: 20px;
            transform: rotate(-10deg);
        }
        .login-card h4 {
            font-weight: 800;
            color: var(--text-main);
            margin-bottom: 8px;
        }
        .login-card p {
            color: var(--text-muted);
            font-size: 14px;
            margin-bottom: 30px;
        }
        .login-card .form-control {
            border-radius: 16px;
            padding: 14px 20px;
            background: var(--bg-light);
            border: 2px solid transparent;
            font-weight: 500;
            font-size: 15px;
            transition: all 0.3s;
        }
        .login-card .form-control:focus {
            background: #fff;
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
        }
        .btn-login {
            border-radius: 16px;
            padding: 14px;
            background: var(--primary);
            color: #fff;
            font-weight: 700;
            font-size: 16px;
            border: none;
            width: 100%;
            margin-top: 10px;
            transition: all 0.3s;
            box-shadow: 0 8px 20px rgba(99, 102, 241, 0.3);
        }
        .btn-login:hover {
            background: var(--primary-hover);
            transform: translateY(-2px);
        }

        /* Toast & Loader */
        .toast-container-custom {
            position: fixed;
            bottom: 30px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 9999;
        }
        .toast-custom {
            background: var(--text-main);
            color: #fff;
            border-radius: 100px;
            padding: 12px 24px;
            font-weight: 500;
            box-shadow: 0 10px 30px rgba(0,0,0,0.15);
            border: none;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .toast-custom .btn-close { display: none; }
        
        .spinner-overlay {
            display: none;
            position: fixed;
            top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(255,255,255,0.8);
            backdrop-filter: blur(4px);
            z-index: 9998;
            justify-content: center;
            align-items: center;
        }
        .spinner-overlay.show { display: flex; }
        .spinner-border { color: var(--primary); width: 3rem; height: 3rem; border-width: 4px; }
        
    </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>

<!-- Custom Toast -->
<div class="toast-container-custom">
    <div id="liveToast" class="toast toast-custom align-items-center" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="d-flex">
            <div class="toast-body" id="toastMessage">
                <i class="fas fa-check-circle text-success me-2"></i> Message goes here
            </div>
        </div>
    </div>
</div>

<div class="container">
    <?php if (!$loggedIn): ?>
        <!-- Modern Login UI -->
        <div class="login-wrapper">
            <div class="login-card">
                <div class="login-icon"><i class="fas fa-fingerprint"></i></div>
                <h4>Admin Access</h4>
                <p>Please enter your credentials to continue</p>
                
                <form id="loginForm">
                    <div class="mb-3">
                        <input type="text" class="form-control" id="adminUsername" placeholder="Username" required>
                    </div>
                    <div class="mb-4">
                        <input type="password" class="form-control" id="adminPassword" placeholder="Password" required>
                    </div>
                    <button type="submit" class="btn-login">Secure Login <i class="fas fa-arrow-right ms-2"></i></button>
                </form>
            </div>
        </div>
    <?php else: ?>
        <!-- Header -->
        <div class="app-header">
            <div class="d-flex align-items-center">
                <a href="#" class="back-btn"><i class="fas fa-angle-left"></i></a>
                <h4>Refund History</h4>
            </div>
            <a href="?logout=1" class="logout-btn"><i class="fas fa-sign-out-alt"></i></a>
        </div>

        <!-- Floating Tabs -->
        <div class="tabs-wrapper">
            <ul class="nav nav-tabs-custom" id="myTab" role="tablist">
                <li class="nav-item">
                    <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#ownerTab" type="button">Owner</button>
                </li>
                <li class="nav-item">
                    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#moderatorTab" type="button">Moderator</button>
                </li>
            </ul>
        </div>

        <div class="tab-content">
            <!-- Owner Tab -->
            <div class="tab-pane fade show active" id="ownerTab">
                <div id="ownerContainer">
                    <div class="text-center text-muted py-5"><i class="fas fa-circle-notch fa-spin fa-2x mb-3"></i><br>Loading records...</div>
                </div>
                <div class="pagination-wrapper">
                    <div id="ownerPagination" class="d-flex justify-content-center"></div>
                </div>
            </div>

            <!-- Moderator Tab -->
            <div class="tab-pane fade" id="moderatorTab">
                <div id="moderatorContainer">
                    <div class="text-center text-muted py-5"><i class="fas fa-circle-notch fa-spin fa-2x mb-3"></i><br>Loading records...</div>
                </div>
                <div class="pagination-wrapper">
                    <div id="moderatorPagination" class="d-flex justify-content-center"></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); ?>;
    let currentPage = { owner: 1, moderator: 1 };
    let lastPage = { owner: 1, moderator: 1 };

    function showToast(message, type = 'success') {
        const body = $('#toastMessage');
        let icon = type === 'success' ? '<i class="fas fa-check-circle text-success me-2"></i>' : 
                  (type === 'warning' ? '<i class="fas fa-exclamation-triangle text-warning me-2"></i>' : 
                                        '<i class="fas fa-times-circle text-danger me-2"></i>');
        body.html(icon + message);
        new bootstrap.Toast($('#liveToast'), { delay: 3000 }).show();
    }

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

    // Secure Login
    $('#loginForm').on('submit', function(e) {
        e.preventDefault();
        showLoading(true);
        $.post('bunasex_refund_api.php', {
            type: 'get_all',
            moderator_type: 'owner',
            admin_username: $('#adminUsername').val(),
            admin_password: $('#adminPassword').val()
        }, function(response) {
            showLoading(false);
            if (response.status === 'success') location.reload();
            else showToast(response.message || 'Invalid credentials', 'error');
        }).fail(() => { showLoading(false); showToast('Server error connecting to API', 'error'); });
    });

    // Premium Card Rendering Engine
    function renderCards(containerId, data, currentPageNum) {
        const container = $('#' + containerId);
        if (data.length === 0) {
            container.html(`
                <div class="text-center py-5">
                    <div class="mb-3"><i class="fas fa-folder-open fa-3x" style="color:#cbd5e1;"></i></div>
                    <h5 class="text-muted fw-bold">No Records Found</h5>
                    <p class="text-muted small">History is currently empty.</p>
                </div>
            `);
            return;
        }
        let html = '';
        data.forEach((row, index) => {
            const serial = (currentPageNum - 1) * DEFAULT_PER_PAGE + index + 1;
            const matchTitle = row.match_title || 'Prologue Match ?? ????? ??? ??';
            const matchId = row.match_id || '#39695.0';
            const refundAmount = parseFloat(row.refunded_amount || 0).toFixed(2);
            const refundedAt = row.refunded_at || '2026-06-06 10:31:28';
            const refundedEmail = row.refunded_email || 'optalha1981@gmail.com';
            const moderator = row.moderator_username || 'SKM eSPORTS';

            // Animation delay for cascading effect
            const animDelay = (index % 10) * 0.05;

            html += `
                <div class="custom-refund-card" style="animation-delay: ${animDelay}s">
                    <div class="card-top">
                        <div class="serial-badge">${serial}</div>
                        <div class="match-info">
                            <div class="match-title">${matchTitle}</div>
                            <div class="match-id"><i class="fas fa-hashtag fa-sm"></i> ${matchId.replace('#','')}</div>
                        </div>
                        <div class="amount-badge-top">TK ${refundAmount}</div>
                    </div>
                    
                    <div class="card-body-custom">
                        <div class="info-row">
                            <div class="time-badge"><i class="far fa-clock"></i> ${refundedAt}</div>
                            <div class="status-badge">REFUNDED</div>
                        </div>
                        
                        <div class="action-row">
                            <div class="btn-refunded-by">Refunded By</div>
                            <div class="moderator-tag"><i class="fas fa-user-shield me-1"></i> ${moderator}</div>
                        </div>
                        
                        <div class="amount-text">
                            <div class="amount-icon"><i class="fas fa-money-bill-wave"></i></div>
                            Refund Amount: TK ${refundAmount}
                        </div>
                    </div>
                    
                    <div class="email-section copyable" onclick="copyText('${refundedEmail}')">
                        <i class="fas fa-envelope-open-text fa-lg"></i> 
                        <span style="flex-grow:1;">${refundedEmail}</span>
                        <i class="far fa-copy opacity-50"></i>
                    </div>
                    
                    <div class="footer-section">
                        <i class="fas fa-shield-alt"></i> Auth: ${moderator}
                    </div>
                </div>
            `;
        });
        container.html(html);
    }

    // Fetch Data from API
    function fetchData(moderatorType, page = 1) {
        showLoading(true);
        $.post('bunasex_refund_api.php', {
            type: 'get_all',
            moderator_type: moderatorType,
            page: page,
            per_page: DEFAULT_PER_PAGE
        }, function(response) {
            showLoading(false);
            const containerId = moderatorType + 'Container';
            const paginationId = moderatorType + 'Pagination';

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

                renderCards(containerId, data, current);
                renderPagination(paginationId, moderatorType, current, last);
            } else {
                showToast(response.message || 'Failed to load data', 'error');
            }
        }).fail(() => { showLoading(false); showToast('Server connection error', 'error'); });
    }

    // Pagination Builder
    function renderPagination(containerId, moderatorType, current, last) {
        if(last <= 1) { $('#' + containerId).html(''); return; }
        
        let html = `<ul class="pagination pagination-custom">`;
        html += `<li class="page-item ${current <= 1 ? 'disabled' : ''}"><a class="page-link" href="#" data-type="${moderatorType}" data-page="${current-1}"><i class="fas fa-chevron-left"></i></a></li>`;
        
        let start = Math.max(1, current - 1);
        let end = Math.min(last, current + 1);
        
        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-type="${moderatorType}" 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-type="${moderatorType}" data-page="${current+1}"><i class="fas fa-chevron-right"></i></a></li>`;
        html += `</ul>`;
        $('#' + containerId).html(html);
    }

    // Pagination Event Listeners
    $(document).on('click', '.pagination-custom .page-link', function(e) {
        e.preventDefault();
        const type = $(this).data('type');
        const page = $(this).data('page');
        if (page && page >= 1 && page <= lastPage[type]) {
            fetchData(type, page);
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    });

    // Handle Tab Switch
    $('button[data-bs-toggle="tab"]').on('shown.bs.tab', function(e) {
        const target = $(e.target).attr('data-bs-target');
        if (target === '#ownerTab') fetchData('owner', currentPage.owner);
        else if (target === '#moderatorTab') fetchData('moderator', currentPage.moderator);
    });

    // Premium Copy Function with fallback
    window.copyText = function(text) {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(text).then(() => {
                showToast('Email copied to clipboard!', 'success');
            }).catch(() => { fallbackCopy(text); });
        } else {
            fallbackCopy(text);
        }
    };

    function fallbackCopy(text) {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();
        try {
            document.execCommand('copy');
            showToast('Email copied to clipboard!', 'success');
        } catch (err) {
            showToast('Copy failed, please select manually.', 'error');
        }
        document.body.removeChild(textArea);
    }

    // Initial Load Logic
    <?php if (isset($_GET['logout'])): session_destroy(); header('Location: ' . $_SERVER['PHP_SELF']); exit; endif; ?>
    <?php if ($loggedIn): ?>
        fetchData('owner', 1);
    <?php endif; ?>
});
</script>
</body>
</html>