<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

require_once "include/db.php";
mysqli_set_charset($conn, "utf8mb4");

$userId = intval($_SESSION['user_id']);
$success = '';
$error = '';

// Defensive Database Logic: Auto-create columns if they don't exist
$checkPinCol = mysqli_query($conn, "SHOW COLUMNS FROM users LIKE 'transaction_pin'");
if (mysqli_num_rows($checkPinCol) == 0) {
    mysqli_query($conn, "ALTER TABLE users ADD COLUMN transaction_pin VARCHAR(10) DEFAULT '0000'");
}
$checkBioCol = mysqli_query($conn, "SHOW COLUMNS FROM users LIKE 'biometric_enabled'");
if (mysqli_num_rows($checkBioCol) == 0) {
    mysqli_query($conn, "ALTER TABLE users ADD COLUMN biometric_enabled TINYINT(1) DEFAULT 0");
}
$checkBioIdCol = mysqli_query($conn, "SHOW COLUMNS FROM users LIKE 'biometric_id'");
if (mysqli_num_rows($checkBioIdCol) == 0) {
    mysqli_query($conn, "ALTER TABLE users ADD COLUMN biometric_id VARCHAR(255) DEFAULT NULL");
}
$checkBioCredCol = mysqli_query($conn, "SHOW COLUMNS FROM users LIKE 'biometric_credential'");
if (mysqli_num_rows($checkBioCredCol) == 0) {
    mysqli_query($conn, "ALTER TABLE users ADD COLUMN biometric_credential TEXT DEFAULT NULL");
}

// Fetch User Data
$sql = "SELECT * FROM users WHERE id = $userId LIMIT 1";
$result = mysqli_query($conn, $sql);
$currentUser = ($result && mysqli_num_rows($result) > 0) ? mysqli_fetch_assoc($result) : null;

if (!$currentUser) {
    header("Location: ../login.php");
    exit;
}

$dbTheme = $_SESSION['theme'] ?? ($currentUser['theme'] ?? '#0ea5e9');
$userName = $currentUser['username'] ?? 'Trader';
$userBalance = $currentUser['balance'] ?? 0;
$biometricEnabled = isset($currentUser['biometric_enabled']) && $currentUser['biometric_enabled'] == 1;

// Handle AJAX Biometric Registration
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action']) && $_POST['ajax_action'] === 'register_biometric') {
    header('Content-Type: application/json');
    $credentialId = mysqli_real_escape_string($conn, $_POST['credential_id'] ?? '');
    $credentialData = mysqli_real_escape_string($conn, $_POST['credential_data'] ?? '');
    
    if (empty($credentialId) || empty($credentialData)) {
        echo json_encode(['success' => false, 'message' => 'Invalid biometric data received.']);
        exit;
    }
    
    $updateSql = "UPDATE users SET biometric_enabled = 1, biometric_id = '$credentialId', biometric_credential = '$credentialData' WHERE id = $userId";
    if (mysqli_query($conn, $updateSql)) {
        echo json_encode(['success' => true, 'message' => 'Biometric authentication registered successfully!']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Database error: ' . mysqli_error($conn)]);
    }
    exit;
}

// Handle AJAX Biometric Login Verification
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action']) && $_POST['ajax_action'] === 'verify_biometric_login') {
    header('Content-Type: application/json');
    $credentialId = mysqli_real_escape_string($conn, $_POST['credential_id'] ?? '');
    
    $checkSql = "SELECT id, username, theme FROM users WHERE biometric_enabled = 1 AND biometric_id = '$credentialId' LIMIT 1";
    $checkResult = mysqli_query($conn, $checkSql);
    
    if ($checkResult && mysqli_num_rows($checkResult) > 0) {
        $bioUser = mysqli_fetch_assoc($checkResult);
        $_SESSION['user_id'] = $bioUser['id'];
        $_SESSION['username'] = $bioUser['username'];
        $_SESSION['theme'] = $bioUser['theme'] ? $bioUser['theme'] : '#0ea5e9';
        echo json_encode(['success' => true, 'redirect' => 'account/dashboard.php']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Biometric credential not recognized.']);
    }
    exit;
}

