<?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_users')) { die("Access Denied: You do not have permission to manage customers."); }

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

if (isset($_POST['toggle_status'])) {
    $target_user_id = sanitize($_POST['target_user_id']);
    $current_status = sanitize($_POST['current_status']);
    $new_status = ($current_status == 1) ? 0 : 1;
    
    $db->insert("UPDATE users SET status = ? WHERE id = ?", [$new_status, $target_user_id]);
    $_SESSION['flash_success'] = $lang->translate('status_updated', 'Status updated successfully!');
    redirect('users.php');
}

if (isset($_POST['delete_user'])) {
    $target_user_id = sanitize($_POST['target_user_id']);
    
    $target_data = $db->select("SELECT profile_pic FROM users WHERE id = ?", [$target_user_id]);
    if (!empty($target_data[0]['profile_pic'])) {
        $pic_path = '../uploads/profiles/' . $target_data[0]['profile_pic'];
        if (file_exists($pic_path)) {
            @unlink($pic_path);
        }
    }
    
    $db->insert("DELETE FROM users WHERE id = ?", [$target_user_id]);
    $_SESSION['flash_success'] = $lang->translate('user_deleted', 'User deleted successfully!');
    redirect('users.php');
}

if (isset($_POST['change_role'])) {
    $target_user_id = sanitize($_POST['target_user_id']);
    $new_role = sanitize($_POST['new_role']); // 'seller' or 'staff'
    
    if (in_array($new_role, ['seller', 'staff'])) {
        $db->insert("UPDATE users SET user_type = ? WHERE id = ?", [$new_role, $target_user_id]);
        
        if ($new_role == 'seller') {
            $check = $db->select("SELECT id FROM sellers WHERE user_id = ?", [$target_user_id]);
            if (empty($check)) {
                $u = $db->select("SELECT * FROM users WHERE id = ?", [$target_user_id])[0];
                $db->insert("INSERT INTO sellers (user_id, name, phone, email, business_name, status) VALUES (?, ?, ?, ?, ?, 1)",
                    [$target_user_id, $u['name'], $u['mobile'], $u['email'], $u['name'] . ' Business']);
            } else {
                $db->insert("UPDATE sellers SET status = 1 WHERE user_id = ?", [$target_user_id]);
            }
        }
        
        $_SESSION['flash_success'] = "User role updated to " . ucfirst($new_role) . " successfully!";
        redirect('users.php');
    }
}

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

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

$search_query = isset($_GET['search']) ? sanitize($_GET['search']) : '';
$where_clause = "user_type = 'customer'";
$params = [];

if (!empty($search_query)) {
    $where_clause .= " AND (id = ? OR name LIKE ? OR mobile LIKE ? OR email LIKE ?)";
    $like_term = "%$search_query%";
    $params = [intval(str_replace('#', '', $search_query)), $like_term, $like_term, $like_term];
}

$customers = $db->select("SELECT * FROM users WHERE $where_clause ORDER BY id DESC", $params);

