<?php
session_start();
require_once '../connection.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Get user ID
$user_id = $_SESSION['user_id'];

// Fetch user data
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    session_destroy();
    header("Location: login.php?error=User account not found");
    exit();
}

$user = $result->fetch_assoc();
$stmt->close();

// Handle form submissions
$success_message = '';
$error_message = '';

// Update Personal Information
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_personal'])) {
    $full_name = trim($_POST['full_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $country = trim($_POST['country'] ?? '');
    $state = trim($_POST['state'] ?? '');
    $city = trim($_POST['city'] ?? '');
    $postal_code = trim($_POST['postal_code'] ?? '');
    
    // Validate phone number (basic validation)
    if (!empty($phone) && !preg_match('/^[0-9\s\-\+\(\)]{10,20}$/', $phone)) {
        $error_message = "Invalid phone number format";
    } else {
        // Check if any changes were made
        if ($full_name === $user['full_name'] && 
            $phone === $user['phone'] && 
            $country === $user['country'] && 
            $state === $user['state'] && 
            $city === $user['city'] && 
            $postal_code === $user['postal_code']) {
            $success_message = "No changes were made to your personal information.";
        } else {
            $stmt = $conn->prepare("UPDATE users SET full_name = ?, phone = ?, country = ?, state = ?, city = ?, postal_code = ?, updated_at = NOW() WHERE id = ?");
            if ($stmt) {
                $stmt->bind_param("ssssssi", $full_name, $phone, $country, $state, $city, $postal_code, $user_id);
                
                if ($stmt->execute()) {
                    $success_message = "Personal information updated successfully!";
                    // Refresh user data
                    $refresh_stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
                    if ($refresh_stmt) {
                        $refresh_stmt->bind_param("i", $user_id);
                        $refresh_stmt->execute();
                        $refresh_result = $refresh_stmt->get_result();
                        if ($refresh_result->num_rows > 0) {
                            $user = $refresh_result->fetch_assoc();
                        }
                        $refresh_stmt->close();
                    }
                } else {
                    $error_message = "Failed to update personal information: " . $conn->error;
                }
                $stmt->close();
            } else {
                $error_message = "Database error: Could not prepare statement";
            }
        }
    }
}

// Update Password
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_password'])) {
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    // Validate passwords
    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        $error_message = "All password fields are required";
    } elseif ($new_password !== $confirm_password) {
        $error_message = "New passwords do not match";
    } elseif (strlen($new_password) < 8) {
        $error_message = "Password must be at least 8 characters long";
    } elseif (!preg_match('/[A-Z]/', $new_password)) {
        $error_message = "Password must contain at least one uppercase letter";
    } elseif (!preg_match('/[0-9]/', $new_password)) {
        $error_message = "Password must contain at least one number";
    } elseif (!preg_match('/[^A-Za-z0-9]/', $new_password)) {
        $error_message = "Password must contain at least one special character";
    } else {
        // Verify current password
        if (password_verify($current_password, $user['password'])) {
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?");
            if ($stmt) {
                $stmt->bind_param("si", $hashed_password, $user_id);
                
                if ($stmt->execute()) {
                    $success_message = "Password updated successfully!";
                    // Update session to prevent logout
                    $_SESSION['password_updated'] = time();
                } else {
                    $error_message = "Failed to update password: " . $conn->error;
                }
                $stmt->close();
            } else {
                $error_message = "Database error: Could not prepare statement";
            }
        } else {
            $error_message = "Current password is incorrect";
        }
    }
}

// Update Notification Preferences
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_notifications'])) {
    $email_notifications = isset($_POST['email_notifications']) ? 1 : 0;
    $sms_notifications = isset($_POST['sms_notifications']) ? 1 : 0;
    $marketing_emails = isset($_POST['marketing_emails']) ? 1 : 0;
    
    $preferences = json_encode([
        'email' => $email_notifications,
        'sms' => $sms_notifications,
        'marketing' => $marketing_emails
    ]);
    
    // Check if preferences changed
    if ($user['notification_preferences'] === $preferences) {
        $success_message = "No changes were made to your notification preferences.";
    } else {
        $stmt = $conn->prepare("UPDATE users SET notification_preferences = ?, updated_at = NOW() WHERE id = ?");
        if ($stmt) {
            $stmt->bind_param("si", $preferences, $user_id);
            
            if ($stmt->execute()) {
                $success_message = "Notification preferences updated successfully!";
                // Update local user data
                $user['notification_preferences'] = $preferences;
            } else {
                $error_message = "Failed to update notification preferences: " . $conn->error;
            }
            $stmt->close();
        } else {
            $error_message = "Database error: Could not prepare statement";
        }
    }
}

// Parse notification preferences
$notification_prefs = [
    'email' => true,
    'sms' => false,
    'marketing' => true
];

if (!empty($user['notification_preferences'])) {
    $parsed_prefs = json_decode($user['notification_preferences'], true);
    if ($parsed_prefs && is_array($parsed_prefs)) {
        $notification_prefs = array_merge($notification_prefs, $parsed_prefs);
    }
}

