<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Jump up from admin/ to root
require_once __DIR__ . '/../config/config.php';

// Auth Check
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: ../login.php");
    exit();
}

$success_msg = '';
$error_msg = '';

// =========================================================
// CRUD OPERATIONS
// =========================================================

// 1. CREATE: Add New User
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_user'])) {
    $full_name     = trim($_POST['full_name'] ?? '');
    $email         = trim($_POST['email'] ?? '');
    $referral_code = strtoupper(trim($_POST['referral_code'] ?? ''));
    $status        = $_POST['status'] ?? 'ACTIVE';
    $password      = password_hash('password123', PASSWORD_BCRYPT);

    // Generate referral code if not provided
    if (empty($referral_code)) {
        $referral_code = strtoupper(substr(preg_replace('/[^a-zA-Z]/', '', $full_name), 0, 3) . bin2hex(random_bytes(3)));
    }

    $check = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $check->execute([$email]);
    if ($check->rowCount() > 0) {
        $error_msg = "A user with that email already exists.";
    } else {
        $stmt = $pdo->prepare("INSERT INTO users (full_name, email, password, referral_code, user_tier, status) VALUES (?, ?, ?, ?, 'FREE', ?)");
        if ($stmt->execute([$full_name, $email, $password, $referral_code, $status])) {
            $success_msg = "User created successfully! Default password is 'password123'.";
        } else {
            $error_msg = "Failed to create user.";
        }
    }
}

// 2. UPDATE: Edit User
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_user'])) {
    $id            = intval($_POST['edit_id'] ?? 0);
    $full_name     = trim($_POST['full_name'] ?? '');
    $email         = trim($_POST['email'] ?? '');
    $referral_code = strtoupper(trim($_POST['referral_code'] ?? ''));
    $status        = $_POST['status'] ?? 'ACTIVE';

    if ($id > 0) {
        $stmt = $pdo->prepare("UPDATE users SET full_name=?, email=?, referral_code=?, status=? WHERE id=?");
        if ($stmt->execute([$full_name, $email, $referral_code, $status, $id])) {
            $success_msg = "User record updated successfully!";
        } else {
            $error_msg = "Failed to update user record.";
        }
    }
}

// 3. ACTION: Toggle Ban/Unban
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_ban'])) {
    $user_id = intval($_POST['user_id'] ?? 0);
    $new_status = $_POST['new_status'] ?? 'ACTIVE';
    
    if ($user_id > 0) {
        $update_stmt = $pdo->prepare("UPDATE users SET status = ? WHERE id = ?");
        $update_stmt->execute([$new_status, $user_id]);
        $success_msg = "User status changed to " . $new_status . ".";
    }
}

// 4. ACTION: Reset Password
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_password'])) {
    $user_id = intval($_POST['user_id'] ?? 0);
    $new_password = password_hash('password123', PASSWORD_BCRYPT);
    
    if ($user_id > 0) {
        $update_stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
        $update_stmt->execute([$new_password, $user_id]);
        $success_msg = "Password reset successfully to 'password123'.";
    }
}

// 5. ACTION: Promote to VIP (30 days)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['promote_vip'])) {
    $user_id = intval($_POST['user_id'] ?? 0);
    
    if ($user_id > 0) {
        $upgrade_sql = "
            UPDATE users 
            SET user_tier = 'VIP',
                vip_expires_at = CASE 
                    WHEN vip_expires_at > NOW() THEN DATE_ADD(vip_expires_at, INTERVAL 30 DAY)
                    ELSE DATE_ADD(NOW(), INTERVAL 30 DAY)
                END
            WHERE id = ?
        ";
        $pdo->prepare($upgrade_sql)->execute([$user_id]);
        $success_msg = "User successfully promoted to VIP for 30 Days!";
    }
}

// 6. DELETE: Remove User
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_user'])) {
    $user_id = intval($_POST['delete_id'] ?? 0);
    if ($user_id > 0) {
        $delete_stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
        if ($delete_stmt->execute([$user_id])) {
            $success_msg = "User permanently deleted from the database.";
        }
    }
}

// =========================================================
// DATA FETCHING
// =========================================================

$edit_mode = false;
$edit_data = [];
if (isset($_GET['edit'])) {
    $edit_mode = true;
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([intval($_GET['edit'])]);
    $edit_data = $stmt->fetch(PDO::FETCH_ASSOC);
}

