<?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'); }

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

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

if (!$user) {
    session_destroy();
    redirect('../login.php');
}

// UI Permissions Check
$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');

// Statistics fetching (only if they have permission to see them, otherwise 0)
/* Soft-deleted accounts are left out of the totals. The fallback keeps the
   dashboard working on a database where neosspmigration.php has not run yet. */
$__has_soft_delete = false;
try {
    $__r = $db->getConnection()->query("SHOW COLUMNS FROM users LIKE 'deleted_at'");
    $__has_soft_delete = ($__r && $__r->num_rows > 0);
} catch (\Throwable $e) { $__has_soft_delete = false; }

$__count_users = function ($type) use ($db, $__has_soft_delete) {
    $sql = "SELECT id FROM users WHERE user_type = ?" . ($__has_soft_delete ? " AND deleted_at IS NULL" : "");
    return count($db->select($sql, [$type]));
};
$total_users   = $can_users   ? $__count_users('customer') : 0;
$total_sellers = $can_sellers ? $__count_users('seller')   : 0;
$total_tickets = $can_tickets ? count($db->select("SELECT id FROM support_tickets WHERE status = 'Open'")) : 0;

$total_revenue = 0.00;
if ($can_transactions || $can_orders) {
    // Platform revenue = value of completed orders (matches admin/reports.php).
    // NOTE: wallet recharges & admin wallet transfers are user deposits, NOT income,
    // so they must be excluded — that was the previous bug.
    $revenue_data = $db->select("SELECT SUM(amount) as total FROM orders WHERE status = 'Completed'");
    $total_revenue = !empty($revenue_data[0]['total']) ? $revenue_data[0]['total'] : 0.00;
}

// Income breakdown (where the revenue comes from) for the click popup
$income_breakdown = [];
$income_this_month = 0.00;
$income_orders_count = 0;
if ($can_transactions || $can_orders) {
    $income_breakdown = $db->select("SELECT service_name, COUNT(*) as cnt, SUM(amount) as total FROM orders WHERE status = 'Completed' GROUP BY service_name ORDER BY total DESC");
    $tm = $db->select("SELECT SUM(amount) as total FROM orders WHERE status='Completed' AND MONTH(created_at)=MONTH(CURRENT_DATE()) AND YEAR(created_at)=YEAR(CURRENT_DATE())");
    $income_this_month = !empty($tm[0]['total']) ? $tm[0]['total'] : 0.00;
    $cc = $db->select("SELECT COUNT(*) as c FROM orders WHERE status='Completed'");
    $income_orders_count = !empty($cc[0]['c']) ? intval($cc[0]['c']) : 0;
}

$recent_orders = $can_orders ? $db->select("SELECT o.*, u.name, u.profile_pic FROM orders o JOIN users u ON o.user_id = u.id ORDER BY o.created_at DESC LIMIT 5") : [];

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

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

// Build dynamic modules array based on permissions
$admin_modules = [];
if($can_users) $admin_modules[] = ['title' => 'Users', 'key' => 'manage_users', 'icon' => 'fa-users', 'gradient' => 'from-blue-500 to-cyan-400', 'link' => 'users.php'];
if($can_sellers) $admin_modules[] = ['title' => 'Sellers', 'key' => 'manage_sellers', 'icon' => 'fa-store', 'gradient' => 'from-purple-500 to-pink-500', 'link' => 'sellers.php'];
if($can_staff) {
    $admin_modules[] = ['title' => 'Staff List', 'key' => 'manage_staff', 'icon' => 'fa-user-shield', 'gradient' => 'from-emerald-500 to-teal-500', 'link' => 'staff.php'];
    $admin_modules[] = ['title' => 'Roles', 'key' => 'manage_roles', 'icon' => 'fa-key', 'gradient' => 'from-indigo-500 to-purple-500', 'link' => 'roles.php'];
}
if($can_services) $admin_modules[] = ['title' => 'Services', 'key' => 'manage_services', 'icon' => 'fa-layer-group', 'gradient' => 'from-orange-400 to-red-500', 'link' => 'services.php'];
if($can_orders) $admin_modules[] = ['title' => 'Orders', 'key' => 'manage_orders', 'icon' => 'fa-shopping-cart', 'gradient' => 'from-emerald-400 to-teal-500', 'link' => 'orders.php'];
if($can_transactions) $admin_modules[] = ['title' => 'Transactions', 'key' => 'all_transactions', 'icon' => 'fa-exchange-alt', 'gradient' => 'from-indigo-500 to-blue-600', 'link' => 'transactions.php'];
if($can_tickets) $admin_modules[] = ['title' => 'Tickets', 'key' => 'support_tickets', 'icon' => 'fa-ticket-alt', 'gradient' => 'from-rose-400 to-red-500', 'link' => 'tickets.php'];
if($can_settings) $admin_modules[] = ['title' => 'Settings', 'key' => 'site_settings', 'icon' => 'fa-cogs', 'gradient' => 'from-slate-600 to-slate-800', 'link' => 'settings.php'];

