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

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

if (!hasPermission('manage_transactions')) { die("Access Denied: You do not have permission to view transactions."); }

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

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

$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);
$total_tickets = count($db->select("SELECT id FROM support_tickets WHERE status = 'Open'"));

$query = "SELECT t.*, u.name, u.mobile, u.user_type, u.profile_pic 
          FROM transactions t 
          JOIN users u ON t.user_id = u.id 
          ORDER BY t.created_at DESC";
$transactions = $db->select($query);

$raw_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($raw_logo, 'http') === 0) ? $raw_logo : '../' . ltrim($raw_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><?php echo $lang->translate('all_transactions', 'Transactions'); ?> - <?php echo $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>
    <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; } .hide-scrollbar::-webkit-scrollbar { display: none; } </style>
</head>
<body class="bg-gray-50" x-data="{ sidebarOpen: window.innerWidth >= 768, profileOpen: false, notifOpen: false }">

    <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-100 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>
                    <a href="../index.php" class="md:hidden flex items-center" x-show="!sidebarOpen">
                        <img src="<?php echo $company_logo; ?>" alt="Logo" class="h-9 w-9 object-contain">
                    </a>
                    <h2 class="text-xl font-bold hidden md:block text-slate-800"><?php echo $lang->translate('all_transactions', 'Transactions'); ?></h2>
                </div>

                <div class="flex items-center space-x-3 sm:space-x-5 ml-auto">
                    <a href="../index.php" target="_blank" class="hidden sm:flex items-center text-sm font-semibold text-gray-500 hover:text-emerald-600 transition-colors">
                        <i class="fas fa-external-link-alt mr-2"></i> Visit Site
                    </a>

                    <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; ?>
                            <i class="fas fa-chevron-down text-xs ml-2 text-slate-400 hidden sm:block"></i>
                        </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" style="display: none;">
                            <div class="px-4 py-3 border-b border-gray-100">
                                <p class="text-sm text-gray-500">Signed in as Admin</p>
                                <p class="text-sm font-bold text-gray-900 truncate"><?php echo $user['name']; ?></p>
                            </div>
                            <a href="profile.php" class="block px-4 py-2 text-sm text-gray-700 hover:bg-emerald-50 hover:text-emerald-600 transition-colors"><i class="fas fa-user mr-2 w-4"></i> My Profile</a>
                            <div class="border-t border-gray-100 mt-2 pt-2">
                                <a href="../logout.php" onclick="return confirm('<?php echo $lang->translate('confirm_logout', 'Are you sure you want to logout?'); ?>');" 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-4"></i> Logout</a>
                            </div>
                        </div>
                    </div>
                </div>
            </header>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8 relative">
                
                <div class="mb-6 flex flex-col md:flex-row md:justify-between md:items-center gap-4">
                    <div>
                        <h2 class="text-2xl font-bold text-slate-800 mb-1"><?php echo $lang->translate('all_transactions', 'All Transactions'); ?></h2>
                        <p class="text-gray-500 text-sm"><?php echo $lang->translate('transactions_desc', 'View all financial activities across the platform.'); ?></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-left border-collapse">
                            <thead>
                                <tr class="bg-slate-50 text-xs uppercase text-slate-500 tracking-wider">
                                    <th class="p-4 pl-6 font-semibold border-b border-gray-200"><?php echo $lang->translate('trans_id', 'Txn ID'); ?></th>
                                    <th class="p-4 font-semibold border-b border-gray-200"><?php echo $lang->translate('user', 'User'); ?></th>
                                    <th class="p-4 font-semibold border-b border-gray-200"><?php echo $lang->translate('description', 'Description'); ?></th>
                                    <th class="p-4 font-semibold border-b border-gray-200 text-right"><?php echo $lang->translate('amount', 'Amount'); ?></th>
                                    <th class="p-4 pr-6 font-semibold border-b border-gray-200 text-right"><?php echo $lang->translate('date', 'Date'); ?></th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100">
                                <?php if(!empty($transactions)): ?>
                                    <?php foreach($transactions as $txn): ?>
                                    <tr class="hover:bg-slate-50/50 transition">
                                        <td class="p-4 pl-6 text-xs text-gray-500 font-mono">
                                            #TXN<?php echo str_pad($txn['id'], 6, '0', STR_PAD_LEFT); ?>
                                        </td>
                                        <td class="p-4">
                                            <div class="flex items-center">
                                                <?php if(!empty($txn['profile_pic']) && file_exists('../uploads/profiles/'.$txn['profile_pic'])): ?>
                                                    <img src="../uploads/profiles/<?php echo $txn['profile_pic']; ?>" class="w-8 h-8 rounded-full object-cover border border-gray-200 mr-3">
                                                <?php else: ?>
                                                    <div class="w-8 h-8 rounded-full bg-slate-100 text-slate-600 flex items-center justify-center font-bold text-xs mr-3">
                                                        <?php echo strtoupper(substr($txn['name'], 0, 1)); ?>
                                                    </div>
                                                <?php endif; ?>
                                                <div>
                                                    <p class="font-bold text-slate-800 text-sm"><?php echo htmlspecialchars($txn['name']); ?></p>
                                                    <p class="text-[10px] text-gray-500 mt-0.5">
                                                        <span class="uppercase tracking-wider font-semibold <?php echo $txn['user_type'] == 'seller' ? 'text-purple-600' : 'text-blue-600'; ?>"><?php echo htmlspecialchars($txn['user_type']); ?></span> &bull; <?php echo htmlspecialchars($txn['mobile']); ?>
                                                    </p>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="p-4">
                                            <div class="flex items-center">
                                                <?php if($txn['type'] == 'credit'): ?>
                                                    <i class="fas fa-arrow-down text-emerald-500 bg-emerald-100 p-1.5 rounded-full text-[10px] mr-2"></i>
                                                <?php else: ?>
                                                    <i class="fas fa-arrow-up text-rose-500 bg-rose-100 p-1.5 rounded-full text-[10px] mr-2"></i>
                                                <?php endif; ?>
                                                <div>
                                                    <p class="font-bold text-gray-800 text-sm"><?php echo htmlspecialchars($txn['description']); ?></p>
                                                    <p class="text-[10px] font-bold mt-0.5 <?php echo $txn['status'] == 'Success' ? 'text-emerald-600' : 'text-yellow-600'; ?>"><?php echo htmlspecialchars($txn['status']); ?></p>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="p-4 text-right font-bold text-sm <?php echo $txn['type'] == 'credit' ? 'text-emerald-600' : 'text-slate-800'; ?>">
                                            <?php echo $txn['type'] == 'credit' ? '+' : '-'; ?>₹<?php echo number_format($txn['amount'], 2); ?>
                                        </td>
                                        <td class="p-4 pr-6 text-right text-gray-500 text-xs whitespace-nowrap">
                                            <?php echo date('d M Y', strtotime($txn['created_at'])); ?><br>
                                            <span class="text-[10px]"><?php echo date('h:i A', strtotime($txn['created_at'])); ?></span>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="5" class="p-12 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-400 text-2xl border border-gray-100">
                                                <i class="fas fa-receipt"></i>
                                            </div>
                                            <p class="text-lg font-medium"><?php echo $lang->translate('no_transactions', 'No transactions found.'); ?></p>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

            </main>
        </div>
    </div>
</body>
</html>