<?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';
require_once __DIR__ . '/includes/bank_view.php';

// Ensure user is logged in
if (!isLoggedIn()) {
    redirect('login.php');
}

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

// PRG Flash Messages Setup
$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']);
}

// Fetch user data early to use balance
$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 Secure Razorpay Wallet Recharge
if(isset($_POST['payment_id']) && isset($_POST['amount'])) {
    $amount = floatval($_POST['amount']);
    $pay_id = sanitize($_POST['payment_id']);
    
    if($amount > 0 && !empty($pay_id)) {
        // Securely verify payment with Razorpay API
        $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) {
                // Deposits always land in the MAIN wallet
                wallet_credit($db, $user_id, WALLET_MAIN, $amount, [
                    'category'       => 'deposit',
                    'description'    => "Wallet Recharge via Razorpay (Txn: $pay_id)",
                    'reference_type' => 'transaction',
                ]);

                $_SESSION['flash_success'] = "Money added to your main wallet successfully!";
                redirect('wallet.php#history');
            }
        }
        
        $_SESSION['flash_error'] = "Payment Verification Failed! Security alert generated.";
        redirect('wallet.php#add_money');
    }
}

/* ---- Wallet to Bank: bank form + withdrawal request ---- */
bank_handle_post($db, $user_id, '', 'wallet.php#to_bank');

// Re-fetch balance after any transactions
$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';

/* ---- Dual wallet ---- */
$wal      = wallet_balances($db, $user_id);
$wal_sum  = wallet_summary($db, $user_id);
$virt_rows = wallet_history($db, $user_id, ['wallet' => 'virtual', 'limit' => 300]);
$bank_data = bank_page_data($db, $user_id);

$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;

// Determine dashboard link based on role
$dashboard_link = 'dashboard.php';
if ($user['user_type'] == 'seller') { $dashboard_link = 'seller/index.php'; } 
elseif ($user['user_type'] == 'admin') { $dashboard_link = 'admin/index.php'; }

// Fetch ALL active categories for the Sidebar Dropdown
$all_categories = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");

// Fetch Transactions
$credits = $db->select("SELECT * FROM transactions WHERE user_id = ? AND type = 'credit' ORDER BY created_at DESC", [$user_id]);
$debits = $db->select("SELECT * FROM transactions WHERE user_id = ? AND type = 'debit' ORDER BY created_at DESC", [$user_id]);

// Organize Debits by Category
$expense_categories = [];
foreach($debits as $d) {
    if (strpos($d['description'], 'Move to Bank') !== false) {
        $cat_name = 'Bank Withdrawals';
    } else {
        $cat_name = str_replace(['Purchased: ', 'Paid for: ', 'Paid via Razorpay'], '', $d['description']);
        $cat_name = preg_replace('/\(ID: [^)]+\) for /', '', $cat_name);
        $cat_name = trim($cat_name);
    }

    if (!isset($expense_categories[$cat_name])) {
        $expense_categories[$cat_name] = ['total' => 0, 'count' => 0, 'transactions' => []];
    }
    $expense_categories[$cat_name]['total'] += $d['amount'];
    $expense_categories[$cat_name]['count'] += 1;
    $expense_categories[$cat_name]['transactions'][] = $d;
}