?>
<!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('admin_dashboard', 'Admin Dashboard'); ?> - <?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>
    <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; } .hide-scrollbar { -ms-overflow-style: none; scrollbar-width: none; } </style>
</head>
<body class="bg-gray-50" x-data="{ sidebarOpen: window.innerWidth >= 768, profileOpen: false, notifOpen: false, incomeModal: 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('admin_dashboard', 'Admin Dashboard'); ?></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 htmlspecialchars($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="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6 mb-8">
                    <?php if($can_transactions): ?>
                    <button type="button" @click="incomeModal = true" class="text-left w-full bg-gradient-to-br from-emerald-500 to-teal-600 rounded-2xl p-6 text-white shadow-lg relative overflow-hidden hover:shadow-2xl hover:-translate-y-0.5 transition-all cursor-pointer group">
                        <div class="absolute -right-6 -top-6 w-24 h-24 bg-white/20 rounded-full blur-xl"></div>
                        <div class="relative z-10 flex items-center">
                            <div class="w-12 h-12 rounded-full bg-white/20 flex items-center justify-center text-xl mr-4 border border-white/30 shadow-inner"><i class="fas fa-wallet"></i></div>
                            <div>
                                <p class="text-xs text-emerald-100 font-bold uppercase tracking-wider mb-1"><?php echo $lang->translate('total_revenue', 'Total Revenue'); ?></p>
                                <h3 class="text-2xl font-extrabold">₹<?php echo number_format($total_revenue, 2); ?></h3>
                            </div>
                        </div>
                        <span class="absolute right-4 bottom-3 text-[10px] font-bold text-white/80 flex items-center gap-1 group-hover:text-white"><i class="fas fa-circle-info"></i> View breakdown</span>
                    </button>
                    <?php endif; ?>

                    <?php if($can_users): ?>
                    <div class="bg-white rounded-2xl p-6 shadow-sm border border-gray-200 flex items-center">
                        <div class="w-12 h-12 rounded-full bg-blue-50 text-blue-600 flex items-center justify-center text-xl mr-4 border border-blue-100"><i class="fas fa-users"></i></div>
                        <div>
                            <p class="text-xs text-gray-500 font-bold uppercase tracking-wider mb-1"><?php echo $lang->translate('total_users', 'Total Users'); ?></p>
                            <h3 class="text-2xl font-bold text-gray-900"><?php echo $total_users; ?></h3>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if($can_sellers): ?>
                    <div class="bg-white rounded-2xl p-6 shadow-sm border border-gray-200 flex items-center">
                        <div class="w-12 h-12 rounded-full bg-purple-50 text-purple-600 flex items-center justify-center text-xl mr-4 border border-purple-100"><i class="fas fa-store"></i></div>
                        <div>
                            <p class="text-xs text-gray-500 font-bold uppercase tracking-wider mb-1"><?php echo $lang->translate('total_sellers', 'Total Sellers'); ?></p>
                            <h3 class="text-2xl font-bold text-gray-900"><?php echo $total_sellers; ?></h3>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php if($can_tickets): ?>
                    <div class="bg-white rounded-2xl p-6 shadow-sm border border-gray-200 flex items-center">
                        <div class="w-12 h-12 rounded-full bg-rose-50 text-rose-600 flex items-center justify-center text-xl mr-4 border border-rose-100"><i class="fas fa-ticket-alt"></i></div>
                        <div>
                            <p class="text-xs text-gray-500 font-bold uppercase tracking-wider mb-1">Open Tickets</p>
                            <h3 class="text-2xl font-bold text-gray-900"><?php echo $total_tickets; ?></h3>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>

                <div class="mb-6"><h2 class="text-xl font-bold text-gray-800 mb-2">Platform Modules</h2></div>

                <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4 mb-10">
                    <?php foreach ($admin_modules as $mod): ?>
                    <a href="<?php echo $mod['link']; ?>" class="block group">
                        <div class="bg-white rounded-xl p-4 text-center shadow-sm hover:shadow-lg transition-all duration-300 border border-gray-100 flex flex-col items-center justify-center group-hover:border-emerald-200 h-full">
                            <div class="w-12 h-12 rounded-lg bg-gradient-to-br <?php echo $mod['gradient']; ?> text-white flex items-center justify-center mb-3 shadow-md group-hover:scale-110 transition-transform duration-300">
                                <i class="fas <?php echo $mod['icon']; ?> text-xl"></i>
                            </div>
                            <h3 class="font-bold text-xs text-slate-700"><?php echo $lang->translate($mod['key'], $mod['title']); ?></h3>
                        </div>
                    </a>
                    <?php endforeach; ?>
                </div>

                <?php if($can_orders): ?>
                <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden mb-10">
                    <div class="px-6 py-5 border-b border-gray-100 bg-gray-50 flex justify-between items-center">
                        <h3 class="text-lg font-bold text-gray-800"><i class="fas fa-shopping-bag text-emerald-600 mr-2"></i> Recent Orders</h3>
                        <a href="orders.php" class="text-sm text-emerald-600 font-bold hover:text-emerald-800">View All</a>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="bg-white text-[10px] uppercase text-gray-400 tracking-wider border-b border-gray-100">
                                    <th class="p-4 pl-6 font-semibold">Order ID</th>
                                    <th class="p-4 font-semibold">User</th>
                                    <th class="p-4 font-semibold">Service</th>
                                    <th class="p-4 font-semibold">Status</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-50">
                                <?php if(!empty($recent_orders)): ?>
                                    <?php foreach($recent_orders as $order): ?>
                                    <tr class="hover:bg-slate-50 transition">
                                        <td class="p-4 pl-6 font-mono text-xs text-gray-500">#ORD<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?></td>
                                        <td class="p-4">
                                            <div class="flex items-center">
                                                <?php if(!empty($order['profile_pic']) && file_exists('../uploads/profiles/'.$order['profile_pic'])): ?>
                                                    <img src="../uploads/profiles/<?php echo $order['profile_pic']; ?>" class="w-6 h-6 rounded-full object-cover border border-gray-200 mr-2">
                                                <?php else: ?>
                                                    <div class="w-6 h-6 rounded-full bg-slate-100 text-slate-600 flex items-center justify-center font-bold text-[10px] mr-2">
                                                        <?php echo strtoupper(substr($order['name'], 0, 1)); ?>
                                                    </div>
                                                <?php endif; ?>
                                                <span class="font-bold text-slate-800 text-xs"><?php echo htmlspecialchars($order['name']); ?></span>
                                            </div>
                                        </td>
                                        <td class="p-4 font-bold text-emerald-600 text-xs"><?php echo htmlspecialchars($order['service_name']); ?></td>
                                        <td class="p-4">
                                            <?php 
                                                $statusClass = 'bg-slate-100 text-slate-700';
                                                if(strtolower($order['status']) == 'completed' || strtolower($order['status']) == 'success') $statusClass = 'bg-emerald-100 text-emerald-700';
                                                elseif(strtolower($order['status']) == 'pending') $statusClass = 'bg-yellow-100 text-yellow-700';
                                                elseif(strtolower($order['status']) == 'failed' || strtolower($order['status']) == 'cancelled') $statusClass = 'bg-rose-100 text-rose-700';
                                            ?>
                                            <span class="px-2 py-1 text-[9px] font-bold uppercase tracking-wider rounded border border-white/50 <?php echo $statusClass; ?>">
                                                <?php echo htmlspecialchars($order['status']); ?>
                                            </span>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="4" class="p-8 text-center text-gray-500 text-sm">No recent orders found.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <?php endif; ?>

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

    <!-- ===== INCOME BREAKDOWN MODAL ===== -->
    <div x-show="incomeModal" x-transition.opacity style="display:none;" class="fixed inset-0 z-[100] flex items-center justify-center p-4">
        <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="incomeModal = false"></div>
        <div class="relative w-full max-w-2xl bg-white rounded-2xl shadow-2xl overflow-hidden max-h-[90vh] flex flex-col">
            <div class="bg-gradient-to-r from-emerald-500 to-teal-600 px-6 py-5 flex items-center justify-between flex-shrink-0">
                <div>
                    <h3 class="text-white font-bold text-lg"><i class="fas fa-wallet mr-2"></i>Income Breakdown</h3>
                    <p class="text-emerald-100 text-xs mt-0.5">Revenue from completed orders, by service</p>
                </div>
                <button @click="incomeModal = false" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
            </div>

            <!-- summary tiles -->
            <div class="grid grid-cols-3 gap-3 p-5 border-b border-slate-100 flex-shrink-0">
                <div class="bg-emerald-50 rounded-xl p-3 text-center">
                    <p class="text-[10px] font-bold text-emerald-600 uppercase">Total Income</p>
                    <p class="text-lg font-extrabold text-emerald-700">₹<?php echo number_format($total_revenue, 2); ?></p>
                </div>
                <div class="bg-blue-50 rounded-xl p-3 text-center">
                    <p class="text-[10px] font-bold text-blue-600 uppercase">This Month</p>
                    <p class="text-lg font-extrabold text-blue-700">₹<?php echo number_format($income_this_month, 2); ?></p>
                </div>
                <div class="bg-indigo-50 rounded-xl p-3 text-center">
                    <p class="text-[10px] font-bold text-indigo-600 uppercase">Completed Orders</p>
                    <p class="text-lg font-extrabold text-indigo-700"><?php echo number_format($income_orders_count); ?></p>
                </div>
            </div>

            <!-- breakdown list -->
            <div class="p-5 overflow-y-auto">
                <?php if(!empty($income_breakdown)): ?>
                <table class="w-full text-left text-sm">
                    <thead>
                        <tr class="text-slate-500 text-[10px] uppercase border-b">
                            <th class="py-2">Service</th>
                            <th class="py-2 text-center">Orders</th>
                            <th class="py-2 text-right">Income</th>
                            <th class="py-2 text-right pl-3">Share</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                        <?php foreach($income_breakdown as $ib):
                            $pct = ($total_revenue > 0) ? ($ib['total'] / $total_revenue) * 100 : 0;
                        ?>
                        <tr>
                            <td class="py-2.5 pr-2 font-semibold text-slate-700"><?php echo htmlspecialchars($ib['service_name'] ?: 'Unknown'); ?></td>
                            <td class="py-2.5 text-center text-slate-500"><?php echo $ib['cnt']; ?></td>
                            <td class="py-2.5 text-right font-bold text-emerald-600 whitespace-nowrap">₹<?php echo number_format($ib['total'], 2); ?></td>
                            <td class="py-2.5 pl-3 text-right w-28">
                                <div class="flex items-center justify-end gap-2">
                                    <div class="w-14 h-1.5 bg-slate-100 rounded-full overflow-hidden"><div class="h-full bg-emerald-500" style="width: <?php echo round($pct); ?>%"></div></div>
                                    <span class="text-[11px] font-bold text-slate-500 w-9"><?php echo round($pct); ?>%</span>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr class="border-t-2 border-slate-200 font-extrabold">
                            <td class="py-3">Total</td>
                            <td class="py-3 text-center"><?php echo number_format($income_orders_count); ?></td>
                            <td class="py-3 text-right text-emerald-700">₹<?php echo number_format($total_revenue, 2); ?></td>
                            <td class="py-3 text-right pr-1">100%</td>
                        </tr>
                    </tfoot>
                </table>
                <?php else: ?>
                <div class="text-center text-slate-400 py-10">
                    <i class="fas fa-chart-pie text-3xl mb-3"></i>
                    <p class="font-medium">No completed-order income yet.</p>
                </div>
                <?php endif; ?>
                <p class="text-[11px] text-slate-400 mt-4"><i class="fas fa-circle-info mr-1"></i> Income = value of <b>completed</b> orders only. Wallet recharges and admin transfers are user deposits, not income.</p>
            </div>
        </div>
    </div>
</body>
</html>