// Fetch site settings
$site_settings = [];
$settings_stmt = $conn->prepare("SELECT setting_key, setting_value FROM site_settings WHERE setting_group = 'general'");
if ($settings_stmt) {
    if ($settings_stmt->execute()) {
        $settings_result = $settings_stmt->get_result();
        while ($row = $settings_result->fetch_assoc()) {
            $site_settings[$row['setting_key']] = $row['setting_value'];
        }
        $settings_result->free();
    }
    $settings_stmt->close();
} else {
    // Handle error or use defaults
    $site_settings['site_name'] = 'Trading Platform';
    $site_settings['site_email'] = 'support@example.com';
}

// List of countries for dropdown
$countries = [
    '' => 'Select Country',
    'US' => 'United States',
    'GB' => 'United Kingdom',
    'CA' => 'Canada',
    'AU' => 'Australia',
    'DE' => 'Germany',
    'FR' => 'France',
    'IT' => 'Italy',
    'ES' => 'Spain',
    'JP' => 'Japan',
    'CN' => 'China',
    'IN' => 'India',
    'BR' => 'Brazil',
    'MX' => 'Mexico',
    'RU' => 'Russia',
    'ZA' => 'South Africa',
    'NG' => 'Nigeria',
    'KE' => 'Kenya',
    'GH' => 'Ghana',
    'EG' => 'Egypt',
    'AE' => 'United Arab Emirates',
    'SA' => 'Saudi Arabia',
    'SG' => 'Singapore',
    'MY' => 'Malaysia',
    'ID' => 'Indonesia',
    'TH' => 'Thailand',
    'VN' => 'Vietnam',
    'PH' => 'Philippines',
    'KR' => 'South Korea',
    'IL' => 'Israel',
    'TR' => 'Turkey',
    'PL' => 'Poland',
    'NL' => 'Netherlands',
    'SE' => 'Sweden',
    'NO' => 'Norway',
    'DK' => 'Denmark',
    'FI' => 'Finland',
    'CH' => 'Switzerland',
    'AT' => 'Austria',
    'BE' => 'Belgium',
    'IE' => 'Ireland',
    'PT' => 'Portugal',
    'GR' => 'Greece',
    'CZ' => 'Czech Republic',
    'HU' => 'Hungary',
    'RO' => 'Romania',
    'BG' => 'Bulgaria',
    'HR' => 'Croatia',
    'SK' => 'Slovakia',
    'SI' => 'Slovenia',
    'LT' => 'Lithuania',
    'LV' => 'Latvia',
    'EE' => 'Estonia',
    'CY' => 'Cyprus',
    'MT' => 'Malta',
    'LU' => 'Luxembourg',
    'IS' => 'Iceland'
];

// Sanitize user data for display
function sanitize_display($value) {
    return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8');
}

// Get user's current country
$current_country = $user['country'] ?? '';
$current_full_name = sanitize_display($user['full_name']);
$current_phone = sanitize_display($user['phone']);
$current_state = sanitize_display($user['state']);
$current_city = sanitize_display($user['city']);
$current_postal_code = sanitize_display($user['postal_code']);
$current_username = sanitize_display($user['username']);
$current_email = sanitize_display($user['email']);

// Format dates
$created_date = !empty($user['created_at']) ? date('F j, Y', strtotime($user['created_at'])) : 'N/A';
$last_login_date = !empty($user['last_login']) ? date('M d, Y h:i A', strtotime($user['last_login'])) : 'Never';
$verified_date = !empty($user['verified_at']) ? date('M d, Y', strtotime($user['verified_at'])) : 'Not verified';

// Account status
$account_status = $user['account_status'] ?? 'active';
$account_status_class = ($account_status === 'active') ? 'text-green-400' : 'text-red-400';
$account_status_text = ucfirst($account_status);

// Email verification status
$email_verified = $user['email_verified'] ?? 0;
$email_status_class = $email_verified ? 'text-green-400' : 'text-yellow-400';
$email_status_text = $email_verified ? 'Verified' : 'Pending';

// KYC status
$kyc_status = $user['kyc_status'] ?? 'pending';
$kyc_status_class = ($kyc_status === 'verified') ? 'text-green-400' : 
                   (($kyc_status === 'rejected') ? 'text-red-400' : 'text-yellow-400');
$kyc_status_text = ucfirst($kyc_status);

// Two-factor status
$two_factor_enabled = $user['two_factor_enabled'] ?? 0;
$two_factor_class = $two_factor_enabled ? 'text-green-400' : 'text-red-400';
$two_factor_text = $two_factor_enabled ? 'Enabled' : 'Disabled';

// Account tier
$account_tier = $user['account_tier'] ?? 'basic';
$tier_names = [
    'basic' => 'Basic',
    'silver' => 'Silver',
    'gold' => 'Gold',
    'platinum' => 'Platinum',
    'vip' => 'VIP'
];
$tier_name = $tier_names[$account_tier] ?? 'Basic';