$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('manage_users', 'Manage Users'); ?> - <?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('manage_users', 'Manage Users'); ?></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="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('user_list', 'User List'); ?></h2>
                        <p class="text-gray-500 text-sm">Manage all registered customers on your platform.</p>
                    </div>
                    
                    <form method="GET" class="relative group">
                        <div class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none">
                            <i class="fas fa-search text-slate-400 group-focus-within:text-indigo-500 transition-colors"></i>
                        </div>
                        <input type="text" name="search" value="<?php echo isset($_GET['search']) ? htmlspecialchars($_GET['search']) : ''; ?>" placeholder="Search ID, Name, Phone..." class="w-full md:w-72 pl-10 pr-10 py-2.5 bg-white border border-slate-200 rounded-xl text-sm text-slate-800 placeholder-slate-400 focus:outline-none focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500 transition-all shadow-sm hover:shadow-md">
                        <?php if(isset($_GET['search']) && !empty($_GET['search'])): ?>
                            <a href="users.php" class="absolute inset-y-0 right-0 pr-3.5 flex items-center text-slate-400 hover:text-rose-500 transition-colors">
                                <i class="fas fa-times-circle text-lg"></i>
                            </a>
                        <?php endif; ?>
                    </form>
                </div>

                <?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="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">User Details</th>
                                    <th class="p-4 font-semibold border-b border-gray-200"><?php echo $lang->translate('contact_info', 'Contact Info'); ?></th>
                                    <th class="p-4 font-semibold border-b border-gray-200"><?php echo $lang->translate('wallet_balance', 'Wallet Balance'); ?></th>
                                    <th class="p-4 font-semibold border-b border-gray-200"><?php echo $lang->translate('join_date', 'Join Date'); ?></th>
                                    <th class="p-4 font-semibold border-b border-gray-200"><?php echo $lang->translate('status', 'Status'); ?></th>
                                    <th class="p-4 pr-6 font-semibold border-b border-gray-200 text-right"><?php echo $lang->translate('action', 'Action'); ?></th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100">
                                <?php if(!empty($customers)): ?>
                                    <?php foreach($customers as $customer): ?>
                                    <tr class="hover:bg-slate-50/50 transition group">
                                        <td class="p-4 pl-6">
                                            <div class="flex items-center">
                                                <?php if(!empty($customer['profile_pic']) && file_exists('../uploads/profiles/'.$customer['profile_pic'])): ?>
                                                    <img src="../uploads/profiles/<?php echo $customer['profile_pic']; ?>" class="w-10 h-10 rounded-full object-cover border border-gray-200 mr-3">
                                                <?php else: ?>
                                                    <div class="w-10 h-10 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center font-bold text-sm mr-3">
                                                        <?php echo strtoupper(substr($customer['name'], 0, 1)); ?>
                                                    </div>
                                                <?php endif; ?>
                                                <div>
                                                    <p class="font-bold text-slate-800 text-sm"><?php echo htmlspecialchars($customer['name']); ?></p>
                                                    <p class="text-xs text-gray-500">ID: #<?php echo str_pad($customer['id'], 5, '0', STR_PAD_LEFT); ?> &bull; <?php echo ucfirst($customer['gender']); ?></p>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="p-4">
                                            <p class="text-sm text-slate-700 font-medium"><i class="fas fa-phone-alt text-gray-400 w-4 text-center mr-1"></i> <?php echo htmlspecialchars($customer['mobile']); ?></p>
                                            <p class="text-xs text-gray-500 mt-1"><i class="fas fa-envelope text-gray-400 w-4 text-center mr-1"></i> <?php echo htmlspecialchars($customer['email']); ?></p>
                                        </td>
                                        <td class="p-4">
                                            <span class="font-bold text-emerald-600">₹<?php echo number_format($customer['wallet_balance'], 2); ?></span>
                                        </td>
                                        <td class="p-4">
                                            <p class="text-sm text-slate-700 font-medium whitespace-nowrap"><i class="far fa-calendar-alt text-gray-400 mr-1"></i> <?php echo date('d M, Y', strtotime($customer['created_at'])); ?></p>
                                        </td>
                                        <td class="p-4">
                                            <?php if($customer['status'] == 1): ?>
                                                <span class="bg-emerald-100 text-emerald-700 text-[10px] font-bold px-2.5 py-1 rounded-full uppercase tracking-wider border border-emerald-200 whitespace-nowrap">
                                                    <i class="fas fa-check-circle mr-1"></i> <?php echo $lang->translate('active', 'Active'); ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="bg-rose-100 text-rose-700 text-[10px] font-bold px-2.5 py-1 rounded-full uppercase tracking-wider border border-rose-200 whitespace-nowrap">
                                                    <i class="fas fa-ban mr-1"></i> <?php echo $lang->translate('inactive', 'Inactive'); ?>
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="p-4 pr-6 text-right space-x-2 whitespace-nowrap">
                                            
                                            <form method="POST" class="inline-block">
                                                <input type="hidden" name="target_user_id" value="<?php echo $customer['id']; ?>">
                                                <input type="hidden" name="current_status" value="<?php echo $customer['status']; ?>">
                                                <button type="submit" name="toggle_status" class="w-8 h-8 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-600 transition-colors tooltip flex items-center justify-center" title="<?php echo $customer['status'] == 1 ? 'Suspend User' : 'Activate User'; ?>">
                                                    <i class="fas <?php echo $customer['status'] == 1 ? 'fa-user-lock' : 'fa-user-check'; ?>"></i>
                                                </button>
                                            </form>

                                            <form method="POST" class="inline-block" onsubmit="return confirm('<?php echo $lang->translate('confirm_delete_user', 'Are you sure you want to delete this user? This action cannot be undone!'); ?>');">
                                                <input type="hidden" name="target_user_id" value="<?php echo $customer['id']; ?>">
                                                <button type="submit" name="delete_user" class="w-8 h-8 rounded-lg bg-rose-50 hover:bg-rose-100 text-rose-600 transition-colors tooltip flex items-center justify-center" title="Delete User">
                                                    <i class="fas fa-trash-alt"></i>
                                                </button>
                                            </form>
                                            
                                            <form method="POST" class="inline-block ml-2" onsubmit="return confirm('Are you sure you want to upgrade this user role?');">
                                                <input type="hidden" name="target_user_id" value="<?php echo $customer['id']; ?>">
                                                <div class="flex items-center space-x-1">
                                                    <select name="new_role" class="text-xs border border-gray-200 rounded px-2 py-1 outline-none cursor-pointer text-gray-600">
                                                        <option value="seller">Upgrade to Seller</option>
                                                        <option value="staff">Upgrade to Staff</option>
                                                    </select>
                                                    <button type="submit" name="change_role" class="w-8 h-8 rounded-lg bg-indigo-50 hover:bg-indigo-100 text-indigo-600 transition-colors tooltip flex items-center justify-center" title="Change Role">
                                                        <i class="fas fa-arrow-up"></i>
                                                    </button>
                                                </div>
                                            </form>
                                        </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-users-slash"></i>
                                            </div>
                                            <p class="text-lg font-medium"><?php echo $lang->translate('no_users_found', 'No users found.'); ?></p>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

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