<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/wallet.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }

// Check if user has transaction management permission
if (!hasPermission('manage_transactions')) { die("Access Denied: You do not have permission to manage wallets."); }

$lang = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id = $_SESSION['user_id'];

$can_users = hasPermission('manage_users');
$can_sellers = hasPermission('manage_sellers');
$can_staff = hasPermission('manage_staff_roles');
$can_services = hasPermission('manage_services');
$can_orders = hasPermission('manage_orders');
$can_transactions = hasPermission('manage_transactions');
$can_tickets = hasPermission('manage_tickets');
$can_settings = hasPermission('manage_settings');

$success_msg = '';
$error_msg = '';
if (isset($_SESSION['flash_success'])) {
    $success_msg = $_SESSION['flash_success'];
    unset($_SESSION['flash_success']);
}
if (isset($_SESSION['flash_error'])) {
    $error_msg = $_SESSION['flash_error'];
    unset($_SESSION['flash_error']);
}

$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;
$wallet_balance = isset($user['wallet_balance']) ? $user['wallet_balance'] : '0.00';

$rzp_key = getSetting('razorpay_key_id', '');
$rzp_secret = getSetting('razorpay_key_secret', '');

// -----------------------------------------------------
// Handle Admin Wallet Recharge (Add Money)
// -----------------------------------------------------
if(isset($_POST['payment_id']) && isset($_POST['amount'])) {
    $amount = floatval($_POST['amount']);
    $pay_id = sanitize($_POST['payment_id']);
    
    if($amount > 0 && !empty($pay_id)) {
        $url = "https://api.razorpay.com/v1/payments/" . $pay_id;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERPWD, $rzp_key . ":" . $rzp_secret);
        $response = curl_exec($ch);
        curl_close($ch);
        
        $rzp_data = json_decode($response, true);
        
        if (isset($rzp_data['status']) && in_array($rzp_data['status'], ['authorized', 'captured'])) {
            $paid_amount = floatval($rzp_data['amount']) / 100; 
            
            if ($paid_amount >= $amount) {
                wallet_credit($db, $user_id, WALLET_MAIN, $amount, ['category' => 'deposit', 'description' => "Admin Wallet Recharge via Razorpay (Txn: $pay_id)", 'reference_type' => 'transaction']);
                
                $_SESSION['flash_success'] = "Money added to admin wallet successfully!";
                redirect('wallet.php#my_history');
            }
        }
        $_SESSION['flash_error'] = "Payment Verification Failed!";
        redirect('wallet.php#add_money');
    }
}

// -----------------------------------------------------
// Fetch Data for the 7 Panels
// -----------------------------------------------------

// 1. My History (Admin's own transactions)
$my_txns = $db->select("SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT 200", [$user_id]);

// 2. All History (Entire platform)
$all_txns = $db->select("SELECT t.*, u.name, u.user_type FROM transactions t JOIN users u ON t.user_id = u.id ORDER BY t.created_at DESC LIMIT 500");

// 3. Customer History
$customer_txns = $db->select("SELECT t.*, u.name FROM transactions t JOIN users u ON t.user_id = u.id WHERE u.user_type = 'customer' ORDER BY t.created_at DESC LIMIT 500");

/* ---------------------------------------------------------------------------
   SIDEBAR ROLE VIEW  —  wallet.php?role=all|free|pro|seller|employee|admin
   Loads one extra audience-filtered dataset and opens the matching panel.
   ------------------------------------------------------------------------ */
require_once __DIR__ . '/includes/role_filter.php';
$wb_role       = wb_role();
$wb_role_txns  = [];
$wb_start_tab  = 'add_money';
if ($wb_role !== '') {
    $wb_start_tab = 'role_view';
    $cond = wb_role_sql($wb_role, 'u');
    try {
        $wb_role_txns = $db->select(
            "SELECT t.*, u.name, u.user_type, u.mobile, COALESCE(u.is_subscribed,0) AS is_subscribed
               FROM transactions t
               JOIN users u ON t.user_id = u.id
              WHERE $cond
              ORDER BY t.created_at DESC
              LIMIT 500"
        );
    } catch (\Throwable $e) { $wb_role_txns = []; }
}