// Handle Profile Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    // Update Profile Info
    if ($_POST['action'] === 'update_profile') {
        $fullName = mysqli_real_escape_string($conn, trim($_POST['full_name'] ?? ''));
        $email = mysqli_real_escape_string($conn, trim($_POST['email'] ?? ''));
        $phone = mysqli_real_escape_string($conn, trim($_POST['phone'] ?? ''));
        $country = mysqli_real_escape_string($conn, trim($_POST['country'] ?? ''));
        $theme = mysqli_real_escape_string($conn, trim($_POST['theme'] ?? '#0ea5e9'));
        
        $updateSql = "UPDATE users SET full_name = '$fullName', email = '$email', phone = '$phone', country = '$country', theme = '$theme' WHERE id = $userId";
        
        if (mysqli_query($conn, $updateSql)) {
            $_SESSION['theme'] = $theme;
            $success = 'Profile updated successfully!';
            $dbTheme = $theme;
            $result = mysqli_query($conn, "SELECT * FROM users WHERE id = $userId LIMIT 1");
            $currentUser = mysqli_fetch_assoc($result);
        } else {
            $error = 'Failed to update profile. Please try again.';
        }
    }
    
    // Change Password
    if ($_POST['action'] === 'change_password') {
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        
        $storedPass = $currentUser['password'];
        $currentPassInt = (int)$currentPassword;
        
        if ((string)$storedPass !== (string)$currentPassInt && (string)$storedPass !== $currentPassword) {
            $error = 'Current password is incorrect.';
        } elseif (strlen($newPassword) < 6) {
            $error = 'New password must be at least 6 characters.';
        } elseif ($newPassword !== $confirmPassword) {
            $error = 'New passwords do not match.';
        } else {
            $newPassInt = (int)$newPassword;
            $updatePassSql = "UPDATE users SET password = $newPassInt WHERE id = $userId";
            
            if (mysqli_query($conn, $updatePassSql)) {
                $success = 'Password changed successfully!';
            } else {
                $error = 'Failed to change password.';
            }
        }
    }

    // Reset Withdrawal PIN - MUST VERIFY PASSWORD FIRST
    if ($_POST['action'] === 'reset_pin') {
        $password = $_POST['account_password'] ?? '';
        $newPin = $_POST['new_pin'] ?? '';
        $confirmPin = $_POST['confirm_pin'] ?? '';
        
        $storedPass = $currentUser['password'];
        $currentPassInt = (int)$password;

        // STRICT PASSWORD VERIFICATION BEFORE ALLOWING PIN RESET
        if ((string)$storedPass !== (string)$currentPassInt && (string)$storedPass !== $password) {
            $error = 'Security Check Failed: Incorrect Account Password.';
        } elseif (!preg_match('/^\d{4,6}$/', $newPin)) {
            $error = 'PIN must be exactly 4 to 6 digits.';
        } elseif ($newPin !== $confirmPin) {
            $error = 'The new PINs do not match.';
        } else {
            $updatePinSql = "UPDATE users SET transaction_pin = '$newPin' WHERE id = $userId";
            if (mysqli_query($conn, $updatePinSql)) {
                $success = 'Withdrawal PIN reset successfully!';
            } else {
                $error = 'Failed to reset PIN.';
            }
        }
    }

    // Toggle Biometrics
    if ($_POST['action'] === 'enable_biometrics') {
        if (mysqli_query($conn, "UPDATE users SET biometric_enabled = 1 WHERE id = $userId")) {
            $success = 'Fingerprint / Face ID registered successfully!';
            $biometricEnabled = true;
        } else {
            $error = 'Database error registering biometrics.';
        }
    }
    if ($_POST['action'] === 'disable_biometrics') {
        mysqli_query($conn, "UPDATE users SET biometric_enabled = 0, biometric_id = NULL, biometric_credential = NULL WHERE id = $userId");
        $success = 'Biometric login disabled.';
        $biometricEnabled = false;
    }
    
    // Upload Profile Photo
    if ($_POST['action'] === 'upload_photo') {
        if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['profile_photo'];
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            $maxSize = 2 * 1024 * 1024;
            
            if (!in_array($file['type'], $allowedTypes)) {
                $error = 'Only JPG, PNG, GIF, and WebP images are allowed.';
            } elseif ($file['size'] > $maxSize) {
                $error = 'Image must be less than 2MB.';
            } else {
                $uploadDir = 'uploads/profile_photos/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                $fileExt = pathinfo($file['name'], PATHINFO_EXTENSION);
                $fileName = 'user_' . $userId . '_' . time() . '.' . $fileExt;
                $filePath = $uploadDir . $fileName;
                
                if (move_uploaded_file($file['tmp_name'], $filePath)) {
                    if (!empty($currentUser['profile_photo']) && file_exists($currentUser['profile_photo'])) {
                        unlink($currentUser['profile_photo']);
                    }
                    
                    $photoPath = mysqli_real_escape_string($conn, $filePath);
                    $updatePhotoSql = "UPDATE users SET profile_photo = '$photoPath' WHERE id = $userId";
                    
                    if (mysqli_query($conn, $updatePhotoSql)) {
                        $success = 'Profile photo updated!';
                        $result = mysqli_query($conn, "SELECT * FROM users WHERE id = $userId LIMIT 1");
                        $currentUser = mysqli_fetch_assoc($result);
                    } else {
                        $error = 'Failed to save photo reference.';
                    }
                } else {
                    $error = 'Failed to upload photo.';
                }
            }
        } else {
            $error = 'Please select a photo to upload.';
        }
    }
}

// Get initials for avatar
$initials = strtoupper(substr($currentUser['full_name'] ?? $currentUser['username'] ?? 'U', 0, 1));
if (!empty($currentUser['full_name'])) {
    $nameParts = explode(' ', $currentUser['full_name']);
    $initials = strtoupper(substr($nameParts[0], 0, 1) . (isset($nameParts[1]) ? substr($nameParts[1], 0, 1) : ''));
}

// Theme color options
$themeColors = [
    '#0ea5e9' => 'Sky Blue',
    '#8b5cf6' => 'Violet',
    '#ec4899' => 'Pink',
    '#f59e0b' => 'Amber',
    '#10b981' => 'Emerald',
    '#f43f5e' => 'Rose',
    '#6366f1' => 'Indigo',
    '#14b8a6' => 'Teal',
];
?>