$expense_data = [];
foreach($expense_categories as $name => $data) {
    $expense_data[] = [
        'category' => $name,
        'total' => $data['total'],
        'count' => $data['count'],
        'transactions' => $data['transactions']
    ];
}
usort($expense_data, function($a, $b) { return $b['total'] <=> $a['total']; });
?>
<!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><?php echo $lang->translate('wallet', 'Wallet'); ?> - <?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=Poppins:wght@300;400;600&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style> body { font-family: 'Inter', sans-serif; scroll-behavior: smooth; } .font-poppins { font-family: 'Poppins', sans-serif; } .hide-scrollbar::-webkit-scrollbar { display: none; } .hide-scrollbar { -ms-overflow-style: none; scrollbar-width: none; } </style>
</head>
<?php
/* ===== Premium shared layout (Navy + Gold) ===== */
require_once __DIR__ . '/includes/theme.php';
$__cats = isset($all_categories) ? $all_categories : $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
$__subs = isset($sidebar_subcats) ? $sidebar_subcats : null;
if ($__subs === null) { $__subs = [1=>[],5=>[]]; foreach ($db->select("SELECT id, category_id, title, icon_class FROM agency_sub_categories WHERE category_id IN (1,5) AND status = 1 ORDER BY category_id, id") as $__r) { $__subs[$__r['category_id']][] = $__r; } }
$__menu = theme_user_menu($__subs, $__cats);
theme_open([
    'panel'  => 'user',
    'base'   => '',
    'title'  => 'My Wallet',
    'active' => 'wallet',
    'user'   => isset($user) ? $user : ['name' => 'User', 'mobile' => ''],
    'wallet' => isset($wallet_balance) ? $wallet_balance : 0,
    'notifs' => isset($unread_notifs) ? $unread_notifs : [],
    'logo'   => isset($company_logo) ? $company_logo : 'assets/images/logo.png',
    'brand'  => isset($company_name) ? $company_name : 'WBMCZ',
    'menu'   => $__menu,
    'state'  => 'currentTab: (window.location.hash ? window.location.hash.substring(1) : \'add_money\')',
]);
?>

            <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-5xl mx-auto pb-20">

                    <!-- ===== DUAL WALLET SUMMARY (always visible) ===== -->
                    <div class="grid sm:grid-cols-3 gap-3 mb-6">
                        <div class="rounded-2xl p-4 text-white shadow-lg relative overflow-hidden" style="background:linear-gradient(135deg,#312e81,#6d28d9);">
                            <div class="absolute -right-8 -bottom-8 w-32 h-32 bg-white/10 rounded-full blur-2xl"></div>
                            <p class="text-[10px] font-extrabold uppercase tracking-widest text-white/60 mb-1"><i class="fas fa-wallet mr-1"></i>Main Wallet</p>
                            <p class="text-2xl font-black">₹<?php echo number_format($wal['main'], 2); ?></p>
                            <p class="text-[10px] text-white/50 mt-1">Deposits &amp; income · withdrawable</p>
                        </div>
                        <div class="rounded-2xl p-4 text-white shadow-lg relative overflow-hidden" style="background:linear-gradient(135deg,#b45309,#f59e0b);">
                            <div class="absolute -right-8 -bottom-8 w-32 h-32 bg-white/10 rounded-full blur-2xl"></div>
                            <p class="text-[10px] font-extrabold uppercase tracking-widest text-white/70 mb-1"><i class="fas fa-gift mr-1"></i>Virtual Wallet</p>
                            <p class="text-2xl font-black">₹<?php echo number_format($wal['virtual'], 2); ?></p>
                            <p class="text-[10px] text-white/70 mt-1">Referral earnings · spend only</p>
                        </div>
                        <div class="rounded-2xl p-4 bg-white border-2 border-emerald-200 shadow-sm">
                            <p class="text-[10px] font-extrabold uppercase tracking-widest text-emerald-500 mb-1"><i class="fas fa-coins mr-1"></i>Total Spendable</p>
                            <p class="text-2xl font-black text-emerald-600">₹<?php echo number_format($wal['total'], 2); ?></p>
                            <p class="text-[10px] text-slate-400 mt-1">Virtual is used first at checkout</p>
                        </div>
                    </div>

                    <!-- ===== VIRTUAL WALLET TAB ===== -->
                    <div x-show="currentTab === 'virtual'" style="display:none;" x-transition.opacity>
                        <div class="mb-5">
                            <h2 class="text-2xl font-bold text-gray-800"><i class="fas fa-gift text-amber-500 mr-2"></i> Virtual Wallet</h2>
                            <p class="text-gray-500 text-sm">Money you earned from referrals. It cannot be withdrawn, but you can spend it on subscriptions and any product or service.</p>
                        </div>

                        <div class="bg-amber-50 border border-amber-200 rounded-2xl p-4 mb-5 flex items-start gap-3">
                            <i class="fas fa-circle-info text-amber-500 text-lg mt-0.5"></i>
                            <div class="text-xs text-amber-800 leading-relaxed">
                                <p class="font-bold mb-1">How the virtual wallet works</p>
                                <ul class="list-disc pl-4 space-y-0.5">
                                    <li>Every referral commission you earn is credited here automatically.</li>
                                    <li>At checkout, this balance is used <b>first</b> — anything left over comes out of your main wallet.</li>
                                    <li>It <b>cannot</b> be withdrawn or moved to your bank.</li>
                                </ul>
                            </div>
                        </div>

                        <div class="grid sm:grid-cols-3 gap-3 mb-5">
                            <div class="bg-white rounded-2xl border border-gray-200 p-4">
                                <p class="text-[10px] font-extrabold uppercase tracking-wider text-slate-400 mb-1">Current Balance</p>
                                <p class="text-xl font-black text-amber-600">₹<?php echo number_format($wal['virtual'], 2); ?></p>
                            </div>
                            <div class="bg-white rounded-2xl border border-gray-200 p-4">
                                <p class="text-[10px] font-extrabold uppercase tracking-wider text-slate-400 mb-1">Total Earned</p>
                                <p class="text-xl font-black text-emerald-600">+₹<?php echo number_format($wal_sum['virtual_in'] ?? 0, 2); ?></p>
                            </div>
                            <div class="bg-white rounded-2xl border border-gray-200 p-4">
                                <p class="text-[10px] font-extrabold uppercase tracking-wider text-slate-400 mb-1">Total Spent</p>
                                <p class="text-xl font-black text-rose-500">−₹<?php echo number_format($wal_sum['virtual_out'] ?? 0, 2); ?></p>
                            </div>
                        </div>

                        <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="px-5 py-3 border-b border-gray-100 bg-amber-50/50 flex items-center justify-between">
                                <p class="text-sm font-bold text-slate-700"><i class="fas fa-clock-rotate-left mr-2 text-amber-500"></i>Virtual wallet history</p>
                                <a href="earning_report.php" class="text-[11px] font-bold text-indigo-600 hover:underline">Full earning report <i class="fas fa-arrow-right ml-0.5"></i></a>
                            </div>
                            <div class="overflow-x-auto">
                                <table class="w-full text-left text-xs">
                                    <thead>
                                        <tr class="bg-slate-50 text-[10px] uppercase text-slate-500 tracking-wider">
                                            <th class="p-3 pl-5 font-semibold">Date</th>
                                            <th class="p-3 font-semibold">Details</th>
                                            <th class="p-3 font-semibold text-right">Amount</th>
                                            <th class="p-3 pr-5 font-semibold text-right">Balance</th>
                                        </tr>
                                    </thead>
                                    <tbody class="divide-y divide-gray-100">
                                    <?php if(!empty($virt_rows)): foreach($virt_rows as $v): $cr = ($v['direction']==='credit'); ?>
                                        <tr class="hover:bg-slate-50/60">
                                            <td class="p-3 pl-5 whitespace-nowrap">
                                                <p class="font-bold text-slate-700"><?php echo date('d M Y', strtotime($v['created_at'])); ?></p>
                                                <p class="text-[10px] text-slate-400"><?php echo date('h:i A', strtotime($v['created_at'])); ?></p>
                                            </td>
                                            <td class="p-3 text-slate-600">
                                                <p class="break-words"><?php echo htmlspecialchars($v['description'] ?: '—'); ?></p>
                                                <span class="inline-block mt-1 px-2 py-0.5 rounded text-[9px] font-bold uppercase bg-slate-100 text-slate-500"><?php echo wallet_cat_label($v['category']); ?></span>
                                            </td>
                                            <td class="p-3 text-right whitespace-nowrap">
                                                <span class="font-black text-sm <?php echo $cr ? 'text-emerald-600' : 'text-rose-600'; ?>"><?php echo $cr ? '+' : '−'; ?>₹<?php echo number_format((float)$v['amount'], 2); ?></span>
                                            </td>
                                            <td class="p-3 pr-5 text-right whitespace-nowrap font-bold text-slate-500">₹<?php echo number_format((float)$v['balance_after'], 2); ?></td>
                                        </tr>
                                    <?php endforeach; else: ?>
                                        <tr><td colspan="4" class="p-14 text-center text-slate-400">
                                            <i class="fas fa-gift text-3xl mb-3 block text-slate-300"></i>
                                            <p class="text-sm font-semibold text-slate-500 mb-1">Virtual wallet is empty</p>
                                            <p class="text-xs">Refer a friend and your commission will show up here.</p>
                                            <a href="refer.php" class="inline-block mt-4 px-5 py-2.5 rounded-xl bg-amber-500 hover:bg-amber-600 text-white text-xs font-bold">Refer &amp; Earn</a>
                                        </td></tr>
                                    <?php 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-gray-800"><i class="fas fa-plus-circle text-indigo-600 mr-2"></i> Add Money to 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-indigo-600 to-purple-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-indigo-200 font-bold uppercase tracking-widest text-xs mb-2">Available Balance</p>
                                        <h3 class="text-4xl font-extrabold mb-6">₹<?php echo number_format($wallet_balance, 2); ?></h3>
                                        <div class="bg-black/20 backdrop-blur-md rounded-xl p-3 border border-white/10 text-xs">
                                            Use your wallet balance to instantly purchase digital services, tools, and courses without external payment gateways.
                                        </div>
                                    </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"><?php echo $lang->translate('enter_amount', '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-indigo-500 text-3xl font-extrabold text-gray-800 transition-all shadow-inner" placeholder="0.00">
                                        </div>
                                    </div>
                                    
                                    <div class="flex gap-3 mb-8">
                                        <button type="button" onclick="document.getElementById('amount_input').value = 100" class="flex-1 py-3 border border-gray-200 rounded-xl font-bold text-gray-600 hover:bg-indigo-50 hover:text-indigo-700 hover:border-indigo-200 transition-colors shadow-sm">+ ₹100</button>
                                        <button type="button" onclick="document.getElementById('amount_input').value = 500" class="flex-1 py-3 border border-gray-200 rounded-xl font-bold text-gray-600 hover:bg-indigo-50 hover:text-indigo-700 hover:border-indigo-200 transition-colors shadow-sm">+ ₹500</button>
                                        <button type="button" onclick="document.getElementById('amount_input').value = 1000" class="flex-1 py-3 border border-gray-200 rounded-xl font-bold text-gray-600 hover:bg-indigo-50 hover:text-indigo-700 hover:border-indigo-200 transition-colors shadow-sm">+ ₹1,000</button>
                                    </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> Pay Securely via Razorpay
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- ===== WALLET TO BANK ===== -->
                    <div x-show="currentTab === 'to_bank' || currentTab === 'move_bank'" style="display:none;" x-transition.opacity>
                        <?php echo bank_render_to_bank($bank_data, ['rel' => '', 'accent' => 'indigo']); ?>
                    </div>

                    <!-- ===== WALLET HISTORY (ledger) ===== -->
                    <div x-show="currentTab === 'wallet_history'" style="display:none;" x-transition.opacity>
                        <?php echo bank_render_history($db, $user_id, ['accent' => 'indigo', 'self' => 'wallet.php']); ?>
                    </div>

                    <div x-show="currentTab === 'history'" style="display:none;" x-transition.opacity>
                        
                        <div class="mb-6 flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                            <h2 class="text-2xl font-bold text-gray-800"><i class="fas fa-history text-indigo-600 mr-2"></i> Transaction History</h2>
                            
                            <div class="flex space-x-1 bg-gray-200/50 p-1 rounded-lg border border-gray-200">
                                <button @click="historyTab = 'credit'" :class="historyTab === 'credit' ? 'bg-white shadow-sm text-emerald-700 font-bold' : 'text-gray-600 hover:bg-gray-100'" class="px-4 py-2 rounded-md text-sm transition-all">
                                    <i class="fas fa-arrow-down mr-1"></i> Credit (Income)
                                </button>
                                <button @click="historyTab = 'debit'" :class="historyTab === 'debit' ? 'bg-white shadow-sm text-rose-700 font-bold' : 'text-gray-600 hover:bg-gray-100'" class="px-4 py-2 rounded-md text-sm transition-all">
                                    <i class="fas fa-arrow-up mr-1"></i> Debit (Expense)
                                </button>
                            </div>
                        </div>

                        <div x-show="historyTab === 'credit'" style="display:none;">
                            <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-emerald-50/50 text-xs text-gray-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">Amount Received</th>
                                            </tr>
                                        </thead>
                                        <tbody class="divide-y divide-gray-50">
                                            <?php if(!empty($credits)): foreach($credits as $c): ?>
                                            <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($c['created_at'])); ?></span>
                                                    <span><?php echo date('h:i A', strtotime($c['created_at'])); ?></span>
                                                </td>
                                                <td class="p-4">
                                                    <p class="font-medium text-gray-800 text-sm"><?php echo htmlspecialchars($c['description']); ?></p>
                                                    <span class="inline-block mt-1 px-2 py-0.5 bg-emerald-100 text-emerald-700 text-[10px] font-bold uppercase rounded"><i class="fas fa-check mr-1"></i> Success</span>
                                                </td>
                                                <td class="p-4 text-right">
                                                    <span class="font-extrabold text-emerald-600">+₹<?php echo number_format($c['amount'], 2); ?></span>
                                                </td>
                                            </tr>
                                            <?php endforeach; else: ?>
                                                <tr>
                                                    <td colspan="3" class="p-16 text-center text-gray-500">
                                                        <div class="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4 text-gray-300 text-2xl border border-gray-100">
                                                            <i class="fas fa-wallet"></i>
                                                        </div>
                                                        <p class="text-lg font-medium">No credit transactions yet.</p>
                                                    </td>
                                                </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <div x-show="historyTab === 'debit'" style="display:none;">
                            
                            <div class="bg-rose-50 border border-rose-100 p-4 rounded-xl mb-6 flex flex-col sm:flex-row justify-between items-center gap-4">
                                <div>
                                    <h3 class="font-bold text-rose-900"><i class="fas fa-chart-pie mr-2"></i> Expense Categorization</h3>
                                    <p class="text-xs text-rose-700 mt-1">See exactly where your wallet balance was spent.</p>
                                </div>
                                <div class="flex items-center space-x-2">
                                    <label class="text-sm font-bold text-gray-700">Sort By:</label>
                                    <select x-model="expenseFilter" class="px-3 py-2 bg-white border border-gray-200 rounded-lg text-sm font-semibold focus:outline-none focus:ring-2 focus:ring-rose-500">
                                        <option value="high_to_low">Highest Expense First</option>
                                        <option value="low_to_high">Lowest Expense First</option>
                                        <option value="a_z">Alphabetical (A-Z)</option>
                                    </select>
                                </div>
                            </div>

                            <template x-if="sortedExpenses.length > 0">
                                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
                                    <template x-for="cat in sortedExpenses" :key="cat.category">
                                        <div class="bg-white rounded-xl border border-gray-200 shadow-sm p-5 hover:shadow-md transition-shadow">
                                            <div class="flex justify-between items-start mb-4">
                                                <div class="w-10 h-10 bg-rose-50 text-rose-600 rounded-lg flex items-center justify-center font-bold text-xl border border-rose-100">
                                                    <i class="fas fa-shopping-bag"></i>
                                                </div>
                                                <span class="bg-gray-100 text-gray-600 text-[10px] font-bold px-2 py-1 rounded-full border border-gray-200" x-text="cat.count + ' Orders'"></span>
                                            </div>
                                            <h4 class="font-bold text-gray-800 text-sm mb-1 line-clamp-2 h-10" x-text="cat.category"></h4>
                                            <p class="text-xs text-gray-500 uppercase tracking-widest font-bold mb-1">Total Spent</p>
                                            <p class="text-2xl font-extrabold text-rose-600">-₹<span x-text="cat.total.toFixed(2)"></span></p>
                                        </div>
                                    </template>
                                </div>
                            </template>
                            
                            <template x-if="sortedExpenses.length === 0">
                                <div class="p-16 bg-white rounded-2xl border border-gray-200 text-center text-gray-500 shadow-sm mb-8">
                                    <div class="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4 text-gray-300 text-2xl border border-gray-100">
                                        <i class="fas fa-receipt"></i>
                                    </div>
                                    <p class="text-lg font-medium">No expenses yet.</p>
                                </div>
                            </template>

                            <h3 class="text-lg font-bold text-gray-800 mb-4">All Debit Transactions</h3>
                            <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-gray-50 text-xs text-gray-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">Amount Deducted</th>
                                            </tr>
                                        </thead>
                                        <tbody class="divide-y divide-gray-50">
                                            <?php if(!empty($debits)): foreach($debits as $d): ?>
                                            <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($d['created_at'])); ?></span>
                                                    <span><?php echo date('h:i A', strtotime($d['created_at'])); ?></span>
                                                </td>
                                                <td class="p-4">
                                                    <p class="font-medium text-gray-800 text-sm"><?php echo htmlspecialchars($d['description']); ?></p>
                                                    <?php if($d['status'] === 'Pending'): ?>
                                                        <span class="inline-block mt-1 px-2 py-0.5 bg-yellow-100 text-yellow-700 text-[10px] font-bold uppercase rounded"><i class="fas fa-clock mr-1"></i> Pending Approval</span>
                                                    <?php else: ?>
                                                        <span class="inline-block mt-1 px-2 py-0.5 bg-emerald-100 text-emerald-700 text-[10px] font-bold uppercase rounded"><i class="fas fa-check mr-1"></i> Success</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="p-4 text-right">
                                                    <span class="font-extrabold text-rose-600">-₹<?php echo number_format($d['amount'], 2); ?></span>
                                                </td>
                                            </tr>
                                            <?php endforeach; else: ?>
                                                <tr><td colspan="3" class="p-8 text-center text-gray-400 italic">List is empty.</td></tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                    </div>

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

    <script>
        // Razorpay Logic
        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": "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": "#4f46e5" // Tailwind indigo-600 to match user panel theme
                }
            };
            var rzp1 = new Razorpay(options);
            rzp1.open();
        }
    </script>
</body>
</html>