$stmt = $pdo->query("SELECT * FROM users ORDER BY id DESC LIMIT 100");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Analytics
$total_users = count($users);
$active_users = 0;
$banned_users = 0;
$vip_users = 0;
foreach ($users as $u) {
    if (($u['status'] ?? 'ACTIVE') === 'ACTIVE') $active_users++;
    if (($u['status'] ?? 'ACTIVE') === 'BANNED') $banned_users++;
    if (($u['user_tier'] ?? 'FREE') === 'VIP') $vip_users++;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Users & VIPs Hub</title>
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/css/output.css?v=<?php echo time(); ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style> 
        body { font-family: 'Inter', sans-serif; } 
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
        .dark ::-webkit-scrollbar-thumb { background: #334155; }
        .action-btn {
            transition: all 0.15s ease;
        }
        .action-btn:hover { transform: scale(1.05); }
    </style>
    <script>
        if (localStorage.getItem('fpp_theme') === 'dark') {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
    </script>
</head>
<body class="bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-gray-200 antialiased min-h-screen flex flex-col md:flex-row transition-colors duration-300">

    <?php include __DIR__ . '/includes/admin-sidebar.php'; ?>

    <main class="flex-1 p-4 sm:p-6 md:p-8 overflow-x-hidden flex flex-col gap-6">
        
        <!-- ========== HEADER ========== -->
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div>
                <h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 dark:text-white tracking-wide">Users & VIPs Hub</h2>
                <p class="text-xs text-slate-500 dark:text-gray-400 mt-0.5">Manage platform members, track subscriptions, and control access.</p>
            </div>
        </div>

        <!-- ========== MESSAGES ========== -->
        <?php if(!empty($success_msg)): ?>
            <div class="bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-500/10 dark:border-emerald-500/30 dark:text-emerald-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm text-sm font-medium">
                <span>✅</span> <?php echo $success_msg; ?>
            </div>
        <?php endif; ?>
        <?php if(!empty($error_msg)): ?>
            <div class="bg-rose-50 border-rose-200 text-rose-700 dark:bg-rose-500/10 dark:border-rose-500/30 dark:text-rose-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm text-sm font-medium">
                <span>❌</span> <?php echo $error_msg; ?>
            </div>
        <?php endif; ?>

        <!-- ========== STATS CARDS ========== -->
        <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4">
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 p-4 sm:p-5 rounded-2xl shadow-sm transition-colors duration-300">
                <span class="text-[9px] sm:text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-black">Total Profiles</span>
                <span class="text-xl sm:text-2xl font-extrabold text-slate-900 dark:text-white mt-1 block"><?php echo $total_users; ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 p-4 sm:p-5 rounded-2xl shadow-sm transition-colors duration-300">
                <span class="text-[9px] sm:text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-black">Active</span>
                <span class="text-xl sm:text-2xl font-extrabold text-emerald-600 dark:text-emerald-500 mt-1 block"><?php echo $active_users; ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 p-4 sm:p-5 rounded-2xl shadow-sm transition-colors duration-300">
                <span class="text-[9px] sm:text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-black">VIP Members</span>
                <span class="text-xl sm:text-2xl font-extrabold text-amber-500 dark:text-amber-400 mt-1 block"><?php echo $vip_users; ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 p-4 sm:p-5 rounded-2xl shadow-sm transition-colors duration-300">
                <span class="text-[9px] sm:text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-black">Banned</span>
                <span class="text-xl sm:text-2xl font-extrabold text-rose-600 dark:text-rose-500 mt-1 block"><?php echo $banned_users; ?></span>
            </div>
        </div>

        <!-- ========== MAIN CONTENT ========== -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            
            <!-- FORM CARD -->
            <div class="lg:col-span-1">
                <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 sm:p-6 shadow-sm transition-colors duration-300 sticky top-6">
                    <div class="flex items-center justify-between border-b border-slate-200 dark:border-slate-800 pb-3 mb-5">
                        <h3 class="font-bold text-lg text-slate-900 dark:text-white">
                            <?php echo $edit_mode ? '✏️ Edit Member' : '➕ Add Member'; ?>
                        </h3>
                        <?php if($edit_mode): ?>
                            <a href="users.php" class="text-[10px] bg-slate-200 text-slate-600 dark:bg-slate-800 dark:text-gray-400 px-3 py-1.5 rounded-lg font-bold uppercase tracking-wider hover:bg-slate-300 dark:hover:bg-slate-700 transition">Cancel</a>
                        <?php endif; ?>
                    </div>

                    <form action="users.php" method="POST" class="space-y-4">
                        <?php if($edit_mode): ?>
                            <input type="hidden" name="edit_id" value="<?php echo $edit_data['id']; ?>">
                        <?php endif; ?>

                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1 tracking-wider uppercase font-bold">Full Name</label>
                            <input type="text" name="full_name" value="<?php echo $edit_mode ? htmlspecialchars($edit_data['full_name']) : ''; ?>" required class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 text-sm transition-all">
                        </div>
                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1 tracking-wider uppercase font-bold">Email Address</label>
                            <input type="email" name="email" value="<?php echo $edit_mode ? htmlspecialchars($edit_data['email']) : ''; ?>" required class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 text-sm transition-all">
                        </div>
                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1 tracking-wider uppercase font-bold">Referral Code</label>
                            <input type="text" name="referral_code" value="<?php echo $edit_mode ? htmlspecialchars($edit_data['referral_code'] ?? '') : ''; ?>" placeholder="Auto-generated if left empty" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 text-sm transition-all">
                        </div>
                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 mb-1 tracking-wider uppercase font-bold">Account Status</label>
                            <select name="status" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 text-sm transition-all">
                                <option value="ACTIVE" <?php echo ($edit_mode && ($edit_data['status'] ?? 'ACTIVE') == 'ACTIVE') ? 'selected' : ''; ?>>✅ ACTIVE</option>
                                <option value="BANNED" <?php echo ($edit_mode && ($edit_data['status'] ?? 'ACTIVE') == 'BANNED') ? 'selected' : ''; ?>>🚫 BANNED</option>
                            </select>
                        </div>

                        <?php if($edit_mode): ?>
                            <button type="submit" name="update_user" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3.5 rounded-xl transition shadow-lg shadow-blue-500/20 text-sm tracking-wider">💾 Save Changes</button>
                        <?php else: ?>
                            <button type="submit" name="add_user" class="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-3.5 rounded-xl transition shadow-lg shadow-emerald-500/20 text-sm tracking-wider">➕ Create Account</button>
                        <?php endif; ?>
                    </form>

                    <div class="mt-5 pt-4 border-t border-slate-200 dark:border-slate-800">
                        <div class="bg-slate-50 dark:bg-slate-950 p-3 rounded-xl border border-slate-200 dark:border-slate-800 flex items-center justify-between text-xs">
                            <span class="font-semibold text-slate-600 dark:text-gray-400 tracking-wider">Self-Referral Block</span>
                            <span class="text-emerald-600 dark:text-emerald-500 font-extrabold tracking-widest uppercase">✅ Enabled</span>
                        </div>
                        <p class="text-[9px] text-slate-400 dark:text-gray-500 mt-2">Default password for new accounts: <code class="bg-slate-100 dark:bg-slate-800 px-2 py-0.5 rounded font-mono">password123</code></p>
                    </div>
                </div>
            </div>

            <!-- TABLE CARD -->
            <div class="lg:col-span-2">
                <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-4 sm:p-6 shadow-sm transition-colors duration-300">
                    <h3 class="font-bold text-lg mb-5 text-slate-900 dark:text-white border-b border-slate-200 dark:border-slate-800 pb-3">Membership Directory</h3>
                    
                    <div class="overflow-x-auto -mx-4 sm:-mx-6 px-4 sm:px-6">
                        <table class="w-full text-left text-sm border-collapse min-w-[750px]">
                            <thead>
                                <tr class="text-slate-500 dark:text-gray-500 border-b border-slate-200 dark:border-slate-800 text-[10px] tracking-wider uppercase font-black">
                                    <th class="py-3 px-2">User</th>
                                    <th class="py-3 px-2 text-center">Tier & Status</th>
                                    <th class="py-3 px-2 text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 dark:divide-slate-800/60 text-slate-700 dark:text-gray-300 text-xs">
                                <?php foreach($users as $u): 
                                    $is_banned = ($u['status'] ?? 'ACTIVE') === 'BANNED';
                                    $is_vip = ($u['user_tier'] ?? 'FREE') === 'VIP';
                                    $joined_date = date("d M Y", strtotime($u['created_at']));
                                    $avatar_name = urlencode($u['full_name']);
                                    $status_dot = $is_banned ? 'bg-rose-500' : 'bg-emerald-500';
                                ?>
                                <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/40 transition group">
                                    
                                    <td class="py-3 px-2">
                                        <div class="flex items-center gap-3">
                                            <div class="w-8 h-8 bg-slate-200 dark:bg-gray-700 rounded-full overflow-hidden shrink-0">
                                                <img src="https://ui-avatars.com/api/?name=<?php echo $avatar_name; ?>&background=random&size=64" alt="Avatar" class="w-full h-full object-cover">
                                            </div>
                                            <div>
                                                <div class="font-bold text-slate-900 dark:text-white text-sm flex items-center gap-2">
                                                    <?php echo htmlspecialchars($u['full_name']); ?>
                                                    <span class="w-2 h-2 rounded-full <?php echo $status_dot; ?>"></span>
                                                </div>
                                                <div class="text-[10px] text-slate-500 dark:text-gray-400">
                                                    <?php echo htmlspecialchars($u['email']); ?> • <?php echo $joined_date; ?>
                                                </div>
                                                <div class="text-[9px] text-amber-600 dark:text-amber-500 font-mono font-bold">
                                                    REF: <?php echo htmlspecialchars($u['referral_code'] ?: '—'); ?>
                                                </div>
                                            </div>
                                        </div>
                                    </td>

                                    <td class="py-3 px-2 text-center">
                                        <div class="flex flex-col items-center gap-1">
                                            <?php if($is_vip): ?>
                                                <span class="bg-amber-500/10 text-amber-500 border border-amber-500/30 text-[9px] px-2.5 py-0.5 rounded-full font-black tracking-wider uppercase">👑 VIP</span>
                                                <?php if(!empty($u['vip_expires_at'])): ?>
                                                    <span class="text-[9px] font-mono text-slate-400">Exp: <?php echo date("d M Y", strtotime($u['vip_expires_at'])); ?></span>
                                                <?php else: ?>
                                                    <span class="text-[9px] text-rose-500 font-bold">No Expiry</span>
                                                <?php endif; ?>
                                            <?php else: ?>
                                                <span class="bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400 text-[9px] px-2.5 py-0.5 rounded-full font-bold tracking-wider border border-slate-200 dark:border-slate-700">👤 FREE</span>
                                            <?php endif; ?>
                                            <span class="text-[9px] font-bold <?php echo $is_banned ? 'text-rose-500' : 'text-emerald-500'; ?>">
                                                <?php echo $is_banned ? '🚫 BANNED' : 'ACTIVE'; ?>
                                            </span>
                                        </div>
                                    </td>

                                    <td class="py-3 px-2 text-right">
                                        <div class="flex items-center justify-end gap-1.5 flex-wrap">
                                            
                                            <form action="users.php" method="POST" onsubmit="return confirm('Promote <?php echo htmlspecialchars($u['full_name']); ?> to VIP for 30 days?');" class="inline">
                                                <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                                                <button type="submit" name="promote_vip" title="Promote to VIP" class="action-btn bg-amber-50 text-amber-600 border border-amber-200 hover:bg-amber-100 dark:bg-amber-500/10 dark:text-amber-400 dark:border-amber-500/30 dark:hover:bg-amber-500/20 px-2 py-1.5 rounded-lg text-[9px] font-black uppercase tracking-wider transition">👑</button>
                                            </form>

                                            <a href="users.php?edit=<?php echo $u['id']; ?>" title="Edit User" class="action-btn bg-blue-50 text-blue-600 border border-blue-200 hover:bg-blue-100 dark:bg-blue-500/10 dark:text-blue-400 dark:border-blue-500/30 dark:hover:bg-blue-500/20 w-7 h-7 flex items-center justify-center rounded-lg text-sm transition">✏️</a>
                                            
                                            <form action="users.php" method="POST" onsubmit="return confirm('Reset password for <?php echo htmlspecialchars($u['full_name']); ?> to \'password123\'?');" class="inline">
                                                <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                                                <button type="submit" name="reset_password" title="Reset Password" class="action-btn bg-indigo-50 text-indigo-600 border border-indigo-200 hover:bg-indigo-100 dark:bg-indigo-500/10 dark:text-indigo-400 dark:border-indigo-500/30 dark:hover:bg-indigo-500/20 w-7 h-7 flex items-center justify-center rounded-lg text-sm transition">🔑</button>
                                            </form>

                                            <form action="users.php" method="POST" onsubmit="return confirm('Change ban status for <?php echo htmlspecialchars($u['full_name']); ?>?');" class="inline">
                                                <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                                                <input type="hidden" name="new_status" value="<?php echo $is_banned ? 'ACTIVE' : 'BANNED'; ?>">
                                                <button type="submit" name="toggle_ban" title="<?php echo $is_banned ? 'Unban User' : 'Ban User'; ?>" class="action-btn bg-slate-100 text-slate-600 border border-slate-200 hover:bg-slate-200 dark:bg-slate-800 dark:text-slate-300 dark:border-slate-700 dark:hover:bg-slate-700 w-7 h-7 flex items-center justify-center rounded-lg text-sm transition">
                                                    <?php echo $is_banned ? '♻️' : '🚫'; ?>
                                                </button>
                                            </form>

                                            <form action="users.php" method="POST" onsubmit="return confirm('⚠️ Permanently delete <?php echo htmlspecialchars($u['full_name']); ?>? This cannot be undone.');" class="inline">
                                                <input type="hidden" name="delete_id" value="<?php echo $u['id']; ?>">
                                                <button type="submit" name="delete_user" title="Delete User" class="action-btn bg-rose-50 text-rose-600 border border-rose-200 hover:bg-rose-100 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/30 dark:hover:bg-rose-500/20 w-7 h-7 flex items-center justify-center rounded-lg text-sm transition">🗑️</button>
                                            </form>

                                        </div>
                                    </td>

                                </tr>
                                <?php endforeach; ?>
                                <?php if(empty($users)): ?>
                                <tr><td colspan="3" class="py-8 text-center text-slate-400 dark:text-gray-500 text-xs">No registered members found.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

        </div>
    </main>

</body>
</html>