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

/* Only a staff account that was given this module may open the page */
require_once __DIR__ . '/../includes/rbac.php';
rbac_guard('manage_users');

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

$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['approve_request'])) {
    $req_id = sanitize($_POST['request_id']);
    $req = $db->select("SELECT * FROM seller_upgrade_requests WHERE id = ?", [$req_id]);
    
    if (!empty($req)) {
        $req = $req[0];
        $uid = $req['user_id'];
        
        // Update request status
        $db->insert("UPDATE seller_upgrade_requests SET status = 'Approved' WHERE id = ?", [$req_id]);
        
        // Update user type
        $db->insert("UPDATE users SET user_type = 'seller' WHERE id = ?", [$uid]);
        
        // Check sellers table
        $check = $db->select("SELECT id FROM sellers WHERE user_id = ?", [$uid]);
        if (empty($check)) {
            $u = $db->select("SELECT * FROM users WHERE id = ?", [$uid])[0];
            $db->insert("INSERT INTO sellers (user_id, name, phone, email, business_name, status) VALUES (?, ?, ?, ?, ?, 1)",
                [$uid, $u['name'], $req['business_phone'], $u['email'], $req['business_name']]);
        } else {
            $db->insert("UPDATE sellers SET status = 1 WHERE user_id = ?", [$uid]);
        }
        
        $_SESSION['flash_success'] = "Request Approved! User is now a seller.";
        redirect('upgrade_requests.php');
    }
}

if (isset($_POST['reject_request'])) {
    $req_id = sanitize($_POST['request_id']);
    $db->insert("UPDATE seller_upgrade_requests SET status = 'Rejected' WHERE id = ?", [$req_id]);
    $_SESSION['flash_success'] = "Request Rejected.";
    redirect('upgrade_requests.php');
}

// Fetch requests
$requests = $db->select("
    SELECT r.*, u.name, u.email 
    FROM seller_upgrade_requests r
    JOIN users u ON r.user_id = u.id
    ORDER BY r.created_at DESC
");

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

$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="container mx-auto px-4 py-8">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-8 gap-4">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900">Upgrade Requests</h1>
                    <p class="text-gray-500 mt-1">Manage seller account upgrade requests from customers.</p>
                </div>
            </div>

            <?php if ($success_msg): ?>
                <div class="mb-6 p-4 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-800 flex items-start">
                    <i class="fas fa-check-circle mt-1 mr-3 text-emerald-500"></i>
                    <div class="font-medium"><?php echo $success_msg; ?></div>
                </div>
            <?php endif; ?>
            
            <?php if ($error_msg): ?>
                <div class="mb-6 p-4 rounded-xl bg-red-50 border border-red-200 text-red-800 flex items-start">
                    <i class="fas fa-exclamation-circle mt-1 mr-3 text-red-500"></i>
                    <div class="font-medium"><?php echo $error_msg; ?></div>
                </div>
            <?php endif; ?>

            <div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="bg-gray-50 border-b border-gray-100 text-gray-500 text-sm">
                                <th class="py-4 px-6 font-semibold">User</th>
                                <th class="py-4 px-6 font-semibold">Business Info</th>
                                <th class="py-4 px-6 font-semibold">Date</th>
                                <th class="py-4 px-6 font-semibold">Status</th>
                                <th class="py-4 px-6 font-semibold text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 text-sm">
                            <?php if (empty($requests)): ?>
                                <tr>
                                    <td colspan="5" class="py-8 text-center text-gray-500">
                                        <i class="fas fa-inbox text-3xl mb-3 text-gray-300"></i>
                                        <p>No upgrade requests found.</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($requests as $req): ?>
                                    <tr class="hover:bg-gray-50 transition-colors">
                                        <td class="py-4 px-6">
                                            <div class="font-bold text-gray-900"><?php echo htmlspecialchars($req['name']); ?></div>
                                            <div class="text-gray-500 text-xs">ID: #<?php echo $req['user_id']; ?> | <?php echo htmlspecialchars($req['email']); ?></div>
                                        </td>
                                        <td class="py-4 px-6">
                                            <div class="font-semibold text-gray-800"><i class="fas fa-store text-gray-400 mr-1"></i> <?php echo htmlspecialchars($req['business_name']); ?></div>
                                            <div class="text-gray-500 text-xs mt-1"><i class="fas fa-phone text-gray-400 mr-1"></i> <?php echo htmlspecialchars($req['business_phone']); ?></div>
                                            <?php if($req['business_address']): ?>
                                                <div class="text-gray-400 text-xs mt-1 truncate max-w-xs" title="<?php echo htmlspecialchars($req['business_address']); ?>">
                                                    <i class="fas fa-map-marker-alt mr-1"></i> <?php echo htmlspecialchars($req['business_address']); ?>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                        <td class="py-4 px-6 text-gray-500 whitespace-nowrap">
                                            <?php echo date('d M Y, h:i A', strtotime($req['created_at'])); ?>
                                        </td>
                                        <td class="py-4 px-6">
                                            <?php if ($req['status'] == 'Approved'): ?>
                                                <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-emerald-100 text-emerald-800">
                                                    <i class="fas fa-check mr-1"></i> Approved
                                                </span>
                                            <?php elseif ($req['status'] == 'Rejected'): ?>
                                                <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                    <i class="fas fa-times mr-1"></i> Rejected
                                                </span>
                                            <?php else: ?>
                                                <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-amber-100 text-amber-800">
                                                    <i class="fas fa-clock mr-1"></i> Pending
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="py-4 px-6 text-right">
                                            <?php if ($req['status'] == 'Pending'): ?>
                                                <div class="flex justify-end space-x-2">
                                                    <form method="POST" onsubmit="return confirm('Are you sure you want to APPROVE this request?');">
                                                        <input type="hidden" name="request_id" value="<?php echo $req['id']; ?>">
                                                        <button type="submit" name="approve_request" class="p-2 bg-emerald-50 text-emerald-600 rounded-lg hover:bg-emerald-500 hover:text-white transition-colors" title="Approve">
                                                            <i class="fas fa-check"></i>
                                                        </button>
                                                    </form>
                                                    <form method="POST" onsubmit="return confirm('Are you sure you want to REJECT this request?');">
                                                        <input type="hidden" name="request_id" value="<?php echo $req['id']; ?>">
                                                        <button type="submit" name="reject_request" class="p-2 bg-red-50 text-red-600 rounded-lg hover:bg-red-500 hover:text-white transition-colors" title="Reject">
                                                            <i class="fas fa-times"></i>
                                                        </button>
                                                    </form>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

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