// Referral information
$referral_code = $user['referral_code'] ?? 'N/A';
$total_referrals = $user['total_referrals'] ?? 0;
$referral_earnings = number_format($user['referral_earnings'] ?? 0, 2);
$referred_by = $user['referred_by'] ? 'User #' . $user['referred_by'] : 'No one';

// Account ID
$account_id = str_pad($user['id'], 8, '0', STR_PAD_LEFT);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile Settings - <?php echo htmlspecialchars($site_settings['site_name'] ?? 'Trading Platform'); ?></title>
    <script src="https://cdn.tailwindcss.com"></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>
        :root {
            --sidebar-width: 16rem;
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
            min-height: 100vh;
            color: #e2e8f0;
        }
        
        /* Sidebar Styles */
        .sidebar {
            background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%);
            width: var(--sidebar-width);
            height: 100vh;
            position: fixed;
            left: 0;
            top: 0;
            z-index: 1000;
            transform: translateX(-100%);
            transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            overflow-y: auto;
            box-shadow: 4px 0 20px rgba(0, 0, 0, 0.3);
            border-right: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .sidebar.active {
            transform: translateX(0);
        }
        
        @media (min-width: 1024px) {
            .sidebar {
                transform: translateX(0) !important;
            }
        }
        
        .sidebar-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            z-index: 999;
            backdrop-filter: blur(4px);
        }
        
        .sidebar-overlay.active {
            display: block;
        }
        
        /* Main Content */
        .main-content {
            width: 100%;
            min-height: 100vh;
            transition: margin-left 0.3s ease;
        }
        
        @media (min-width: 1024px) {
            .main-content {
                margin-left: var(--sidebar-width);
                width: calc(100% - var(--sidebar-width));
            }
        }
        
        /* Mobile Menu Button */
        .mobile-menu-btn {
            position: fixed;
            top: 1.5rem;
            left: 1.5rem;
            z-index: 1100;
            width: 3rem;
            height: 3rem;
            background: rgba(30, 41, 59, 0.95);
            border-radius: 0.75rem;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid rgba(255, 255, 255, 0.1);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
        }
        
        @media (min-width: 1024px) {
            .mobile-menu-btn {
                display: none;
            }
        }
        
        /* Navigation Items */
        .nav-item {
            display: flex;
            align-items: center;
            padding: 0.875rem 1rem;
            border-radius: 0.75rem;
            margin: 0.25rem 0.75rem;
            color: #94a3b8;
            text-decoration: none;
            transition: all 0.2s ease;
            position: relative;
            overflow: hidden;
        }
        
        .nav-item::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            width: 3px;
            background: var(--primary-gradient);
            transform: translateX(-100%);
            transition: transform 0.3s ease;
        }
        
        .nav-item:hover {
            background: rgba(255, 255, 255, 0.05);
            color: #e2e8f0;
            transform: translateX(4px);
        }
        
        .nav-item:hover::before {
            transform: translateX(0);
        }
        
        .nav-item.active {
            background: rgba(102, 126, 234, 0.1);
            color: #e2e8f0;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
        }
        
        .nav-item.active::before {
            transform: translateX(0);
        }
        
        .nav-item.active i {
            color: #667eea;
            transform: scale(1.1);
        }
        
        .nav-item i {
            width: 1.5rem;
            margin-right: 0.875rem;
            transition: all 0.2s ease;
            font-size: 1.1rem;
        }
        
        /* Card Styles */
        .glass-card {
            background: rgba(30, 41, 59, 0.7);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 1.25rem;
            transition: all 0.3s ease;
        }
        
        .glass-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            border-color: rgba(102, 126, 234, 0.3);
        }
        
        /* Form Styles */
        .form-input {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.75rem;
            padding: 0.875rem 1rem;
            color: #e2e8f0;
            font-size: 0.95rem;
            transition: all 0.2s ease;
            width: 100%;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            background: rgba(255, 255, 255, 0.08);
        }
        
        .form-input::placeholder {
            color: #94a3b8;
        }
        
        .form-label {
            display: block;
            color: #cbd5e0;
            font-size: 0.875rem;
            font-weight: 500;
            margin-bottom: 0.5rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-select {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.75rem;
            padding: 0.875rem 1rem;
            color: #e2e8f0;
            font-size: 0.95rem;
            transition: all 0.2s ease;
            width: 100%;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3E%3Cpath stroke='%2394a3b8' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3E%3C/svg%3E");
            background-position: right 0.75rem center;
            background-repeat: no-repeat;
            background-size: 1.5em 1.5em;
        }
        
        .form-select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            background-color: rgba(255, 255, 255, 0.08);
        }
        
        .btn-primary {
            background: var(--primary-gradient);
            color: white;
            border: none;
            border-radius: 0.75rem;
            padding: 0.875rem 1.75rem;
            font-weight: 600;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(102, 126, 234, 0.4);
        }
        
        .btn-primary:active {
            transform: translateY(0);
        }
        
        .btn-secondary {
            background: rgba(255, 255, 255, 0.05);
            color: #cbd5e0;
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.75rem;
            padding: 0.875rem 1.75rem;
            font-weight: 500;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-secondary:hover {
            background: rgba(255, 255, 255, 0.1);
            color: #e2e8f0;
        }
        
        /* Toggle Switch */
        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 3.5rem;
            height: 2rem;
        }
        
        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #4a5568;
            transition: .4s;
            border-radius: 2rem;
        }
        
        .toggle-slider:before {
            position: absolute;
            content: "";
            height: 1.5rem;
            width: 1.5rem;
            left: 0.25rem;
            bottom: 0.25rem;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        
        input:checked + .toggle-slider {
            background-color: #667eea;
        }
        
        input:checked + .toggle-slider:before {
            transform: translateX(1.5rem);
        }
        
        /* Alert Messages */
        .alert-success {
            background: rgba(72, 187, 120, 0.1);
            border: 1px solid rgba(72, 187, 120, 0.2);
            color: #48bb78;
            padding: 1rem 1.5rem;
            border-radius: 0.75rem;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            animation: slideIn 0.3s ease-out;
        }
        
        .alert-error {
            background: rgba(245, 101, 101, 0.1);
            border: 1px solid rgba(245, 101, 101, 0.2);
            color: #f56565;
            padding: 1rem 1.5rem;
            border-radius: 0.75rem;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            animation: slideIn 0.3s ease-out;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        /* Close button for mobile sidebar */
        .sidebar-close-btn {
            display: none;
        }
        
        @media (max-width: 1023px) {
            .sidebar-close-btn {
                display: block;
                position: absolute;
                top: 1rem;
                right: 1rem;
                z-index: 1001;
                width: 2.5rem;
                height: 2.5rem;
                background: rgba(255, 255, 255, 0.1);
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                border: none;
                color: white;
                cursor: pointer;
                transition: all 0.2s ease;
                backdrop-filter: blur(10px);
            }
            
            .sidebar-close-btn:hover {
                background: rgba(255, 255, 255, 0.2);
                transform: rotate(90deg);
            }
        }
        
        /* Password strength indicator */
        .password-strength {
            height: 4px;
            border-radius: 2px;
            background: #4a5568;
            margin-top: 0.5rem;
            overflow: hidden;
        }
        
        .password-strength-fill {
            height: 100%;
            border-radius: 2px;
            transition: width 0.3s ease;
        }
        
        /* Tab Navigation */
        .tab-nav {
            display: flex;
            gap: 0.5rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 2rem;
            overflow-x: auto;
        }
        
        .tab-btn {
            padding: 0.75rem 1.5rem;
            color: #94a3b8;
            background: transparent;
            border: none;
            border-bottom: 2px solid transparent;
            font-weight: 500;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.2s ease;
            white-space: nowrap;
        }
        
        .tab-btn:hover {
            color: #e2e8f0;
        }
        
        .tab-btn.active {
            color: #667eea;
            border-bottom-color: #667eea;
            background: rgba(102, 126, 234, 0.05);
        }
        
        /* Scrollbar */
        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
        
        ::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.05);
        }
        
        ::-webkit-scrollbar-thumb {
            background: var(--primary-gradient);
            border-radius: 3px;
        }
    </style>