<?php include "include/header.php"?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    :root {
        --primary-theme: <?php echo htmlspecialchars($dbTheme, ENT_QUOTES, 'UTF-8'); ?>;
        --primary-rgb: <?php 
            $hex = ltrim($dbTheme, '#');
            $r = hexdec(substr($hex, 0, 2));
            $g = hexdec(substr($hex, 2, 2));
            $b = hexdec(substr($hex, 4, 2));
            echo "$r, $g, $b";
        ?>;
    }
    
    .text-theme { color: var(--primary-theme) !important; }
    .bg-theme { background-color: var(--primary-theme) !important; }
    .border-theme { border-color: var(--primary-theme) !important; }
    .bg-theme-gradient { 
        background: linear-gradient(135deg, var(--primary-theme) 0%, #1e1b4b 100%) !important; 
    }
    .shadow-theme {
        box-shadow: 0 4px 20px -2px rgba(var(--primary-rgb), 0.25),
                    0 2px 8px -2px rgba(var(--primary-rgb), 0.15);
    }
    
    .glass-card {
        background: rgba(30, 41, 59, 0.6);
        backdrop-filter: blur(12px);
        border: 1px solid rgba(255, 255, 255, 0.08);
    }
    .glass-card-light {
        background: rgb(0 0 0 / 80%);
        backdrop-filter: blur(12px);
        border: 1px solid rgba(0, 0, 0, 0.06);
    }
    
    .gradient-border {
        position: relative;
        background: linear-gradient(135deg, rgba(var(--primary-rgb), 0.1), rgba(30, 27, 75, 0.2));
        border-radius: 1rem;
    }
    .gradient-border::before {
        content: '';
        position: absolute;
        inset: 0;
        border-radius: 1rem;
        padding: 1.5px;
        background: linear-gradient(135deg, var(--primary-theme), rgba(var(--primary-rgb), 0.3), transparent);
        -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
        mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
        -webkit-mask-composite: xor;
        mask-composite: exclude;
        pointer-events: none;
    }
    
    ::-webkit-scrollbar { width: 6px; height: 6px; }
    ::-webkit-scrollbar-track { background: transparent; }
    ::-webkit-scrollbar-thumb { background: rgba(var(--primary-rgb), 0.3); border-radius: 99px; }
    ::-webkit-scrollbar-thumb:hover { background: rgba(var(--primary-rgb), 0.5); }
    
    .neon-accent {
        box-shadow: 0 0 15px rgba(var(--primary-rgb), 0.2),
                    inset 0 1px 0 rgba(255,255,255,0.1);
    }
    
    .tab-btn {
        transition: all 0.3s ease;
        position: relative;
    }
    .tab-btn.active {
        color: var(--primary-theme);
        border-bottom: 2px solid var(--primary-theme);
    }
    .tab-btn:not(.active):hover {
        color: var(--primary-theme);
    }
    
    .theme-option {
        transition: all 0.2s ease;
        cursor: pointer;
    }
    .theme-option:hover {
        transform: scale(1.1);
    }
    .theme-option.selected {
        ring: 2px;
        ring-offset: 2px;
        ring-color: var(--primary-theme);
        transform: scale(1.15);
    }
    
    .photo-upload-area {
        transition: all 0.3s ease;
    }
    .photo-upload-area:hover {
        border-color: var(--primary-theme);
        background: rgba(var(--primary-rgb), 0.05);
    }
    
    .input-field {
        transition: all 0.2s ease;
    }
    .input-field:focus {
        border-color: var(--primary-theme);
        box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.1);
    }
    
    .btn-primary {
        background: var(--primary-theme);
        transition: all 0.3s ease;
    }
    .btn-primary:hover {
        filter: brightness(1.1);
        transform: translateY(-1px);
    }
    
    .alert-success {
        background: linear-gradient(135deg, rgba(16, 185, 129, 0.15), rgba(16, 185, 129, 0.05));
        border: 1px solid rgba(16, 185, 129, 0.3);
        color: #10b981;
    }
    .alert-error {
        background: linear-gradient(135deg, rgba(244, 63, 94, 0.15), rgba(244, 63, 94, 0.05));
        border: 1px solid rgba(244, 63, 94, 0.3);
        color: #f43f5e;
    }

    /* PIN Input Styling */
    .pin-input {
        letter-spacing: 0.5em;
        text-align: center;
        font-weight: bold;
        font-size: 1.2rem;
    }
    
    /* Biometric Status Badge */
    .bio-status {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 4px 12px;
        border-radius: 9999px;
        font-size: 0.75rem;
        font-weight: 600;
    }
    .bio-status.active {
        background: rgba(16, 185, 129, 0.15);
        color: #10b981;
        border: 1px solid rgba(16, 185, 129, 0.3);
    }
    .bio-status.inactive {
        background: rgba(107, 114, 128, 0.15);
        color: #6b7280;
        border: 1px solid rgba(107, 114, 128, 0.3);
    }
</style>

<?php include "include/nav.php"?>