// 4. Seller History
$seller_txns = $db->select("SELECT t.*, u.name FROM transactions t JOIN users u ON t.user_id = u.id WHERE u.user_type = 'seller' ORDER BY t.created_at DESC LIMIT 500");

// 5. Staff History (Admin users)
$staff_txns = $db->select("SELECT t.*, u.name FROM transactions t JOIN users u ON t.user_id = u.id WHERE u.user_type = 'admin' ORDER BY t.created_at DESC LIMIT 500");

$unread_notifs = $db->select("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5", [$user_id]);
$unread_count = count($unread_notifs);

$company_logo = getSetting('company_logo', '../assets/images/logo.png');
$company_logo = (strpos($company_logo, 'http') === 0) ? $company_logo : '../' . ltrim($company_logo, '/');
$company_name = getSetting('company_name', 'WBMCZ');
$profile_image_url = !empty($user['profile_pic']) ? '../uploads/profiles/' . $user['profile_pic'] : null;

?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wallet Management - <?php echo htmlspecialchars($company_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style> body { font-family: 'Inter', sans-serif; scroll-behavior: smooth;} .hide-scrollbar::-webkit-scrollbar { display: none; } </style>
</head>
<body class="bg-gray-50" x-data="{ 
    sidebarOpen: window.innerWidth >= 768, 
    profileOpen: false, 
    notifOpen: false,
    currentTab: window.location.hash ? window.location.hash.substring(1) : '<?php echo $wb_start_tab; ?>'
}" @hashchange.window="currentTab = window.location.hash.substring(1) || '<?php echo $wb_start_tab; ?>'">

    <div class="flex h-screen overflow-hidden">
        
        <?php include __DIR__ . '/includes/sidebar.php'; ?>
        <div class="flex-1 flex flex-col min-w-0 bg-gray-50 overflow-hidden">
            
            <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40 relative">
                <div class="flex items-center">
                    <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 focus:outline-none rounded-lg hover:bg-gray-100 transition-colors">
                        <i class="fas fa-bars text-xl"></i>
                    </button>
                    <h2 class="text-xl font-bold hidden md:block text-slate-800">Wallet Management</h2>
                </div>

                <div class="flex items-center space-x-3 sm:space-x-5 ml-auto">
                    <div class="relative">
                        <button @click="notifOpen = !notifOpen" @click.away="notifOpen = false" class="relative p-2 text-gray-400 hover:text-emerald-600 transition-colors focus:outline-none">
                            <i class="fas fa-bell text-xl"></i>
                            <?php if($unread_count > 0): ?>
                                <span class="absolute top-1 right-1 w-4 h-4 bg-rose-500 border-2 border-white rounded-full flex items-center justify-center text-[9px] font-bold text-white"><?php echo $unread_count; ?></span>
                            <?php endif; ?>
                        </button>
                        <div x-show="notifOpen" x-transition class="absolute right-[-60px] sm:right-0 mt-3 w-[300px] sm:w-80 bg-white rounded-xl shadow-2xl border border-gray-100 overflow-hidden z-50 text-gray-800" style="display: none;">
                            <div class="px-4 py-8 text-center text-gray-500 text-sm">
                                <div class="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-3 text-gray-400"><i class="fas fa-bell-slash text-xl"></i></div>
                                No new alerts
                            </div>
                        </div>
                    </div>

                    <div class="relative">
                        <button @click="profileOpen = !profileOpen" @click.away="profileOpen = false" class="flex items-center focus:outline-none">
                            <?php if(!empty($profile_image_url) && file_exists($profile_image_url)): ?>
                                <img src="<?php echo $profile_image_url; ?>" class="w-10 h-10 rounded-full border-2 border-emerald-100 shadow-sm object-cover">
                            <?php else: ?>
                                <div class="w-10 h-10 rounded-full bg-emerald-100 border-2 border-emerald-200 text-emerald-600 flex items-center justify-center text-lg font-bold shadow-sm">
                                    <?php echo strtoupper(substr($user['name'], 0, 1)); ?>
                                </div>
                            <?php endif; ?>
                        </button>
                        <div x-show="profileOpen" x-transition class="absolute right-0 mt-3 w-56 bg-white rounded-xl shadow-2xl py-2 border border-gray-100 z-50 text-gray-800" style="display: none;">
                            <div class="px-4 py-3 border-b border-gray-100">
                                <p class="text-sm font-bold text-gray-900 truncate"><?php echo htmlspecialchars($user['name']); ?></p>
                                <p class="text-xs text-gray-500 mt-1"><?php echo htmlspecialchars($user['mobile']); ?></p>
                            </div>
                            <div class="border-t border-gray-100 pt-2 pb-2">
                                <a href="../logout.php" onclick="return confirm('<?php echo $lang->translate('confirm_logout', 'Are you sure?'); ?>');" class="block px-4 py-2 text-sm text-rose-600 hover:bg-rose-50 transition-colors"><i class="fas fa-sign-out-alt mr-2 w-5 text-center"></i> Logout</a>
                            </div>
                        </div>
                    </div>
                </div>
            </header>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8 relative">

                <?php if ($success_msg): ?>
                <div class="mb-6 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl relative flex items-center shadow-sm" role="alert">
                    <i class="fas fa-check-circle text-xl mr-3"></i>
                    <span class="block sm:inline font-medium"><?php echo $success_msg; ?></span>
                </div>
                <?php endif; ?>

                <?php if ($error_msg): ?>
                <div class="mb-6 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl relative flex items-center shadow-sm" role="alert">
                    <i class="fas fa-exclamation-circle text-xl mr-3"></i>
                    <span class="block sm:inline font-medium"><?php echo $error_msg; ?></span>
                </div>
                <?php endif; ?>

                <div class="max-w-6xl mx-auto pb-20">

                    <!-- ============ AUDIENCE (ROLE) VIEW — opened from the sidebar ============ -->
                    <div x-show="currentTab === 'role_view'" style="display:none;" x-transition.opacity>
                        <div class="mb-6">
                            <h2 class="text-2xl font-bold text-slate-800 mb-4">
                                <i class="fas <?php echo wb_role_icon($wb_role ?: 'all'); ?> text-emerald-600 mr-2"></i>
                                Wallet — <?php echo htmlspecialchars(wb_role_label($wb_role ?: 'all')); ?>
                            </h2>
                            <?php echo wb_role_tabs($wb_role, 'wallet.php'); ?>
                        </div>

                        <?php
                        $wb_cr = 0; $wb_dr = 0;
                        foreach ($wb_role_txns as $t) {
                            if (($t['type'] ?? '') === 'credit') $wb_cr += (float)$t['amount']; else $wb_dr += (float)$t['amount'];
                        }
                        ?>
                        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">
                            <div class="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm">
                                <p class="text-[11px] font-bold uppercase tracking-widest text-slate-400 mb-1">Entries</p>
                                <p class="text-2xl font-extrabold text-slate-800"><?php echo count($wb_role_txns); ?></p>
                            </div>
                            <div class="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm">
                                <p class="text-[11px] font-bold uppercase tracking-widest text-slate-400 mb-1">Total Credit</p>
                                <p class="text-2xl font-extrabold text-emerald-600">&#8377;<?php echo number_format($wb_cr, 2); ?></p>
                            </div>
                            <div class="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm">
                                <p class="text-[11px] font-bold uppercase tracking-widest text-slate-400 mb-1">Total Debit</p>
                                <p class="text-2xl font-extrabold text-rose-600">&#8377;<?php echo number_format($wb_dr, 2); ?></p>
                            </div>
                        </div>

                        <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="overflow-x-auto">
                                <table class="w-full text-sm">
                                    <thead class="bg-slate-50 text-slate-500 text-[11px] uppercase tracking-wider">
                                        <tr>
                                            <th class="px-5 py-3 text-left font-bold">User</th>
                                            <th class="px-5 py-3 text-left font-bold">Description</th>
                                            <th class="px-5 py-3 text-right font-bold">Amount</th>
                                            <th class="px-5 py-3 text-left font-bold">Status</th>
                                            <th class="px-5 py-3 text-left font-bold">Date</th>
                                        </tr>
                                    </thead>
                                    <tbody class="divide-y divide-slate-100">
                                    <?php if (empty($wb_role_txns)): ?>
                                        <tr><td colspan="5" class="px-5 py-12 text-center text-slate-400">
                                            <i class="fas fa-inbox text-3xl mb-3 block text-slate-300"></i>No wallet activity for this audience yet.
                                        </td></tr>
                                    <?php else: foreach ($wb_role_txns as $t): ?>
                                        <tr class="hover:bg-slate-50/70 transition-colors">
                                            <td class="px-5 py-3">
                                                <p class="font-bold text-slate-800"><?php echo htmlspecialchars($t['name'] ?? '—'); ?></p>
                                                <p class="text-[11px] text-slate-400"><?php echo htmlspecialchars($t['mobile'] ?? ''); ?></p>
                                            </td>
                                            <td class="px-5 py-3 text-slate-600"><?php echo htmlspecialchars($t['description'] ?? ''); ?></td>
                                            <td class="px-5 py-3 text-right font-extrabold <?php echo ($t['type'] ?? '') === 'credit' ? 'text-emerald-600' : 'text-rose-600'; ?>">
                                                <?php echo (($t['type'] ?? '') === 'credit' ? '+' : '-'); ?>&#8377;<?php echo number_format((float)$t['amount'], 2); ?>
                                            </td>
                                            <td class="px-5 py-3">
                                                <span class="px-2.5 py-1 rounded-full text-[10px] font-bold bg-slate-100 text-slate-600"><?php echo htmlspecialchars($t['status'] ?? ''); ?></span>
                                            </td>
                                            <td class="px-5 py-3 text-slate-500 text-xs whitespace-nowrap"><?php echo date('d M Y, h:i A', strtotime($t['created_at'])); ?></td>
                                        </tr>
                                    <?php endforeach; endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <div x-show="currentTab === 'add_money'" style="display:none;" x-transition.opacity>
                        <div class="mb-6 flex justify-between items-center">
                            <h2 class="text-2xl font-bold text-slate-800"><i class="fas fa-plus-circle text-emerald-600 mr-2"></i> Add Money to Admin Wallet</h2>
                        </div>
                        <div class="flex flex-col md:flex-row gap-6">
                            <div class="w-full md:w-1/3">
                                <div class="bg-gradient-to-br from-emerald-600 to-teal-700 rounded-2xl p-6 text-white shadow-lg relative overflow-hidden flex flex-col justify-center h-full">
                                    <div class="absolute -right-10 -bottom-10 w-48 h-48 bg-white/10 rounded-full blur-2xl"></div>
                                    <div class="relative z-10 text-center">
                                        <p class="text-emerald-100 font-bold uppercase tracking-widest text-xs mb-2">System Admin Balance</p>
                                        <h3 class="text-4xl font-extrabold mb-6">₹<?php echo number_format($wallet_balance, 2); ?></h3>
                                    </div>
                                </div>
                            </div>
                            <div class="w-full md:w-2/3 bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                                <div class="p-6 md:p-8">
                                    <div class="mb-8">
                                        <label class="block text-sm font-bold text-gray-700 mb-3">Enter Amount to Recharge (₹)</label>
                                        <div class="relative">
                                            <span class="absolute inset-y-0 left-0 w-14 flex items-center justify-center text-gray-400 font-bold text-2xl pointer-events-none">₹</span>
                                            <input type="number" id="amount_input" min="1" step="1" required class="w-full pl-14 pr-4 py-5 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-emerald-500 text-3xl font-extrabold text-gray-800 transition-all shadow-inner" placeholder="0.00">
                                        </div>
                                    </div>
                                    <form id="razorpayForm" method="POST" class="hidden">
                                        <input type="hidden" name="amount" id="rzp_amount">
                                        <input type="hidden" name="payment_id" id="rzp_payment_id">
                                    </form>
                                    <button type="button" @click="payViaRazorpay()" class="w-full bg-slate-800 hover:bg-slate-900 text-white font-bold py-4 px-6 rounded-xl shadow-lg transition-colors text-lg flex items-center justify-center">
                                        <i class="fas fa-shield-alt mr-3"></i> Secure Admin Recharge
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div x-show="currentTab === 'my_history'" style="display:none;" x-transition.opacity>
                        <div class="mb-6 flex justify-between items-center">
                            <h2 class="text-2xl font-bold text-slate-800"><i class="fas fa-history text-emerald-600 mr-2"></i> My Admin Wallet History</h2>
                        </div>
                        <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="overflow-x-auto">
                                <table class="w-full text-left border-collapse">
                                    <thead>
                                        <tr class="bg-slate-50 text-xs text-slate-500 uppercase tracking-wider border-b border-gray-100">
                                            <th class="p-4 pl-6 font-semibold border-b border-gray-200">Date & Time</th>
                                            <th class="p-4 font-semibold border-b border-gray-200">Description</th>
                                            <th class="p-4 font-semibold border-b border-gray-200 text-right">Type</th>
                                            <th class="p-4 font-semibold border-b border-gray-200 text-right pr-6">Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody class="divide-y divide-gray-50">
                                        <?php if(!empty($my_txns)): foreach($my_txns as $t): ?>
                                        <tr class="hover:bg-gray-50 transition-colors">
                                            <td class="p-4 pl-6 text-xs text-gray-500 whitespace-nowrap">
                                                <span class="font-bold text-gray-700 block mb-0.5"><?php echo date('d M Y', strtotime($t['created_at'])); ?></span>
                                                <span><?php echo date('h:i A', strtotime($t['created_at'])); ?></span>
                                            </td>
                                            <td class="p-4"><p class="font-medium text-gray-800 text-sm"><?php echo htmlspecialchars($t['description']); ?></p></td>
                                            <td class="p-4 text-right">
                                                <?php if($t['type'] == 'credit'): ?>
                                                    <span class="px-2 py-1 bg-emerald-100 text-emerald-700 text-[10px] font-bold uppercase rounded">Credit</span>
                                                <?php else: ?>
                                                    <span class="px-2 py-1 bg-rose-100 text-rose-700 text-[10px] font-bold uppercase rounded">Debit</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="p-4 text-right pr-6">
                                                <span class="font-extrabold <?php echo $t['type'] == 'credit' ? 'text-emerald-600' : 'text-rose-600'; ?>">
                                                    <?php echo $t['type'] == 'credit' ? '+' : '-'; ?>₹<?php echo number_format($t['amount'], 2); ?>
                                                </span>
                                            </td>
                                        </tr>
                                        <?php endforeach; else: ?>
                                            <tr><td colspan="4" class="p-10 text-center text-gray-500 font-medium">No transactions found in your admin wallet.</td></tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <div x-show="currentTab === 'move_bank'" style="display:none;" x-transition.opacity>
                        <div class="mb-6 flex justify-between items-center">
                            <h2 class="text-2xl font-bold text-slate-800"><i class="fas fa-university text-emerald-600 mr-2"></i> Move to Bank</h2>
                        </div>
                        <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="px-6 py-5 border-b border-gray-100 bg-gray-50/50">
                                <h3 class="text-lg font-bold text-gray-800"><i class="fas fa-money-check-alt text-emerald-600 mr-2"></i> Admin Bank Withdrawal</h3>
                            </div>
                            <div class="p-16 text-center text-gray-500">
                                <div class="w-20 h-20 bg-emerald-50 rounded-full flex items-center justify-center mx-auto mb-5 text-emerald-600 text-3xl border border-emerald-100">
                                    <i class="fas fa-university"></i>
                                </div>
                                <h3 class="text-2xl font-extrabold text-gray-800 mb-2">Coming Soon</h3>
                                <p class="text-gray-500 max-w-sm mx-auto">The secure admin bank withdrawal portal is currently under development.</p>
                            </div>
                        </div>
                    </div>

                   <div x-show="currentTab === 'all_history'" style="display:none;" x-transition.opacity>
                        <div class="mb-6 flex justify-between items-center">
                            <h2 class="text-2xl font-bold text-slate-800"><i class="fas fa-globe text-emerald-600 mr-2"></i> Global Wallet History</h2>
                        </div>
                        <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="overflow-x-auto">
                                <table class="w-full text-left border-collapse">
                                    <thead>
                                        <tr class="bg-slate-50 text-xs text-slate-500 uppercase tracking-wider border-b border-gray-100">
                                            <th class="p-4 pl-6 font-semibold border-b border-gray-200">Date & Time</th>
                                            <th class="p-4 font-semibold border-b border-gray-200">User Detail</th>
                                            <th class="p-4 font-semibold border-b border-gray-200">Description</th>
                                            <th class="p-4 font-semibold border-b border-gray-200 text-right">Type</th>
                                            <th class="p-4 font-semibold border-b border-gray-200 text-right pr-6">Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody class="divide-y divide-gray-50">
                                        <?php if(!empty($all_txns)): foreach($all_txns as $t): ?>
                                        <tr class="hover:bg-gray-50 transition-colors">
                                            <td class="p-4 pl-6 text-xs text-gray-500 whitespace-nowrap">
                                                <span class="font-bold text-gray-700 block mb-0.5"><?php echo date('d M Y', strtotime($t['created_at'])); ?></span>
                                                <span><?php echo date('h:i A', strtotime($t['created_at'])); ?></span>
                                            </td>
                                            <td class="p-4 whitespace-nowrap">
                                                <span class="font-bold text-gray-800 block text-sm"><?php echo htmlspecialchars($t['name']); ?></span>
                                                <span class="text-[10px] font-bold uppercase tracking-wider text-slate-500"><?php echo htmlspecialchars($t['user_type']); ?></span>
                                            </td>
                                            <td class="p-4"><p class="font-medium text-gray-800 text-sm"><?php echo htmlspecialchars($t['description']); ?></p></td>
                                            <td class="p-4 text-right">
                                                <?php if($t['type'] == 'credit'): ?>
                                                    <span class="px-2 py-1 bg-emerald-100 text-emerald-700 text-[10px] font-bold uppercase rounded">Credit</span>
                                                <?php else: ?>
                                                    <span class="px-2 py-1 bg-rose-100 text-rose-700 text-[10px] font-bold uppercase rounded">Debit</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="p-4 text-right pr-6">
                                                <span class="font-extrabold <?php echo $t['type'] == 'credit' ? 'text-emerald-600' : 'text-rose-600'; ?>">
                                                    <?php echo $t['type'] == 'credit' ? '+' : '-'; ?>₹<?php echo number_format($t['amount'], 2); ?>
                                                </span>
                                            </td>
                                        </tr>
                                        <?php endforeach; else: ?>
                                            <tr><td colspan="5" class="p-10 text-center text-gray-500 font-medium">No global transactions found.</td></tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <div x-show="currentTab === 'customer_history'" style="display:none;" x-transition.opacity>
                        <div class="mb-6 flex justify-between items-center">
                            <h2 class="text-2xl font-bold text-slate-800"><i class="fas fa-users text-blue-500 mr-2"></i> Customer Wallet History</h2>
                        </div>
                        <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="overflow-x-auto">
                                <table class="w-full text-left border-collapse">
                                    <thead>
                                        <tr class="bg-slate-50 text-xs text-slate-500 uppercase tracking-wider border-b border-gray-100">
                                            <th class="p-4 pl-6 font-semibold border-b border-gray-200">Date & Time</th>
                                            <th class="p-4 font-semibold border-b border-gray-200">Customer Name</th>
                                            <th class="p-4 font-semibold border-b border-gray-200">Description</th>
                                            <th class="p-4 font-semibold border-b border-gray-200 text-right">Type</th>
                                            <th class="p-4 font-semibold border-b border-gray-200 text-right pr-6">Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody class="divide-y divide-gray-50">
                                        <?php if(!empty($customer_txns)): foreach($customer_txns as $t): ?>
                                        <tr class="hover:bg-gray-50 transition-colors">
                                            <td class="p-4 pl-6 text-xs text-gray-500 whitespace-nowrap">
                                                <span class="font-bold text-gray-700 block mb-0.5"><?php echo date('d M Y', strtotime($t['created_at'])); ?></span>
                                                <span><?php echo date('h:i A', strtotime($t['created_at'])); ?></span>
                                            </td>
                                            <td class="p-4 font-bold text-gray-800 text-sm whitespace-nowrap"><?php echo htmlspecialchars($t['name']); ?></td>
                                            <td class="p-4"><p class="font-medium text-gray-800 text-sm"><?php echo htmlspecialchars($t['description']); ?></p></td>
                                            <td class="p-4 text-right">
                                                <?php if($t['type'] == 'credit'): ?>
                                                    <span class="px-2 py-1 bg-emerald-100 text-emerald-700 text-[10px] font-bold uppercase rounded">Credit</span>
                                                <?php else: ?>
                                                    <span class="px-2 py-1 bg-rose-100 text-rose-700 text-[10px] font-bold uppercase rounded">Debit</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="p-4 text-right pr-6">
                                                <span class="font-extrabold <?php echo $t['type'] == 'credit' ? 'text-emerald-600' : 'text-rose-600'; ?>">
                                                    <?php echo $t['type'] == 'credit' ? '+' : '-'; ?>₹<?php echo number_format($t['amount'], 2); ?>
                                                </span>
                                            </td>
                                        </tr>
                                        <?php endforeach; else: ?>
                                            <tr><td colspan="5" class="p-10 text-center text-gray-500 font-medium">No customer transactions found.</td></tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <div x-show="currentTab === 'seller_history'" style="display:none;" x-transition.opacity>
                        <div class="mb-6 flex justify-between items-center">
                            <h2 class="text-2xl font-bold text-slate-800"><i class="fas fa-store text-purple-500 mr-2"></i> Seller Wallet History</h2>
                        </div>
                        <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="overflow-x-auto">
                                <table class="w-full text-left border-collapse">
                                    <thead>
                                        <tr class="bg-slate-50 text-xs text-slate-500 uppercase tracking-wider border-b border-gray-100">
                                            <th class="p-4 pl-6 font-semibold border-b border-gray-200">Date & Time</th>
                                            <th class="p-4 font-semibold border-b border-gray-200">Seller Name</th>
                                            <th class="p-4 font-semibold border-b border-gray-200">Description</th>
                                            <th class="p-4 font-semibold border-b border-gray-200 text-right">Type</th>
                                            <th class="p-4 font-semibold border-b border-gray-200 text-right pr-6">Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody class="divide-y divide-gray-50">
                                        <?php if(!empty($seller_txns)): foreach($seller_txns as $t): ?>
                                        <tr class="hover:bg-gray-50 transition-colors">
                                            <td class="p-4 pl-6 text-xs text-gray-500 whitespace-nowrap">
                                                <span class="font-bold text-gray-700 block mb-0.5"><?php echo date('d M Y', strtotime($t['created_at'])); ?></span>
                                                <span><?php echo date('h:i A', strtotime($t['created_at'])); ?></span>
                                            </td>
                                            <td class="p-4 font-bold text-gray-800 text-sm whitespace-nowrap"><?php echo htmlspecialchars($t['name']); ?></td>
                                            <td class="p-4"><p class="font-medium text-gray-800 text-sm"><?php echo htmlspecialchars($t['description']); ?></p></td>
                                            <td class="p-4 text-right">
                                                <?php if($t['type'] == 'credit'): ?>
                                                    <span class="px-2 py-1 bg-emerald-100 text-emerald-700 text-[10px] font-bold uppercase rounded">Credit</span>
                                                <?php else: ?>
                                                    <span class="px-2 py-1 bg-rose-100 text-rose-700 text-[10px] font-bold uppercase rounded">Debit</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="p-4 text-right pr-6">
                                                <span class="font-extrabold <?php echo $t['type'] == 'credit' ? 'text-emerald-600' : 'text-rose-600'; ?>">
                                                    <?php echo $t['type'] == 'credit' ? '+' : '-'; ?>₹<?php echo number_format($t['amount'], 2); ?>
                                                </span>
                                            </td>
                                        </tr>
                                        <?php endforeach; else: ?>
                                            <tr><td colspan="5" class="p-10 text-center text-gray-500 font-medium">No seller transactions found.</td></tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <div x-show="currentTab === 'staff_history'" style="display:none;" x-transition.opacity>
                        <div class="mb-6 flex justify-between items-center">
                            <h2 class="text-2xl font-bold text-slate-800"><i class="fas fa-id-badge text-amber-500 mr-2"></i> Staff Wallet History</h2>
                        </div>
                        <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="overflow-x-auto">
                                <table class="w-full text-left border-collapse">
                                    <thead>
                                        <tr class="bg-slate-50 text-xs text-slate-500 uppercase tracking-wider border-b border-gray-100">
                                            <th class="p-4 pl-6 font-semibold border-b border-gray-200">Date & Time</th>
                                            <th class="p-4 font-semibold border-b border-gray-200">Staff Name</th>
                                            <th class="p-4 font-semibold border-b border-gray-200">Description</th>
                                            <th class="p-4 font-semibold border-b border-gray-200 text-right">Type</th>
                                            <th class="p-4 font-semibold border-b border-gray-200 text-right pr-6">Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody class="divide-y divide-gray-50">
                                        <?php if(!empty($staff_txns)): foreach($staff_txns as $t): ?>
                                        <tr class="hover:bg-gray-50 transition-colors">
                                            <td class="p-4 pl-6 text-xs text-gray-500 whitespace-nowrap">
                                                <span class="font-bold text-gray-700 block mb-0.5"><?php echo date('d M Y', strtotime($t['created_at'])); ?></span>
                                                <span><?php echo date('h:i A', strtotime($t['created_at'])); ?></span>
                                            </td>
                                            <td class="p-4 font-bold text-gray-800 text-sm whitespace-nowrap"><?php echo htmlspecialchars($t['name']); ?></td>
                                            <td class="p-4"><p class="font-medium text-gray-800 text-sm"><?php echo htmlspecialchars($t['description']); ?></p></td>
                                            <td class="p-4 text-right">
                                                <?php if($t['type'] == 'credit'): ?>
                                                    <span class="px-2 py-1 bg-emerald-100 text-emerald-700 text-[10px] font-bold uppercase rounded">Credit</span>
                                                <?php else: ?>
                                                    <span class="px-2 py-1 bg-rose-100 text-rose-700 text-[10px] font-bold uppercase rounded">Debit</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="p-4 text-right pr-6">
                                                <span class="font-extrabold <?php echo $t['type'] == 'credit' ? 'text-emerald-600' : 'text-rose-600'; ?>">
                                                    <?php echo $t['type'] == 'credit' ? '+' : '-'; ?>₹<?php echo number_format($t['amount'], 2); ?>
                                                </span>
                                            </td>
                                        </tr>
                                        <?php endforeach; else: ?>
                                            <tr><td colspan="5" class="p-10 text-center text-gray-500 font-medium">No staff transactions found.</td></tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                </div>
            </main>
        </div>
    </div>

    <script>
        // Razorpay Logic for Admin Add Money
        const rzpKey = "<?php echo $rzp_key; ?>";
        const companyName = "<?php echo addslashes($company_name); ?>";
        const userName = "<?php echo addslashes($user['name']); ?>";
        const userEmail = "<?php echo addslashes($user['email']); ?>";
        const userPhone = "<?php echo addslashes($user['mobile']); ?>";

        function payViaRazorpay() {
            const amount = parseFloat(document.getElementById('amount_input').value);
            if(isNaN(amount) || amount <= 0) {
                alert('Please enter a valid amount!');
                return;
            }

            var options = {
                "key": rzpKey,
                "amount": amount * 100, // Amount in paise
                "currency": "INR",
                "name": companyName,
                "description": "Admin Wallet Recharge",
                "handler": function (response) {
                    document.getElementById('rzp_amount').value = amount;
                    document.getElementById('rzp_payment_id').value = response.razorpay_payment_id;
                    document.getElementById('razorpayForm').submit();
                },
                "prefill": {
                    "name": userName,
                    "email": userEmail,
                    "contact": userPhone
                },
                "theme": {
                    "color": "#0f766e" // Tailwind emerald-600 to match Admin theme
                }
            };
            var rzp1 = new Razorpay(options);
            rzp1.open();
        }
    </script>
</body>
</html>