</head>
<body class="text-white">
   <?php include("nav.php"); ?>

        <!-- Main Content -->
        <div class="main-content">
            <!-- Top Bar -->
            <div class="border-b border-gray-800/50 p-6 glass-card mx-4 mt-4">
                <div class="flex flex-col lg:flex-row lg:justify-between lg:items-center gap-6">
                    <div>
                        <h2 class="text-2xl lg:text-3xl font-bold bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">
                            Profile Settings
                        </h2>
                        <p class="text-gray-400 mt-2">
                            Manage your account information, security, and notification preferences
                        </p>
                    </div>
                    <div class="flex items-center gap-4">
                        <a href="index.php" class="btn-secondary">
                            <i class="fas fa-arrow-left mr-2"></i> Back to Dashboard
                        </a>
                    </div>
                </div>
            </div>

            <!-- Profile Content -->
            <div class="p-6">
                <!-- Success/Error Messages -->
                <?php if ($success_message): ?>
                    <div class="alert-success">
                        <i class="fas fa-check-circle"></i>
                        <span><?php echo htmlspecialchars($success_message); ?></span>
                    </div>
                <?php endif; ?>
                
                <?php if ($error_message): ?>
                    <div class="alert-error">
                        <i class="fas fa-exclamation-circle"></i>
                        <span><?php echo htmlspecialchars($error_message); ?></span>
                    </div>
                <?php endif; ?>

                <!-- Tab Navigation -->
                <div class="tab-nav">
                    <button class="tab-btn active" onclick="showTab('personal')">
                        <i class="fas fa-user-circle mr-2"></i> Personal Information
                    </button>
                    <button class="tab-btn" onclick="showTab('password')">
                        <i class="fas fa-key mr-2"></i> Password
                    </button>
                   
                    <button class="tab-btn" onclick="showTab('account')">
                        <i class="fas fa-cog mr-2"></i> Account Details
                    </button>
                </div>

                <!-- Personal Information Tab -->
                <div id="personal-tab" class="tab-content">
                    <div class="glass-card p-6">
                        <h3 class="text-xl font-bold mb-6 flex items-center">
                            <i class="fas fa-user-circle mr-3 text-blue-400"></i> Personal Information
                        </h3>
                        
                        <form method="POST" action="">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div class="form-group">
                                    <label class="form-label">Full Name</label>
                                    <input type="text" name="full_name" class="form-input" 
                                           value="<?php echo htmlspecialchars($user['full_name'] ?? ''); ?>"
                                           placeholder="Enter your full name">
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Email Address</label>
                                    <input type="email" class="form-input bg-gray-800/30 cursor-not-allowed" 
                                           value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>"
                                           disabled readonly>
                                    <p class="text-xs text-gray-400 mt-2">Email cannot be changed. Contact support for assistance.</p>
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Phone Number</label>
                                    <input type="tel" name="phone" class="form-input" 
                                           value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>"
                                           placeholder="+1 (555) 123-4567">
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Username</label>
                                    <input type="text" class="form-input bg-gray-800/30 cursor-not-allowed" 
                                           value="<?php echo htmlspecialchars($user['username'] ?? ''); ?>"
                                           disabled readonly>
                                    <p class="text-xs text-gray-400 mt-2">Username cannot be changed.</p>
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Country</label>
                                    <select name="country" class="form-select">
                                        <option value="">Select Country</option>
                                        <?php foreach ($countries as $code => $name): ?>
                                            <option value="<?php echo $code; ?>" 
                                                <?php echo (($user['country'] ?? '') === $code) ? 'selected' : ''; ?>>
                                                <?php echo $name; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">State/Province</label>
                                    <input type="text" name="state" class="form-input" 
                                           value="<?php echo htmlspecialchars($user['state'] ?? ''); ?>"
                                           placeholder="Enter state or province">
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">City</label>
                                    <input type="text" name="city" class="form-input" 
                                           value="<?php echo htmlspecialchars($user['city'] ?? ''); ?>"
                                           placeholder="Enter city">
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Postal Code</label>
                                    <input type="text" name="postal_code" class="form-input" 
                                           value="<?php echo htmlspecialchars($user['postal_code'] ?? ''); ?>"
                                           placeholder="Enter postal code">
                                </div>
                            </div>
                            
                            <div class="mt-8 pt-6 border-t border-gray-700/50">
                                <button type="submit" name="update_personal" class="btn-primary">
                                    <i class="fas fa-save mr-2"></i> Save Changes
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Password Tab -->
                <div id="password-tab" class="tab-content hidden">
                    <div class="glass-card p-6">
                        <h3 class="text-xl font-bold mb-6 flex items-center">
                            <i class="fas fa-key mr-3 text-green-400"></i> Change Password
                        </h3>
                        
                        <form method="POST" action="">
                            <div class="space-y-6 max-w-2xl">
                                <div class="form-group">
                                    <label class="form-label">Current Password</label>
                                    <input type="password" name="current_password" class="form-input" 
                                           placeholder="Enter your current password" required>
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">New Password</label>
                                    <input type="password" name="new_password" id="newPassword" class="form-input" 
                                           placeholder="Enter new password" required
                                           oninput="checkPasswordStrength(this.value)">
                                    <div class="password-strength">
                                        <div id="passwordStrengthFill" class="password-strength-fill"></div>
                                    </div>
                                    <p class="text-xs text-gray-400 mt-2">
                                        <i class="fas fa-info-circle mr-1"></i>
                                        Password must be at least 8 characters long
                                    </p>
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Confirm New Password</label>
                                    <input type="password" name="confirm_password" class="form-input" 
                                           placeholder="Confirm new password" required>
                                </div>
                                
                                <div class="p-4 bg-gray-800/30 rounded-lg">
                                    <h4 class="font-medium text-sm mb-2 text-gray-300">Password Requirements</h4>
                                    <ul class="text-xs text-gray-400 space-y-1">
                                        <li class="flex items-center gap-2">
                                            <i class="fas fa-check text-green-400"></i>
                                            <span>Minimum 8 characters</span>
                                        </li>
                                        <li class="flex items-center gap-2">
                                            <i class="fas fa-check text-green-400"></i>
                                            <span>At least one uppercase letter</span>
                                        </li>
                                        <li class="flex items-center gap-2">
                                            <i class="fas fa-check text-green-400"></i>
                                            <span>At least one number</span>
                                        </li>
                                        <li class="flex items-center gap-2">
                                            <i class="fas fa-check text-green-400"></i>
                                            <span>At least one special character</span>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            
                            <div class="mt-8 pt-6 border-t border-gray-700/50">
                                <button type="submit" name="update_password" class="btn-primary">
                                    <i class="fas fa-key mr-2"></i> Update Password
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Notifications Tab -->
                <div id="notifications-tab" class="tab-content hidden">
                    <div class="glass-card p-6">
                        <h3 class="text-xl font-bold mb-6 flex items-center">
                            <i class="fas fa-bell mr-3 text-yellow-400"></i> Notification Preferences
                        </h3>
                        
                        <form method="POST" action="">
                            <div class="space-y-6">
                                <div class="p-4 bg-gray-800/30 rounded-lg">
                                    <div class="flex items-center justify-between">
                                        <div>
                                            <h4 class="font-medium">Email Notifications</h4>
                                            <p class="text-sm text-gray-400">Receive important updates via email</p>
                                        </div>
                                        <label class="toggle-switch">
                                            <input type="checkbox" name="email_notifications" 
                                                   <?php echo $notification_prefs['email'] ? 'checked' : ''; ?>>
                                            <span class="toggle-slider"></span>
                                        </label>
                                    </div>
                                </div>
                                
                                <div class="p-4 bg-gray-800/30 rounded-lg">
                                    <div class="flex items-center justify-between">
                                        <div>
                                            <h4 class="font-medium">SMS Notifications</h4>
                                            <p class="text-sm text-gray-400">Receive security alerts via SMS</p>
                                        </div>
                                        <label class="toggle-switch">
                                            <input type="checkbox" name="sms_notifications"
                                                   <?php echo $notification_prefs['sms'] ? 'checked' : ''; ?>>
                                            <span class="toggle-slider"></span>
                                        </label>
                                    </div>
                                </div>
                                
                                <div class="p-4 bg-gray-800/30 rounded-lg">
                                    <div class="flex items-center justify-between">
                                        <div>
                                            <h4 class="font-medium">Marketing Emails</h4>
                                            <p class="text-sm text-gray-400">Receive newsletters and promotions</p>
                                        </div>
                                        <label class="toggle-switch">
                                            <input type="checkbox" name="marketing_emails"
                                                   <?php echo $notification_prefs['marketing'] ? 'checked' : ''; ?>>
                                            <span class="toggle-slider"></span>
                                        </label>
                                    </div>
                                </div>
                                
                                <div class="p-4 bg-blue-900/10 border border-blue-900/30 rounded-lg">
                                    <h4 class="font-medium text-blue-400 mb-2">Notification Types</h4>
                                    <ul class="text-sm text-gray-400 space-y-1">
                                        <li><i class="fas fa-circle text-xs mr-2 text-blue-400"></i> Deposit & Withdrawal alerts</li>
                                        <li><i class="fas fa-circle text-xs mr-2 text-blue-400"></i> Investment updates</li>
                                        <li><i class="fas fa-circle text-xs mr-2 text-blue-400"></i> Security alerts</li>
                                        <li><i class="fas fa-circle text-xs mr-2 text-blue-400"></i> Market news</li>
                                    </ul>
                                </div>
                            </div>
                            
                            <div class="mt-8 pt-6 border-t border-gray-700/50">
                                <button type="submit" name="update_notifications" class="btn-primary">
                                    <i class="fas fa-save mr-2"></i> Save Preferences
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Account Details Tab -->
                <div id="account-tab" class="tab-content hidden">
                    <div class="glass-card p-6">
                        <h3 class="text-xl font-bold mb-6 flex items-center">
                            <i class="fas fa-cog mr-3 text-purple-400"></i> Account Details
                        </h3>
                        
                        <div class="space-y-6">
                            <!-- Account Information -->
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div class="p-4 bg-gray-800/30 rounded-lg">
                                    <h4 class="font-medium text-sm text-gray-400 mb-1">Account ID</h4>
                                    <p class="text-lg font-mono"><?php echo str_pad($user['id'], 8, '0', STR_PAD_LEFT); ?></p>
                                </div>
                                
                                <div class="p-4 bg-gray-800/30 rounded-lg">
                                    <h4 class="font-medium text-sm text-gray-400 mb-1">Account Status</h4>
                                    <p class="text-lg <?php echo ($user['account_status'] ?? '') === 'active' ? 'text-green-400' : 'text-red-400'; ?>">
                                        <?php echo ucfirst($user['account_status'] ?? 'unknown'); ?>
                                    </p>
                                </div>
                                
                                <div class="p-4 bg-gray-800/30 rounded-lg">
                                    <h4 class="font-medium text-sm text-gray-400 mb-1">Account Tier</h4>
                                    <p class="text-lg text-yellow-400">
                                        <i class="fas fa-crown mr-2"></i>
                                        <?php echo ucfirst($user['account_tier'] ?? 'basic'); ?>
                                    </p>
                                </div>
                                
                                <div class="p-4 bg-gray-800/30 rounded-lg">
                                    <h4 class="font-medium text-sm text-gray-400 mb-1">Email Verification</h4>
                                    <p class="text-lg <?php echo ($user['email_verified'] ?? 0) ? 'text-green-400' : 'text-yellow-400'; ?>">
                                        <i class="fas fa-<?php echo ($user['email_verified'] ?? 0) ? 'check' : 'exclamation'; ?>-circle mr-2"></i>
                                        <?php echo ($user['email_verified'] ?? 0) ? 'Verified' : 'Pending'; ?>
                                    </p>
                                </div>
                            </div>
                            
                            <!-- Security Information -->
                            <div class="p-4 bg-gray-800/30 rounded-lg">
                                <h4 class="font-medium text-lg mb-4">Security Information</h4>
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <p class="text-sm text-gray-400">Two-Factor Authentication</p>
                                        <p class="<?php echo ($user['two_factor_enabled'] ?? 0) ? 'text-green-400' : 'text-red-400'; ?>">
                                            <i class="fas fa-<?php echo ($user['two_factor_enabled'] ?? 0) ? 'check' : 'times'; ?> mr-2"></i>
                                            <?php echo ($user['two_factor_enabled'] ?? 0) ? 'Enabled' : 'Disabled'; ?>
                                        </p>
                                    </div>
                                    
                                    <div>
                                        <p class="text-sm text-gray-400">KYC Status</p>
                                        <p class="<?php echo ($user['kyc_status'] ?? '') === 'verified' ? 'text-green-400' : 'text-yellow-400'; ?>">
                                            <?php echo ucfirst($user['kyc_status'] ?? 'pending'); ?>
                                        </p>
                                    </div>
                                    
                                    <div>
                                        <p class="text-sm text-gray-400">Last Login</p>
                                        <p><?php echo $user['last_login'] ? date('M d, Y h:i A', strtotime($user['last_login'])) : 'Never'; ?></p>
                                    </div>
                                    
                                    <div>
                                        <p class="text-sm text-gray-400">Member Since</p>
                                        <p><?php echo date('M d, Y', strtotime($user['created_at'])); ?></p>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Referral Information -->
                            <div class="p-4 bg-gray-800/30 rounded-lg">
                                <h4 class="font-medium text-lg mb-4">Referral Information</h4>
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <p class="text-sm text-gray-400">Your Referral Code</p>
                                        <p class="text-lg font-mono font-bold text-purple-400">
                                            <?php echo $user['referral_code'] ?? 'N/A'; ?>
                                        </p>
                                    </div>
                                    
                                    <div>
                                        <p class="text-sm text-gray-400">Total Referrals</p>
                                        <p class="text-lg"><?php echo $user['total_referrals'] ?? 0; ?></p>
                                    </div>
                                    
                                    <div>
                                        <p class="text-sm text-gray-400">Referral Earnings</p>
                                        <p class="text-lg text-green-400">$<?php echo number_format($user['referral_earnings'] ?? 0, 2); ?></p>
                                    </div>
                                    
                                    <div>
                                        <p class="text-sm text-gray-400">Referred By</p>
                                        <p class="text-lg"><?php echo $user['referred_by'] ? 'User #' . $user['referred_by'] : 'No one'; ?></p>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Account Actions -->
                            <div class="p-4 bg-gray-800/30 rounded-lg">
                                <h4 class="font-medium text-lg mb-4">Account Actions</h4>
                                <div class="flex flex-wrap gap-3">
                                    <a href="deposit.php" class="btn-secondary">
                                        <i class="fas fa-shield-alt mr-2"></i> Deposit
                                    </a>
                                    <a href="investment.php" class="btn-secondary">
                                        <i class="fas fa-id-card mr-2"></i> Invest
                                    </a>
                                    <a href="support.php" class="btn-secondary">
                                        <i class="fas fa-users mr-2"></i> Support
                                    </a>
                                    <a href="logout.php" class="btn-secondary bg-red-900/20 hover:bg-red-900/30 text-red-400">
                                        <i class="fas fa-sign-out-alt mr-2"></i> Logout
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Footer -->
                <div class="mt-8 text-center">
                    <p class="text-gray-500 text-sm">
                        Last updated: <?php echo date('F j, Y, g:i a'); ?> | 
                        Need help? <a href="support.php" class="text-blue-400 hover:text-blue-300">Contact Support</a>
                    </p>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Mobile menu toggle functionality
        const menuToggle = document.getElementById('menuToggle');
        const closeSidebar = document.getElementById('closeSidebar');
        const sidebar = document.getElementById('sidebar');
        const sidebarOverlay = document.getElementById('sidebarOverlay');
        const body = document.body;

        // Function to toggle sidebar
        function toggleSidebar() {
            sidebar.classList.toggle('active');
            sidebarOverlay.classList.toggle('active');
            
            if (sidebar.classList.contains('active')) {
                body.classList.add('sidebar-open');
                body.style.overflow = 'hidden';
            } else {
                body.classList.remove('sidebar-open');
                body.style.overflow = '';
            }
        }

        // Function to close sidebar
        function closeSidebarFunc() {
            sidebar.classList.remove('active');
            sidebarOverlay.classList.remove('active');
            body.classList.remove('sidebar-open');
            body.style.overflow = '';
        }

        // Event listeners for mobile menu
        menuToggle.addEventListener('click', toggleSidebar);
        closeSidebar.addEventListener('click', closeSidebarFunc);
        sidebarOverlay.addEventListener('click', closeSidebarFunc);

        // Tab Navigation
        function showTab(tabName) {
            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.add('hidden');
            });
            
            // Remove active class from all tab buttons
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            
            // Show selected tab
            document.getElementById(tabName + '-tab').classList.remove('hidden');
            
            // Add active class to clicked button
            event.target.classList.add('active');
        }

        // Password strength checker
        function checkPasswordStrength(password) {
            let strength = 0;
            const fill = document.getElementById('passwordStrengthFill');
            
            if (password.length >= 8) strength += 25;
            if (/[A-Z]/.test(password)) strength += 25;
            if (/[0-9]/.test(password)) strength += 25;
            if (/[^A-Za-z0-9]/.test(password)) strength += 25;
            
            // Update progress bar
            fill.style.width = strength + '%';
            
            // Update color based on strength
            if (strength < 50) {
                fill.style.backgroundColor = '#f56565'; // Red
            } else if (strength < 75) {
                fill.style.backgroundColor = '#ed8936'; // Orange
            } else {
                fill.style.backgroundColor = '#48bb78'; // Green
            }
        }

        // Handle window resize
        window.addEventListener('resize', function() {
            if (window.innerWidth >= 1024) {
                sidebar.classList.add('active');
                sidebarOverlay.classList.remove('active');
                body.classList.remove('sidebar-open');
                body.style.overflow = '';
            } else {
                if (!sidebar.classList.contains('active')) {
                    sidebar.classList.remove('active');
                    sidebarOverlay.classList.remove('active');
                    body.classList.remove('sidebar-open');
                    body.style.overflow = '';
                }
            }
        });

        // Initialize sidebar state on load
        document.addEventListener('DOMContentLoaded', function() {
            if (window.innerWidth >= 1024) {
                sidebar.classList.add('active');
            }
            
            // Set active nav item
            document.querySelectorAll('.nav-item').forEach(nav => {
                const href = nav.getAttribute('href');
                if (href && href.includes('profile.php')) {
                    nav.classList.add('active');
                } else {
                    nav.classList.remove('active');
                }
            });
            
            // Initialize password strength checker
            const newPasswordInput = document.getElementById('newPassword');
            if (newPasswordInput) {
                newPasswordInput.addEventListener('input', function() {
                    checkPasswordStrength(this.value);
                });
            }
        });

        // Escape key closes sidebar
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && sidebar.classList.contains('active')) {
                closeSidebarFunc();
            }
        });

        // Form validation
        document.querySelectorAll('form').forEach(form => {
            form.addEventListener('submit', function(e) {
                // Clear previous error messages
                const errorElements = form.querySelectorAll('.error-message');
                errorElements.forEach(el => el.remove());
                
                let hasError = false;
                
                // Password form validation
                if (form.querySelector('[name="update_password"]')) {
                    const currentPass = form.querySelector('[name="current_password"]');
                    const newPass = form.querySelector('[name="new_password"]');
                    const confirmPass = form.querySelector('[name="confirm_password"]');
                    
                    if (currentPass && newPass && confirmPass) {
                        if (newPass.value !== confirmPass.value) {
                            showFieldError(confirmPass, 'Passwords do not match');
                            hasError = true;
                        }
                        
                        if (newPass.value.length < 8) {
                            showFieldError(newPass, 'Password must be at least 8 characters long');
                            hasError = true;
                        }
                    }
                }
                
                // Phone number validation
                const phoneInput = form.querySelector('[name="phone"]');
                if (phoneInput && phoneInput.value.trim() !== '') {
                    const phoneRegex = /^[0-9\s\-\+\(\)]{10,20}$/;
                    if (!phoneRegex.test(phoneInput.value.trim())) {
                        showFieldError(phoneInput, 'Invalid phone number format');
                        hasError = true;
                    }
                }
                
                if (hasError) {
                    e.preventDefault();
                }
            });
        });

        function showFieldError(input, message) {
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-message text-red-400 text-xs mt-1 flex items-center gap-1';
            errorDiv.innerHTML = `<i class="fas fa-exclamation-circle"></i> ${message}`;
            input.parentNode.appendChild(errorDiv);
            input.classList.add('border-red-500');
            
            // Remove error on input
            input.addEventListener('input', function() {
                errorDiv.remove();
                this.classList.remove('border-red-500');
            }, { once: true });
        }

        // Country selector enhancement
        const countrySelect = document.querySelector('select[name="country"]');
        if (countrySelect) {
            countrySelect.addEventListener('change', function() {
                // You could add logic here to load states/provinces based on country
            });
        }
    </script>
</body>
</html>