<div class="flex min-h-screen bg-slate-50 dark:bg-[#0b111a] transition-colors duration-300">
  
  <?php include "include/sidebar.php"?>
  
  <main class="flex-1 min-w-0 md:ml-72 pb-24 md:pb-8">
    <div class="max-w-screen-2xl mx-auto px-4 sm:px-6 py-6">

      <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
        <div>
          <h1 class="text-2xl sm:text-3xl font-bold text-slate-900 dark:text-white tracking-tight">
            Profile <span class="text-theme">Settings</span>
          </h1>
          <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Manage your account preferences and security</p>
        </div>
      </div>

      <?php if ($success): ?>
      <div class="mb-6 p-4 rounded-xl alert-success flex items-center gap-3">
        <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></svg>
        <span class="text-sm font-medium"><?= htmlspecialchars($success) ?></span>
      </div>
      <?php endif; ?>
      
      <?php if ($error): ?>
      <div class="mb-6 p-4 rounded-xl alert-error flex items-center gap-3">
        <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M15 9l-6 6M9 9l6 6"/></svg>
        <span class="text-sm font-medium"><?= htmlspecialchars($error) ?></span>
      </div>
      <?php endif; ?>

      <div class="gradient-border overflow-hidden mb-6">
        <div class="bg-theme-gradient p-8 text-center relative">
          <div class="absolute inset-0 bg-[url('data:image/svg+xml,%3Csvg width=\'60\' height=\'60\' viewBox=\'0 0 60 60\' xmlns=\'http://www.w3.org/2000/svg\'%3E%3Cg fill=\'none\' fill-rule=\'evenodd\'%3E%3Cg fill=\'%23ffffff\' fill-opacity=\'0.03\'%3E%3Cpath d=\'M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z\'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E')] opacity-50"></div>
          <div class="relative">
            
            <div class="relative inline-block mb-4">
              <?php if (!empty($currentUser['profile_photo']) && file_exists($currentUser['profile_photo'])): ?>
              <img src="<?= htmlspecialchars($currentUser['profile_photo']) ?>" alt="Profile" class="w-24 h-24 rounded-full object-cover border-4 border-white/20 shadow-2xl">
              <?php else: ?>
              <div class="w-24 h-24 rounded-full bg-white/20 flex items-center justify-center text-white text-3xl font-bold shadow-2xl border-4 border-white/20 backdrop-blur-sm">
                <?= $initials ?>
              </div>
              <?php endif; ?>
              <button onclick="document.getElementById('photo-upload-modal').classList.remove('hidden')" class="absolute bottom-0 right-0 w-8 h-8 bg-white dark:bg-slate-800 rounded-full flex items-center justify-center shadow-lg hover:scale-110 transition-transform border border-slate-200 dark:border-slate-700">
                <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-slate-600 dark:text-slate-300"><path d="M12 5v14M5 12h14"/></svg>
              </button>
            </div>
            
            <h2 class="text-xl font-bold text-white"><?= htmlspecialchars($currentUser['full_name'] ?? $currentUser['username'] ?? 'User') ?></h2>
            <p class="text-white/70 text-sm mt-1"><?= htmlspecialchars($currentUser['email'] ?? '') ?></p>
            <div class="flex items-center justify-center gap-4 mt-3 flex-wrap">
              <span class="px-3 py-1 bg-white/10 text-white text-xs font-medium rounded-full border border-white/20">Verified Account</span>
              <span class="px-3 py-1 bg-white/10 text-white text-xs font-medium rounded-full border border-white/20">Member since <?= date('M Y', strtotime($currentUser['created_at'] ?? 'now')) ?></span>
              <?php if($biometricEnabled): ?>
              <span class="px-3 py-1 bg-emerald-500/20 text-emerald-300 text-xs font-medium rounded-full border border-emerald-500/30 flex items-center gap-1">
                <svg width="10" height="10" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>
                Biometrics Active
              </span>
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>

      <div class="glass-card-light dark:glass-card rounded-2xl border border-slate-200 dark:border-slate-700/50 overflow-hidden transition-colors">
        
        <div class="flex border-b border-slate-200 dark:border-slate-700/50 overflow-x-auto">
          <button onclick="switchTab('profile')" id="tab-profile" class="tab-btn active px-6 py-4 text-sm font-bold text-slate-600 dark:text-slate-300 whitespace-nowrap">
            <div class="flex items-center gap-2">
              <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
              Profile Info
            </div>
          </button>
          <button onclick="switchTab('security')" id="tab-security" class="tab-btn px-6 py-4 text-sm font-bold text-slate-600 dark:text-slate-300 whitespace-nowrap">
            <div class="flex items-center gap-2">
              <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
              Security
            </div>
          </button>
          <!--
          <button onclick="switchTab('appearance')" id="tab-appearance" class="tab-btn px-6 py-4 text-sm font-bold text-slate-600 dark:text-slate-300 whitespace-nowrap">
            <div class="flex items-center gap-2">
              <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>
              Appearance
            </div>
          </button>
          -->
        </div>

        <!-- PROFILE TAB -->
        <div id="content-profile" class="p-6 space-y-6">
          <form method="POST" action="" class="space-y-6">
            <input type="hidden" name="action" value="update_profile">
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Full Name</label>
                <input type="text" name="full_name" value="<?= htmlspecialchars($currentUser['full_name'] ?? '') ?>" 
                       class="input-field w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white text-sm rounded-xl px-4 py-3 outline-none">
              </div>
              
              <div>
                <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Username</label>
                <input type="text" value="<?= htmlspecialchars($currentUser['username'] ?? '') ?>" readonly
                       class="w-full bg-slate-100 dark:bg-slate-900 border border-slate-200 dark:border-slate-700 text-slate-500 dark:text-slate-500 text-sm rounded-xl px-4 py-3 outline-none cursor-not-allowed">
                <p class="text-[10px] text-slate-400 mt-1">Username cannot be changed</p>
              </div>
              
              <div>
                <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Email Address</label>
                <input type="email" name="email" value="<?= htmlspecialchars($currentUser['email'] ?? '') ?>" 
                       class="input-field w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white text-sm rounded-xl px-4 py-3 outline-none cursor-not-allowed">
              </div>
              
              <div>
                <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Phone Number</label>
                <input type="tel" name="phone" value="<?= htmlspecialchars($currentUser['phone'] ?? '') ?>" 
                       class="input-field w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white text-sm rounded-xl px-4 py-3 outline-none">
              </div>
              
              <div class="md:col-span-2">
                <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Country</label>
                <select name="country" class="input-field w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white text-sm rounded-xl px-4 py-3 outline-none appearance-none cursor-pointer">
                  <option value="">Select Country</option>
                  <option value="United States" <?= ($currentUser['country'] ?? '') === 'United States' ? 'selected' : '' ?>>United States</option>
                  <option value="United Kingdom" <?= ($currentUser['country'] ?? '') === 'United Kingdom' ? 'selected' : '' ?>>United Kingdom</option>
                  <option value="Canada" <?= ($currentUser['country'] ?? '') === 'Canada' ? 'selected' : '' ?>>Canada</option>
                  <option value="Australia" <?= ($currentUser['country'] ?? '') === 'Australia' ? 'selected' : '' ?>>Australia</option>
                  <option value="Germany" <?= ($currentUser['country'] ?? '') === 'Germany' ? 'selected' : '' ?>>Germany</option>
                  <option value="France" <?= ($currentUser['country'] ?? '') === 'France' ? 'selected' : '' ?>>France</option>
                  <option value="Japan" <?= ($currentUser['country'] ?? '') === 'Japan' ? 'selected' : '' ?>>Japan</option>
                  <option value="Nigeria" <?= ($currentUser['country'] ?? '') === 'Nigeria' ? 'selected' : '' ?>>Nigeria</option>
                  <option value="South Africa" <?= ($currentUser['country'] ?? '') === 'South Africa' ? 'selected' : '' ?>>South Africa</option>
                  <option value="Brazil" <?= ($currentUser['country'] ?? '') === 'Brazil' ? 'selected' : '' ?>>Brazil</option>
                  <option value="India" <?= ($currentUser['country'] ?? '') === 'India' ? 'selected' : '' ?>>India</option>
                  <option value="China" <?= ($currentUser['country'] ?? '') === 'China' ? 'selected' : '' ?>>China</option>
                  <option value="Other" <?= ($currentUser['country'] ?? '') === 'Other' ? 'selected' : '' ?>>Other</option>
                </select>
              </div>
            </div>
            
            <div class="flex justify-end pt-4 border-t border-slate-200 dark:border-slate-700/50">
              <button type="submit" class="btn-primary px-6 py-3 text-white text-sm font-bold rounded-xl shadow-theme flex items-center gap-2">
                <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></svg>
                Save Changes
              </button>
            </div>
          </form>
        </div>

        <!-- SECURITY TAB -->
        <div id="content-security" class="p-6 space-y-6 hidden">
          <div class="bg-amber-500/5 border border-amber-500/20 rounded-xl p-4 mb-6">
            <div class="flex items-start gap-3">
              <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-amber-500 shrink-0 mt-0.5"><path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
              <div>
                <p class="text-sm font-medium text-amber-700 dark:text-amber-400">Security Notice</p>
                <p class="text-xs text-amber-600 dark:text-amber-500 mt-1">Choose a strong password with at least 6 characters. Avoid using common words or personal information.</p>
              </div>
            </div>
          </div>
          
          <!-- Change Password -->
          <form method="POST" action="" class="space-y-6 border-b border-slate-200 dark:border-slate-700/50 pb-6">
            <input type="hidden" name="action" value="change_password">
            
            <h3 class="text-sm font-bold text-slate-800 dark:text-white uppercase mb-2 tracking-wider flex items-center gap-2">
                <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-theme"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
                Change Password
            </h3>
            
            <div class="space-y-4 max-w-md">
              <div>
                <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Current Password</label>
                <div class="relative">
                  <input type="password" name="current_password" required
                         class="input-field w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white text-sm rounded-xl px-4 py-3 outline-none pr-10">
                  <button type="button" onclick="togglePassword(this)" class="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600">
                    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                  </button>
                </div>
              </div>
              
              <div>
                <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">New Password</label>
                <div class="relative">
                  <input type="password" name="new_password" required minlength="6"
                         class="input-field w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white text-sm rounded-xl px-4 py-3 outline-none pr-10">
                  <button type="button" onclick="togglePassword(this)" class="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600">
                    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                  </button>
                </div>
              </div>
              
              <div>
                <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Confirm New Password</label>
                <div class="relative">
                  <input type="password" name="confirm_password" required minlength="6"
                         class="input-field w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white text-sm rounded-xl px-4 py-3 outline-none pr-10">
                  <button type="button" onclick="togglePassword(this)" class="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600">
                    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                  </button>
                </div>
              </div>
            </div>
            
            <div class="flex justify-end pt-4">
              <button type="submit" class="btn-primary px-6 py-3 text-white text-sm font-bold rounded-xl shadow-theme flex items-center gap-2">
                <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
                Change Password
              </button>
            </div>
          </form>

          <!-- Reset Withdrawal PIN - PASSWORD VERIFICATION REQUIRED -->
          <form method="POST" action="" class="space-y-6 border-b border-slate-200 dark:border-slate-700/50 pb-6">
            <input type="hidden" name="action" value="reset_pin">
            
            <div class="flex items-center justify-between mb-2">
                <h3 class="text-sm font-bold text-slate-800 dark:text-white uppercase tracking-wider flex items-center gap-2">
                    <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-theme"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>
                    Reset Withdrawal PIN
                </h3>
                <span class="bio-status <?= !empty($currentUser['transaction_pin']) && $currentUser['transaction_pin'] !== '0000' ? 'active' : 'inactive' ?>">
                    <?= !empty($currentUser['transaction_pin']) && $currentUser['transaction_pin'] !== '0000' ? 'PIN Set' : 'Default PIN' ?>
                </span>
            </div>
            
            <div class="bg-red-500/5 border border-red-500/20 rounded-lg p-3 mb-4">
                <p class="text-xs text-red-600 dark:text-red-400 flex items-center gap-2">
                    <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
                    For security, you must verify your account password before resetting your PIN.
                </p>
            </div>
            
            <div class="space-y-4 max-w-md">
              <!-- ACCOUNT PASSWORD VERIFICATION (REQUIRED) -->
              <div>
                <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">
                    Account Password <span class="text-red-500">*</span>
                </label>
                <div class="relative">
                  <input type="password" name="account_password" required placeholder="Enter your current password"
                         class="input-field w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white text-sm rounded-xl px-4 py-3 outline-none pr-10">
                  <button type="button" onclick="togglePassword(this)" class="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600">
                    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                  </button>
                </div>
                <p class="text-[10px] text-slate-400 mt-1">This is your login password, not the PIN</p>
              </div>
              
              <div class="grid grid-cols-2 gap-4">
                <div>
                  <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">New PIN (4-6 digits)</label>
                  <input type="password" name="new_pin" required minlength="4" maxlength="6" pattern="\d{4,6}" placeholder="••••"
                         class="pin-input input-field w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-theme rounded-xl px-4 py-3 outline-none">
                </div>
                <div>
                  <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Confirm PIN</label>
                  <input type="password" name="confirm_pin" required minlength="4" maxlength="6" pattern="\d{4,6}" placeholder="••••"
                         class="pin-input input-field w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-theme rounded-xl px-4 py-3 outline-none">
                </div>
              </div>
            </div>
            
            <div class="flex justify-end pt-4">
              <button type="submit" class="bg-slate-900 dark:bg-white text-white dark:text-slate-900 px-6 py-3 text-sm font-bold rounded-xl shadow-xl hover:-translate-y-1 transition-all flex items-center gap-2">
                <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
                Reset PIN
              </button>
            </div>
          </form>

          <!-- Fingerprint & Face ID Section -->
          <div class="pt-2">
            <div class="flex flex-col md:flex-row md:items-center justify-between gap-6 bg-slate-50 dark:bg-slate-800/50 p-6 rounded-2xl border border-slate-200 dark:border-slate-700/50">
              <div class="flex-1">
                <div class="flex items-center gap-3 mb-2">
                    <h3 class="text-sm font-bold text-slate-800 dark:text-white uppercase tracking-wider flex items-center gap-2">
                        <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-emerald-500"><path d="M12 2a10 10 0 0 0-10 10v2a2 2 0 0 0 2 2h0a2 2 0 0 0 2-2v-2a6 6 0 0 1 12 0v2a2 2 0 0 0 2 2h0a2 2 0 0 0 2-2v-2a10 10 0 0 0-10-10z"/><path d="M12 6a6 6 0 0 0-6 6v2a2 2 0 0 0 2 2h0a2 2 0 0 0 2-2v-2a2 2 0 0 1 4 0v2a2 2 0 0 0 2 2h0a2 2 0 0 0 2-2v-2a6 6 0 0 0-6-6z"/></svg>
                        Fingerprint & Face ID
                    </h3>
                    <?php if($biometricEnabled): ?>
                    <span class="bio-status active">
                        <span class="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span>
                        Active
                    </span>
                    <?php else: ?>
                    <span class="bio-status inactive">Not Set Up</span>
                    <?php endif; ?>
                </div>
                <p class="text-xs font-medium text-slate-500 dark:text-slate-400 leading-relaxed">
                    <?php if($biometricEnabled): ?>
                        Your device biometric sensor is linked. You can log in instantly using Face ID or Fingerprint from the login page.
                    <?php else: ?>
                        Link your device's biometric sensor (Touch ID, Face ID, Windows Hello) to log in instantly without typing your password.
                    <?php endif; ?>
                </p>
                <?php if($biometricEnabled && !empty($currentUser['biometric_id'])): ?>
                <p class="text-[10px] text-slate-400 mt-2 font-mono">Credential ID: <?= substr($currentUser['biometric_id'], 0, 20) ?>...</p>
                <?php endif; ?>
              </div>
              
              <?php if($biometricEnabled): ?>
                  <form method="POST" action="">
                      <input type="hidden" name="action" value="disable_biometrics">
                      <button type="submit" class="px-5 py-2.5 bg-rose-500/10 text-rose-500 border border-rose-500/20 font-bold uppercase tracking-wider rounded-xl text-xs hover:bg-rose-500 hover:text-white transition-all whitespace-nowrap flex items-center gap-2">
                          <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                          Remove Biometrics
                      </button>
                  </form>
              <?php else: ?>
                  <button type="button" onclick="registerBiometrics()" class="px-5 py-2.5 bg-emerald-500 text-white font-bold uppercase tracking-wider rounded-xl text-xs shadow-lg shadow-emerald-500/30 hover:brightness-110 transition-all whitespace-nowrap flex items-center gap-2">
                      <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M12 2a10 10 0 0 0-10 10v2a2 2 0 0 0 2 2h0a2 2 0 0 0 2-2v-2a6 6 0 0 1 12 0v2a2 2 0 0 0 2 2h0a2 2 0 0 0 2-2v-2a10 10 0 0 0-10-10z"/></svg>
                      Setup Biometrics
                  </button>
              <?php endif; ?>
            </div>
          </div>
        </div>

        <!-- APPEARANCE TAB -->
        <div id="content-appearance" class="p-6 space-y-6 hidden">
          <form method="POST" action="" class="space-y-6">
            <input type="hidden" name="action" value="update_profile">
            
            <div>
              <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-4 tracking-wider">Theme Color</label>
              <div class="flex flex-wrap gap-4">
                <?php foreach ($themeColors as $color => $name): ?>
                <label class="flex flex-col items-center gap-2 cursor-pointer">
                  <input type="radio" name="theme" value="<?= $color ?>" <?= ($currentUser['theme'] ?? '#0ea5e9') === $color ? 'checked' : '' ?> class="sr-only">
                  <div class="theme-option w-12 h-12 rounded-full shadow-lg flex items-center justify-center" 
                       style="background-color: <?= $color ?>; <?= ($currentUser['theme'] ?? '#0ea5e9') === $color ? 'box-shadow: 0 0 0 3px white, 0 0 0 5px ' . $color . '; transform: scale(1.1);' : '' ?>"
                       onclick="selectTheme(this, '<?= $color ?>')">
                    <?php if (($currentUser['theme'] ?? '#0ea5e9') === $color): ?>
                    <svg width="16" height="16" fill="none" stroke="white" stroke-width="3" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></svg>
                    <?php endif; ?>
                  </div>
                  <span class="text-[10px] font-medium text-slate-500 dark:text-slate-400"><?= $name ?></span>
                </label>
                <?php endforeach; ?>
              </div>
            </div>
            
            <div class="flex justify-end pt-4 border-t border-slate-200 dark:border-slate-700/50">
              <button type="submit" class="btn-primary px-6 py-3 text-white text-sm font-bold rounded-xl shadow-theme flex items-center gap-2">
                <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></svg>
                Save Theme
              </button>
            </div>
          </form>
        </div>

      </div>

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

<!-- Photo Upload Modal -->
<div id="photo-upload-modal" class="fixed inset-0 z-50 hidden">
  <div class="absolute inset-0 bg-black/60 backdrop-blur-sm" onclick="document.getElementById('photo-upload-modal').classList.add('hidden')"></div>
  <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-md px-4">
    <div class="bg-white dark:bg-slate-900 rounded-2xl shadow-2xl border border-slate-200 dark:border-slate-700 p-6">
      <div class="flex justify-between items-center mb-6">
        <h3 class="text-lg font-bold text-slate-900 dark:text-white">Update Profile Photo</h3>
        <button onclick="document.getElementById('photo-upload-modal').classList.add('hidden')" class="text-slate-400 hover:text-slate-600">
          <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M18 6L6 18M6 6l12 12"/></svg>
        </button>
      </div>
      
      <form method="POST" action="" enctype="multipart/form-data">
        <input type="hidden" name="action" value="upload_photo">
        
        <div class="photo-upload-area border-2 border-dashed border-slate-300 dark:border-slate-700 rounded-xl p-8 text-center cursor-pointer" 
             onclick="document.getElementById('profile_photo').click()"
             ondragover="event.preventDefault(); this.classList.add('border-theme', 'bg-theme/5');"
             ondragleave="this.classList.remove('border-theme', 'bg-theme/5');"
             ondrop="event.preventDefault(); document.getElementById('profile_photo').files = event.dataTransfer.files; previewPhoto(event.dataTransfer.files[0]);">
          
          <div id="upload-placeholder">
            <div class="w-16 h-16 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center mx-auto mb-3">
              <svg width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-slate-400"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
            </div>
            <p class="text-sm font-medium text-slate-700 dark:text-slate-300">Click or drag photo here</p>
            <p class="text-xs text-slate-400 mt-1">JPG, PNG, GIF, WebP up to 2MB</p>
          </div>
          
          <img id="photo-preview" class="hidden w-32 h-32 rounded-full object-cover mx-auto border-4 border-slate-200 dark:border-slate-700" />
          
          <input type="file" id="profile_photo" name="profile_photo" accept="image/jpeg,image/png,image/gif,image/webp" class="hidden" onchange="previewPhoto(this.files[0])">
        </div>
        
        <div class="flex gap-3 mt-6">
          <button type="button" onclick="document.getElementById('photo-upload-modal').classList.add('hidden')" class="flex-1 py-3 text-sm font-bold text-slate-600 dark:text-slate-300 bg-slate-100 dark:bg-slate-800 rounded-xl hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors">
            Cancel
          </button>
          <button type="submit" class="flex-1 py-3 text-sm font-bold text-white bg-theme rounded-xl hover:brightness-110 transition-all shadow-theme">
            Upload Photo
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php include "include/footer.php"?>

<div id="toast" class="fixed top-20 right-4 z-50 transform translate-x-full transition-transform duration-300">
    <div class="bg-slate-900 dark:bg-white text-white dark:text-slate-900 px-4 py-3 rounded-xl shadow-2xl flex items-center gap-2 text-sm font-medium">
        <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-emerald-500"><path d="M20 6L9 17l-5-5"/></svg>
        <span id="toast-message">Success</span>
    </div>
</div>

<script>
function showToast(message) {
    const toast = document.getElementById('toast');
    document.getElementById('toast-message').textContent = message;
    toast.classList.remove('translate-x-full');
    setTimeout(() => toast.classList.add('translate-x-full'), 3000);
}

function switchTab(tabName) {
    document.querySelectorAll('[id^="content-"]').forEach(el => el.classList.add('hidden'));
    document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
    
    document.getElementById('content-' + tabName).classList.remove('hidden');
    document.getElementById('tab-' + tabName).classList.add('active');
}

function togglePassword(btn) {
    const input = btn.parentElement.querySelector('input');
    if (input.type === 'password') {
        input.type = 'text';
        btn.innerHTML = '<svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>';
    } else {
        input.type = 'password';
        btn.innerHTML = '<svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>';
    }
}

function selectTheme(el, color) {
    document.querySelectorAll('.theme-option').forEach(opt => {
        opt.style.boxShadow = '';
        opt.style.transform = '';
        opt.innerHTML = '';
    });
    el.style.boxShadow = '0 0 0 3px white, 0 0 0 5px ' + color;
    el.style.transform = 'scale(1.1)';
    el.innerHTML = '<svg width="16" height="16" fill="none" stroke="white" stroke-width="3" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></svg>';
    
    document.querySelector('input[name="theme"][value="' + color + '"]').checked = true;
}

function previewPhoto(file) {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = function(e) {
        document.getElementById('upload-placeholder').classList.add('hidden');
        const preview = document.getElementById('photo-preview');
        preview.src = e.target.result;
        preview.classList.remove('hidden');
    };
    reader.readAsDataURL(file);
}

// ============================================
// WEBAUTHN BIOMETRIC REGISTRATION (Fingerprint / Face ID)
// ============================================
// This is the EASIEST and BEST approach for PHP:
// 1. Uses native browser WebAuthn API (no external libraries needed)
// 2. Stores credential in your existing MySQL database
// 3. Works with Touch ID, Face ID, Windows Hello, Android Biometric
// ============================================

async function registerBiometrics() {
    if (!window.PublicKeyCredential) {
        Swal.fire({
            icon: 'error',
            title: 'Not Supported',
            text: 'Your browser does not support biometric authentication. Use Chrome, Safari, Edge, or Firefox.',
            confirmButtonColor: '#f43f5e'
        });
        return;
    }

    try {
        // Check if device supports platform authenticator (built-in biometrics)
        const available = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
        if (!available) {
            Swal.fire({
                icon: 'warning',
                title: 'No Biometric Sensor',
                text: 'Your device does not have a built-in biometric sensor (Fingerprint/Face ID).',
                confirmButtonColor: '#f59e0b'
            });
            return;
        }

        Swal.fire({
            title: 'Setting Up Biometrics',
            text: 'Please follow your device prompt to scan your fingerprint or face...',
            allowOutsideClick: false,
            didOpen: () => { Swal.showLoading(); }
        });

        // Generate a random challenge
        const challenge = new Uint8Array(32);
        window.crypto.getRandomValues(challenge);

        // Create credential options
        const publicKeyCredentialCreationOptions = {
            challenge: challenge,
            rp: {
                name: "Theinteractivebrokers",
                id: window.location.hostname
            },
            user: {
                id: Uint8Array.from("<?= $userId ?>_<?= md5($currentUser['email'] ?? 'user') ?>", c => c.charCodeAt(0)),
                name: "<?= htmlspecialchars($currentUser['email'] ?? 'user@example.com') ?>",
                displayName: "<?= htmlspecialchars($currentUser['full_name'] ?? $currentUser['username'] ?? 'User') ?>"
            },
            pubKeyCredParams: [
                { alg: -7, type: "public-key" },   // ES256
                { alg: -257, type: "public-key" }  // RS256
            ],
            authenticatorSelection: {
                authenticatorAttachment: "platform", // Forces built-in sensor (not USB key)
                userVerification: "required",        // Forces biometric (not just PIN)
                residentKey: "preferred",
                requireResidentKey: false
            },
            timeout: 60000,
            attestation: "none", // "none" is simpler and sufficient for this use case
            excludeCredentials: [] // Prevent duplicate registration
        };

        const credential = await navigator.credentials.create({
            publicKey: publicKeyCredentialCreationOptions
        });

        if (credential) {
            // Convert credential data for server storage
            const credentialId = btoa(String.fromCharCode(...new Uint8Array(credential.rawId)));
            
            // Get the client data JSON for verification
            const clientDataJSON = btoa(String.fromCharCode(...new Uint8Array(credential.response.clientDataJSON)));
            const attestationObject = btoa(String.fromCharCode(...new Uint8Array(credential.response.attestationObject)));

            // Send to server via AJAX
            const formData = new FormData();
            formData.append('ajax_action', 'register_biometric');
            formData.append('credential_id', credentialId);
            formData.append('credential_data', JSON.stringify({
                id: credential.id,
                rawId: credentialId,
                type: credential.type,
                response: {
                    clientDataJSON: clientDataJSON,
                    attestationObject: attestationObject
                }
            }));

            const response = await fetch('', {
                method: 'POST',
                body: formData
            });

            const result = await response.json();

            if (result.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Biometrics Linked!',
                    text: 'You can now log in using Face ID or Fingerprint.',
                    confirmButtonColor: '#10b981',
                    timer: 2000,
                    showConfirmButton: false
                });
                setTimeout(() => location.reload(), 1500);
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Registration Failed',
                    text: result.message || 'Could not save biometric data.',
                    confirmButtonColor: '#f43f5e'
                });
            }
        }
    } catch (err) {
        console.error("Biometric Error:", err);
        let errorMsg = 'Biometric setup was cancelled or failed.';
        if (err.name === 'NotAllowedError') {
            errorMsg = 'Permission denied. Please allow biometric access in your browser settings.';
        } else if (err.name === 'SecurityError') {
            errorMsg = 'Security error. Make sure you are on a secure connection (HTTPS).';
        }
        Swal.fire({
            icon: 'error',
            title: 'Setup Cancelled',
            text: errorMsg,
            confirmButtonColor: '#f43f5e'
        });
    }
}

document.addEventListener('DOMContentLoaded', () => {
    if (typeof lucide !== 'undefined') lucide.createIcons();
});
</script>

</body>
</html>