<?php
// This is the first line of ANY secure admin page.
require_once 'includes/auth_check.php';

// Set the current page for the sidebar active state
$page = 'users';

// Include your database and functions
require_once '../config/database.php';
require_once '../includes/functions.php';

// Create a database connection
$database = new Database();
$db = $database->getConnection();

// --- Get User ID from URL ---
$user_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$user_id) {
    header('Location: manage_users.php');
    exit;
}

// --- Helper function to check if a table exists ---
function tableExists($db, $tableName) {
    try {
        $result = $db->query("SELECT 1 FROM `$tableName` LIMIT 1");
        return $result !== false;
    } catch (Exception $e) {
        return false;
    }
}

// --- Helper function to generate unique transaction reference ---
function generateUniqueReference($db, $prefix = 'TXN') {
    $unique = false;
    $reference = '';
    
    while (!$unique) {
        // Generate a reference with prefix, random string and timestamp
        $reference = $prefix . '_' . bin2hex(random_bytes(8)) . '_' . time();
        
        // Check if this reference already exists
        $stmt = $db->prepare("SELECT COUNT(*) FROM transactions WHERE reference = ?");
        $stmt->execute([$reference]);
        $count = $stmt->fetchColumn();
        
        if ($count == 0) {
            $unique = true;
        }
    }
    
    return $reference;
}

// --- Handle Form Submission (POST Request) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Debug information
    error_log('Form submitted. Processing user edit for ID: ' . $user_id);
    
    // CSRF Check
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $_SESSION['error_message'] = "Invalid security token. Please try again.";
        header("Location: edit_user.php?id=$user_id");
        exit;
    }

    // Sanitize and retrieve form data
    // Personal Information
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
    $phone = trim($_POST['phone']);
    $dob = $_POST['dob'];
    $gender = $_POST['gender'];
    $country = $_POST['country'];
    $address = trim($_POST['address']);
    $city = trim($_POST['city'] ?? '');
    $state = trim($_POST['state'] ?? '');
    $zip_code = trim($_POST['zip_code'] ?? '');
    $ssn = trim($_POST['ssn'] ?? '');
    $mothers_maiden_name = trim($_POST['mothers_maiden_name'] ?? '');
    
    // Next of kin details
    $kin_name = trim($_POST['kin_name']);
    $kin_relationship = $_POST['kin_relationship'];
    $kin_email = filter_var(trim($_POST['kin_email']), FILTER_SANITIZE_EMAIL);
    $kin_phone = trim($_POST['kin_phone']);
    $kin_address = trim($_POST['kin_address']);
    
    // Account details
    $account_type = $_POST['account_type'];
    $currency = $_POST['currency'];
    $employment_status = $_POST['employment_status'];
    $income_source = $_POST['income_source'];
    $occupation = trim($_POST['occupation'] ?? '');
    $employer = trim($_POST['employer'] ?? '');
    $status = $_POST['status'];
    
    // Account preferences
    $request_debit_card = $_POST['request_debit_card'] ?? '';
    $online_banking = $_POST['online_banking'] ?? '';
    $initial_deposit = $_POST['initial_deposit'] ?? '';
    
    // Username (don't allow changing if not provided)
    $username = trim($_POST['username']);

    // Validate data
    if (empty($first_name) || empty($last_name) || empty($email) || empty($status)) {
        $_SESSION['error_message'] = "Please fill in all required fields.";
    } else {
        try {
            // Begin transaction
            $db->beginTransaction();
            error_log('Database transaction started for user edit');
            
            // Handle profile picture upload
            $profilePicture = '';
            $targetPath = '';
            $currentPicture = $_POST['current_profile_picture'];
            
            if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] === 0) {
                $uploadDir = '../uploads/profiles/';
                if (!file_exists($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }

                $allowedTypes = ['image/jpeg', 'image/png'];
                $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
                $mimeType = finfo_file($fileInfo, $_FILES['profile_picture']['tmp_name']);
                finfo_close($fileInfo);

                if (!in_array($mimeType, $allowedTypes)) {
                    throw new Exception('Invalid file type. Only JPG and PNG files are allowed.');
                }

                if ($_FILES['profile_picture']['size'] > 5 * 1024 * 1024) {
                    throw new Exception('File size too large. Maximum size is 5MB.');
                }

                $extension = strtolower(pathinfo($_FILES['profile_picture']['name'], PATHINFO_EXTENSION));
                $fileName = uniqid() . '_' . time() . '.' . $extension;
                $targetPath = $uploadDir . $fileName;

                if (!move_uploaded_file($_FILES['profile_picture']['tmp_name'], $targetPath)) {
                    throw new Exception('Error uploading profile picture.');
                }

                $profilePicture = $fileName;
                
                // Delete old profile picture if it exists and is not the default
                if (!empty($currentPicture) && file_exists('../uploads/profiles/' . $currentPicture)) {
                    unlink('../uploads/profiles/' . $currentPicture);
                }
            } else {
                // Keep the current profile picture
                $profilePicture = $currentPicture;
            }

            // Update user record
            $query = "UPDATE users SET 
                        first_name = :first_name,
                        last_name = :last_name,
                        email = :email,
                        phone = :phone,
                        date_of_birth = :dob,
                        gender = :gender,
                        country = :country,
                        address = :address,
                        city = :city,
                        state = :state,
                        zip_code = :zip_code,
                        ssn = :ssn,
                        mothers_maiden_name = :mothers_maiden_name,
                        account_type = :account_type,
                        currency = :currency,
                        employment_status = :employment_status,
                        income_source = :income_source,
                        occupation = :occupation,
                        employer = :employer,
                        status = :status,
                        request_debit_card = :request_debit_card,
                        online_banking = :online_banking,
                        initial_deposit = :initial_deposit";
            
            // Only add profile_picture to the query if it's not empty
            if (!empty($profilePicture)) {
                $query .= ", profile_picture = :profile_picture";
            }
            
            // Only update username if it's different from the current one
            if (!empty($username)) {
                $query .= ", username = :username";
            }
            
            $query .= " WHERE id = :id";
            
            $stmt = $db->prepare($query);

            // Bind parameters
            $stmt->bindParam(':first_name', $first_name);
            $stmt->bindParam(':last_name', $last_name);
            $stmt->bindParam(':email', $email);
            $stmt->bindParam(':phone', $phone);
            $stmt->bindParam(':dob', $dob);
            $stmt->bindParam(':gender', $gender);
            $stmt->bindParam(':country', $country);
            $stmt->bindParam(':address', $address);
            $stmt->bindParam(':city', $city);
            $stmt->bindParam(':state', $state);
            $stmt->bindParam(':zip_code', $zip_code);
            $stmt->bindParam(':ssn', $ssn);
            $stmt->bindParam(':mothers_maiden_name', $mothers_maiden_name);
            $stmt->bindParam(':account_type', $account_type);
            $stmt->bindParam(':currency', $currency);
            $stmt->bindParam(':employment_status', $employment_status);
            $stmt->bindParam(':income_source', $income_source);
            $stmt->bindParam(':occupation', $occupation);
            $stmt->bindParam(':employer', $employer);
            $stmt->bindParam(':status', $status);
            $stmt->bindParam(':request_debit_card', $request_debit_card);
            $stmt->bindParam(':online_banking', $online_banking);
            $stmt->bindParam(':initial_deposit', $initial_deposit);
            
            if (!empty($profilePicture)) {
                $stmt->bindParam(':profile_picture', $profilePicture);
            }
            
            if (!empty($username)) {
                $stmt->bindParam(':username', $username);
            }
            
            $stmt->bindParam(':id', $user_id, PDO::PARAM_INT);

            // Execute the update
            $stmt->execute();
            error_log('User record updated successfully');
            
            // Update next of kin if the table exists
            if (tableExists($db, 'next_of_kin')) {
                // Check if next of kin record exists
                $check_stmt = $db->prepare("SELECT id FROM next_of_kin WHERE user_id = ?");
                $check_stmt->execute([$user_id]);
                $kin_exists = $check_stmt->fetch();
                
                if ($kin_exists) {
                    // Update existing record
                    $kin_stmt = $db->prepare("
                        UPDATE next_of_kin SET 
                            full_name = ?, 
                            relationship = ?, 
                            email = ?, 
                            phone = ?, 
                            address = ? 
                        WHERE user_id = ?
                    ");
                    $kin_stmt->execute([
                        $kin_name, 
                        $kin_relationship, 
                        $kin_email, 
                        $kin_phone, 
                        $kin_address, 
                        $user_id
                    ]);
                    error_log('Next of kin record updated');
                } else {
                    // Create new record
                    $kin_stmt = $db->prepare("
                        INSERT INTO next_of_kin (
                            user_id, full_name, relationship, email, phone, address, created_at
                        ) VALUES (?, ?, ?, ?, ?, ?, NOW())
                    ");
                    $kin_stmt->execute([
                        $user_id, 
                        $kin_name, 
                        $kin_relationship, 
                        $kin_email, 
                        $kin_phone, 
                        $kin_address
                    ]);
                    error_log('Next of kin record created');
                }
            }
            
            // Update account balances if currency has changed
            if (tableExists($db, 'account_balances')) {
                // Check if we need to update the currency in account_balances
                $check_stmt = $db->prepare("
                    SELECT ab.currency, ab.balance 
                    FROM account_balances ab 
                    JOIN users u ON ab.user_id = u.id 
                    WHERE u.id = ? AND ab.currency != ?
                ");
                $check_stmt->execute([$user_id, $currency]);
                $old_balance = $check_stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($old_balance) {
                    error_log('Currency change detected: ' . $old_balance['currency'] . ' to ' . $currency);
                    
                    // Check if a balance record with the new currency already exists
                    $check_new_stmt = $db->prepare("
                        SELECT id, balance FROM account_balances 
                        WHERE user_id = ? AND currency = ?
                    ");
                    $check_new_stmt->execute([$user_id, $currency]);
                    $new_balance = $check_new_stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($new_balance) {
                        // Update existing balance record with the new currency
                        $update_stmt = $db->prepare("
                            UPDATE account_balances 
                            SET balance = balance + ?, last_updated = NOW() 
                            WHERE id = ?
                        ");
                        $update_stmt->execute([$old_balance['balance'], $new_balance['id']]);
                        
                        // Delete the old currency record
                        $delete_stmt = $db->prepare("
                            DELETE FROM account_balances 
                            WHERE user_id = ? AND currency = ?
                        ");
                        $delete_stmt->execute([$user_id, $old_balance['currency']]);
                        error_log('Merged balances and deleted old currency record');
                    } else {
                        // Just update the currency in the existing record
                        $update_stmt = $db->prepare("
                            UPDATE account_balances 
                            SET currency = ?, last_updated = NOW() 
                            WHERE user_id = ? AND currency = ?
                        ");
                        $update_stmt->execute([$currency, $user_id, $old_balance['currency']]);
                        error_log('Updated currency in existing balance record');
                    }
                    
                    // Add a transaction record for the currency change if transactions table exists
                    if (tableExists($db, 'transactions')) {
                        try {
                            // Generate a guaranteed unique reference
                            $reference = generateUniqueReference($db, 'CURR');
                            error_log('Generated unique transaction reference: ' . $reference);
                            
                            $description = "Currency changed from {$old_balance['currency']} to {$currency}";
                            $trans_stmt = $db->prepare("
                                INSERT INTO transactions (
                                    user_id, type, amount, currency, description, reference, status, created_at
                                ) VALUES (?, 'system', ?, ?, ?, ?, 'completed', NOW())
                            ");
                            $trans_stmt->execute([
                                $user_id, 
                                $old_balance['balance'], 
                                $currency, 
                                $description,
                                $reference
                            ]);
                            error_log('Transaction record created for currency change');
                        } catch (PDOException $e) {
                            // Handle transaction insertion error specifically
                            error_log('Error creating transaction record: ' . $e->getMessage());
                            // Continue with the update process even if transaction record fails
                        }
                    }
                }
            }

            // Commit all changes
            $db->commit();
            error_log('All changes committed successfully');
            
            $_SESSION['success_message'] = "User details for " . htmlspecialchars($first_name . ' ' . $last_name) . " have been updated successfully!";
            header("Location: view_user.php?id=$user_id");
            exit;

        } catch (PDOException $e) {
            // Rollback on error
            $db->rollBack();
            
            // Delete uploaded file if exists
            if (!empty($targetPath) && file_exists($targetPath)) {
                unlink($targetPath);
            }
            
            error_log("Edit User DB Error: " . $e->getMessage());
            $_SESSION['error_message'] = "A database error occurred: " . $e->getMessage();
        } catch (Exception $e) {
            // Rollback on error
            $db->rollBack();
            
            // Delete uploaded file if exists
            if (!empty($targetPath) && file_exists($targetPath)) {
                unlink($targetPath);
            }
            
            error_log("Edit User Error: " . $e->getMessage());
            $_SESSION['error_message'] = $e->getMessage();
        }
    }
    // Redirect back to the edit page if there was an error
    header("Location: edit_user.php?id=$user_id");
    exit;
}

// --- Fetch User Data for Form (GET Request) ---
try {
    // Fetch user data
    $stmt = $db->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->execute([':id' => $user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        $_SESSION['error_message'] = "User not found.";
        header('Location: manage_users.php');
        exit;
    }
    
    // Fetch next of kin data if available
    $kin = null;
    if (tableExists($db, 'next_of_kin')) {
        $kin_stmt = $db->prepare("SELECT * FROM next_of_kin WHERE user_id = ?");
        $kin_stmt->execute([$user_id]);
        $kin = $kin_stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    // Fetch account balances
    $balances = [];
    if (tableExists($db, 'account_balances')) {
        $balance_stmt = $db->prepare("SELECT * FROM account_balances WHERE user_id = ? ORDER BY currency ASC");
        $balance_stmt->execute([$user_id]);
        $balances = $balance_stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    // Generate a CSRF token for the form
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

} catch (PDOException $e) {
    error_log("Edit User Fetch DB Error: " . $e->getMessage());
    $pageError = "Could not load user data. Please check the system logs.";
}

// Include the header for the admin page
include 'includes/header.php';
?>

<style>
:root {
    --primary-color: #4f46e5;
    --primary-light: rgba(79, 70, 229, 0.1);
    --primary-dark: #4338ca;
    --success-color: #10b981;
    --success-light: rgba(16, 185, 129, 0.1);
    --danger-color: #ef4444;
    --danger-light: rgba(239, 68, 68, 0.1);
    --warning-color: #f59e0b;
    --warning-light: rgba(245, 158, 11, 0.1);
    --info-color: #0ea5e9;
    --info-light: rgba(14, 165, 233, 0.1);
    --secondary-color: #6b7280;
    --secondary-light: rgba(107, 114, 128, 0.1);
    --border-color: #e2e8f0;
    --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    --transition-base: all 0.3s ease;
}

/* Main Container Styles */
.content-wrapper {
    padding: 2rem;
    background-color: #f9fafb;
    min-height: calc(100vh - 60px);
}

/* Page Header */
.page-header {
    margin-bottom: 2rem;
}

.page-title {
    font-size: 1.75rem;
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
}

.page-title i {
    margin-right: 0.75rem;
    font-size: 2rem;
    color: var(--primary-color);
}

.page-subtitle {
    color: #64748b;
    font-size: 1rem;
    margin-bottom: 0;
}

/* Card Styles */
.app-card {
    background: white;
    border-radius: 1rem;
    box-shadow: var(--card-shadow);
    border: none;
    overflow: hidden;
    margin-bottom: 2rem;
}

.app-card-header {
    padding: 1.5rem;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.app-card-title {
    font-size: 1.25rem;
    font-weight: 600;
    color: #1e293b;
    margin: 0;
    display: flex;
    align-items: center;
}

.app-card-title i {
    font-size: 1.5rem;
    margin-right: 0.75rem;
    color: var(--primary-color);
}

.app-card-body {
    padding: 1.5rem;
}

.app-card-footer {
    padding: 1.25rem 1.5rem;
    background-color: #f8fafc;
    border-top: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* Form Wizard Navigation */
.form-wizard-nav {
    display: flex;
    justify-content: space-between;
    position: relative;
    margin-bottom: 2.5rem;
    padding: 0 1rem;
}

.form-wizard-nav::before {
    content: '';
    position: absolute;
    top: 1.25rem;
    left: 0;
    right: 0;
    height: 2px;
    background-color: var(--border-color);
    z-index: 1;
}

.wizard-step {
    position: relative;
    z-index: 2;
    text-align: center;
    width: 25%;
}

.step-icon {
    width: 2.5rem;
    height: 2.5rem;
    border-radius: 50%;
    background-color: white;
    border: 2px solid var(--border-color);
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 0.5rem;
    font-weight: 600;
    color: var(--secondary-color);
    transition: var(--transition-base);
}

.wizard-step.active .step-icon {
    background-color: var(--primary-color);
    border-color: var(--primary-color);
    color: white;
    box-shadow: 0 0 0 4px var(--primary-light);
}

.wizard-step.completed .step-icon {
    background-color: var(--success-color);
    border-color: var(--success-color);
    color: white;
}

.step-title {
    font-size: 0.875rem;
    color: var(--secondary-color);
    margin-top: 0.5rem;
    font-weight: 500;
}

.wizard-step.active .step-title {
    color: var(--primary-color);
    font-weight: 600;
}

.wizard-step.completed .step-title {
    color: var(--success-color);
}

/* Form Controls */
.form-group {
    margin-bottom: 1.5rem;
}

.form-label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 500;
    color: #334155;
}

.form-control {
    display: block;
    width: 100%;
    padding: 0.75rem 1rem;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #1e293b;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #cbd5e1;
    border-radius: 0.5rem;
    transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.form-control:focus {
    border-color: var(--primary-color);
    outline: 0;
    box-shadow: 0 0 0 3px var(--primary-light);
}

.form-select {
    display: block;
    width: 100%;
    padding: 0.75rem 2.5rem 0.75rem 1rem;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #1e293b;
    background-color: #fff;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right 1rem center;
    background-size: 16px 12px;
    border: 1px solid #cbd5e1;
    border-radius: 0.5rem;
    appearance: none;
}

.form-select:focus {
    border-color: var(--primary-color);
    outline: 0;
    box-shadow: 0 0 0 3px var(--primary-light);
}

.form-text {
    margin-top: 0.25rem;
    font-size: 0.875rem;
    color: #64748b;
}

/* Section Headers */
.section-header {
    font-size: 1.25rem;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 1.25rem;
    padding-bottom: 0.75rem;
    border-bottom: 1px solid var(--border-color);
}

/* Profile Upload */
.profile-upload-container {
    display: flex;
    align-items: center;
    gap: 1.5rem;
    margin-bottom: 1.5rem;
}

.profile-preview {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    overflow: hidden;
    border: 3px solid var(--border-color);
    position: relative;
    background-color: #f8fafc;
}

.profile-preview img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.profile-upload-info h6 {
    font-weight: 600;
    margin-bottom: 0.5rem;
    color: #334155;
}

.profile-upload-info p {
    color: #64748b;
    margin-bottom: 0.75rem;
}

/* Alert Styles */
.app-alert {
    padding: 1rem 1.25rem;
    border-radius: 0.5rem;
    margin-bottom: 1.5rem;
    display: flex;
    align-items: flex-start;
}

.app-alert-icon {
    margin-right: 0.75rem;
    font-size: 1.25rem;
    padding-top: 0.125rem;
}

.app-alert-content {
    flex: 1;
}

.app-alert-title {
    font-weight: 600;
    margin-bottom: 0.25rem;
}

.app-alert-success {
    background-color: var(--success-light);
    border-left: 4px solid var(--success-color);
    color: #065f46;
}

.app-alert-danger {
    background-color: var(--danger-light);
    border-left: 4px solid var(--danger-color);
    color: #991b1b;
}

.app-alert-info {
    background-color: var(--info-light);
    border-left: 4px solid var(--info-color);
    color: #0c4a6e;
}

.app-alert-warning {
    background-color: var(--warning-light);
    border-left: 4px solid var(--warning-color);
    color: #92400e;
}

/* Buttons */
.btn {
    display: inline-block;
    font-weight: 500;
    line-height: 1.5;
    color: #1e293b;
    text-align: center;
    vertical-align: middle;
    cursor: pointer;
    user-select: none;
    background-color: transparent;
    border: 1px solid transparent;
    padding: 0.75rem 1.5rem;
    font-size: 1rem;
    border-radius: 0.5rem;
    transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, 
                border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.btn-primary {
    color: #fff;
    background-color: var(--primary-color);
    border-color: var(--primary-color);
}

.btn-primary:hover {
    background-color: var(--primary-dark);
    border-color: var(--primary-dark);
}

.btn-success {
    color: #fff;
    background-color: var(--success-color);
    border-color: var(--success-color);
}

.btn-success:hover {
    background-color: #0d9488;
    border-color: #0d9488;
}

.btn-outline-secondary {
    color: #64748b;
    border-color: #cbd5e1;
}

.btn-outline-secondary:hover {
    color: #1e293b;
    background-color: #f1f5f9;
    border-color: #94a3b8;
}

.btn-sm {
    padding: 0.5rem 1rem;
    font-size: 0.875rem;
    border-radius: 0.375rem;
}

/* Table Styles */
.app-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    margin-bottom: 1.5rem;
}

.app-table th {
    font-weight: 600;
    text-transform: uppercase;
    font-size: 0.75rem;
    letter-spacing: 0.5px;
    color: #64748b;
    padding: 0.75rem 1rem;
    background-color: #f8fafc;
    border-bottom: 1px solid var(--border-color);
}

.app-table td {
    padding: 0.75rem 1rem;
    vertical-align: middle;
    border-bottom: 1px solid var(--border-color);
    color: #1e293b;
}

.app-table tr:last-child td {
    border-bottom: none;
}

/* Responsive Adjustments */
@media (max-width: 768px) {
    .content-wrapper {
        padding: 1.5rem;
    }
    
        .form-wizard-nav {
        overflow-x: auto;
        padding-bottom: 1rem;
    }
    
    .profile-upload-container {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .profile-preview {
        margin-bottom: 1rem;
    }
}
</style>

<div class="content-wrapper">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="page-title">
                    <i class="bx bx-edit-alt"></i>
                    Edit User
                </h1>
                <?php if ($user): ?>
                    <p class="page-subtitle">ID: <?php echo $user['id']; ?> | <?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></p>
                <?php endif; ?>
            </div>
            <div class="d-flex">
                <a href="view_user.php?id=<?php echo $user_id; ?>" class="btn btn-outline-secondary btn-sm me-2">
                    <i class="bx bx-show me-1"></i> View User
                </a>
                <a href="manage_users.php" class="btn btn-outline-secondary btn-sm">
                    <i class="bx bx-arrow-back me-1"></i> Back to Users
                </a>
            </div>
        </div>

        <?php if (isset($pageError)): ?>
            <div class="app-alert app-alert-danger">
                <div class="app-alert-icon">
                    <i class="bx bx-error-circle"></i>
                </div>
                <div class="app-alert-content">
                    <div class="app-alert-title">Error</div>
                    <div><?php echo $pageError; ?></div>
                </div>
            </div>
        <?php else: ?>
            <!-- Display Success/Error Messages from redirects -->
            <?php if (isset($_SESSION['success_message'])): ?>
                <div class="app-alert app-alert-success mb-4">
                    <div class="app-alert-icon">
                        <i class="bx bx-check-circle"></i>
                    </div>
                    <div class="app-alert-content">
                        <div class="app-alert-title">Success</div>
                        <div><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?></div>
                    </div>
                    <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>
            
            <?php if (isset($_SESSION['error_message'])): ?>
                <div class="app-alert app-alert-danger mb-4">
                    <div class="app-alert-icon">
                        <i class="bx bx-error-circle"></i>
                    </div>
                    <div class="app-alert-content">
                        <div class="app-alert-title">Error</div>
                        <div><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?></div>
                    </div>
                    <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <div class="app-card">
                <div class="app-card-body">
                    <form id="editUserForm" action="edit_user.php?id=<?php echo $user_id; ?>" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                        
                        <!-- Form Wizard Navigation -->
                        <div class="form-wizard-nav">
                            <div class="wizard-step active" data-step="1">
                                <div class="step-icon">1</div>
                                <div class="step-title">Personal</div>
                            </div>
                            <div class="wizard-step" data-step="2">
                                <div class="step-icon">2</div>
                                <div class="step-title">Profile</div>
                            </div>
                            <div class="wizard-step" data-step="3">
                                <div class="step-icon">3</div>
                                <div class="step-title">Account</div>
                            </div>
                            <div class="wizard-step" data-step="4">
                                <div class="step-icon">4</div>
                                <div class="step-title">Security</div>
                            </div>
                        </div>
                        
                        <!-- Form Content -->
                        <div class="tab-content" id="userFormContent">
                            <!-- Step 1: Personal Information -->
                            <div class="tab-pane fade show active" id="personal" role="tabpanel">
                                <h5 class="section-header">Personal Information</h5>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">First Name</label>
                                            <input type="text" class="form-control" name="first_name" value="<?php echo htmlspecialchars($user['first_name']); ?>" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Last Name</label>
                                            <input type="text" class="form-control" name="last_name" value="<?php echo htmlspecialchars($user['last_name']); ?>" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Email Address</label>
                                            <input type="email" class="form-control" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Phone Number</label>
                                            <input type="tel" class="form-control" name="phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Date of Birth</label>
                                            <input type="date" class="form-control" name="dob" value="<?php echo htmlspecialchars($user['date_of_birth'] ?? ''); ?>" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Gender</label>
                                            <select class="form-select" name="gender" required>
                                                <option value="">Select Gender</option>
                                                <option value="male" <?php if (($user['gender'] ?? '') == 'male') echo 'selected'; ?>>Male</option>
                                                <option value="female" <?php if (($user['gender'] ?? '') == 'female') echo 'selected'; ?>>Female</option>
                                                <option value="other" <?php if (($user['gender'] ?? '') == 'other') echo 'selected'; ?>>Other</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Social Security Number</label>
                                            <input type="text" class="form-control" name="ssn" value="<?php echo htmlspecialchars($user['ssn'] ?? ''); ?>">
                                            <div class="form-text">Format: XXX-XX-XXXX</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Mother's Maiden Name</label>
                                            <input type="text" class="form-control" name="mothers_maiden_name" value="<?php echo htmlspecialchars($user['mothers_maiden_name'] ?? ''); ?>">
                                            <div class="form-text">Used for security verification</div>
                                        </div>
                                    </div>
                                </div>

                                <h5 class="section-header mt-4">Address Information</h5>
                                <div class="row g-3">
                                    <div class="col-12">
                                        <div class="form-group">
                                            <label class="form-label">Street Address</label>
                                            <textarea class="form-control" name="address" rows="2" required><?php echo htmlspecialchars($user['address'] ?? ''); ?></textarea>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label class="form-label">City</label>
                                            <input type="text" class="form-control" name="city" value="<?php echo htmlspecialchars($user['city'] ?? ''); ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label class="form-label">State/Province</label>
                                            <input type="text" class="form-control" name="state" value="<?php echo htmlspecialchars($user['state'] ?? ''); ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label class="form-label">Zip/Postal Code</label>
                                            <input type="text" class="form-control" name="zip_code" value="<?php echo htmlspecialchars($user['zip_code'] ?? ''); ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Country</label>
                                            <select class="form-select" name="country" required>
                                                <option value="">Select Country</option>
                                                <option value="US" <?php if (($user['country'] ?? '') == 'US') echo 'selected'; ?>>United States</option>
                                                <option value="GB" <?php if (($user['country'] ?? '') == 'GB') echo 'selected'; ?>>United Kingdom</option>
                                                <option value="CA" <?php if (($user['country'] ?? '') == 'CA') echo 'selected'; ?>>Canada</option>
                                                <option value="AU" <?php if (($user['country'] ?? '') == 'AU') echo 'selected'; ?>>Australia</option>
                                                <option value="DE" <?php if (($user['country'] ?? '') == 'DE') echo 'selected'; ?>>Germany</option>
                                                <option value="FR" <?php if (($user['country'] ?? '') == 'FR') echo 'selected'; ?>>France</option>
                                                <!-- Add more countries as needed -->
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <div class="d-flex justify-content-end mt-4">
                                    <button type="button" class="btn btn-primary" onclick="nextStep(1)">
                                        Continue <i class='bx bx-right-arrow-alt ms-1'></i>
                                    </button>
                                </div>
                            </div>

                            <!-- Step 2: Profile & Documents -->
                            <div class="tab-pane fade" id="profile" role="tabpanel">
                                <h5 class="section-header">Profile Setup</h5>
                                
                                <!-- Profile Picture Upload -->
                                <div class="profile-upload-container">
                                    <div class="profile-preview">
                                        <img src="../<?php echo !empty($user['profile_picture']) ? 'uploads/profiles/' . htmlspecialchars($user['profile_picture']) : 'assets/images/default-avatar.png'; ?>" 
                                             id="profilePreview" alt="Profile Preview">
                                    </div>
                                    <div class="profile-upload-info">
                                        <h6>Profile Picture</h6>
                                        <p>Upload a clear photo of the user</p>
                                        <input type="file" id="profile_picture" name="profile_picture" class="form-control" accept="image/*">
                                        <input type="hidden" name="current_profile_picture" value="<?php echo htmlspecialchars($user['profile_picture'] ?? ''); ?>">
                                        <div class="form-text">Max file size: 5MB (JPG or PNG)</div>
                                    </div>
                                </div>

                                <!-- Employment Information -->
                                <h5 class="section-header mt-4">Employment Information</h5>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Employment Status</label>
                                            <select class="form-select" name="employment_status" required>
                                                <option value="">Select Status</option>
                                                <option value="employed" <?php if (($user['employment_status'] ?? '') == 'employed') echo 'selected'; ?>>Employed</option>
                                                <option value="self-employed" <?php if (($user['employment_status'] ?? '') == 'self-employed') echo 'selected'; ?>>Self-Employed</option>
                                                <option value="student" <?php if (($user['employment_status'] ?? '') == 'student') echo 'selected'; ?>>Student</option>
                                                <option value="retired" <?php if (($user['employment_status'] ?? '') == 'retired') echo 'selected'; ?>>Retired</option>
                                                <option value="unemployed" <?php if (($user['employment_status'] ?? '') == 'unemployed') echo 'selected'; ?>>Unemployed</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Source of Income</label>
                                            <select class="form-select" name="income_source" required>
                                                <option value="">Select Source</option>
                                                <option value="salary" <?php if (($user['income_source'] ?? '') == 'salary') echo 'selected'; ?>>Salary</option>
                                                <option value="business" <?php if (($user['income_source'] ?? '') == 'business') echo 'selected'; ?>>Business Income</option>
                                                <option value="investments" <?php if (($user['income_source'] ?? '') == 'investments') echo 'selected'; ?>>Investments</option>
                                                <option value="other" <?php if (($user['income_source'] ?? '') == 'other') echo 'selected'; ?>>Other</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Occupation</label>
                                            <input type="text" class="form-control" name="occupation" value="<?php echo htmlspecialchars($user['occupation'] ?? ''); ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Employer</label>
                                            <input type="text" class="form-control" name="employer" value="<?php echo htmlspecialchars($user['employer'] ?? ''); ?>">
                                        </div>
                                    </div>
                                </div>

                                <!-- Next of Kin Information -->
                                <h5 class="section-header mt-4">Next of Kin Details</h5>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Full Name</label>
                                            <input type="text" class="form-control" name="kin_name" value="<?php echo htmlspecialchars($kin['full_name'] ?? ''); ?>" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Relationship</label>
                                            <select class="form-select" name="kin_relationship" required>
                                                <option value="">Select Relationship</option>
                                                <option value="spouse" <?php if (($kin['relationship'] ?? '') == 'spouse') echo 'selected'; ?>>Spouse</option>
                                                <option value="parent" <?php if (($kin['relationship'] ?? '') == 'parent') echo 'selected'; ?>>Parent</option>
                                                <option value="child" <?php if (($kin['relationship'] ?? '') == 'child') echo 'selected'; ?>>Child</option>
                                                <option value="sibling" <?php if (($kin['relationship'] ?? '') == 'sibling') echo 'selected'; ?>>Sibling</option>
                                                <option value="other" <?php if (($kin['relationship'] ?? '') == 'other') echo 'selected'; ?>>Other</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Email Address</label>
                                            <input type="email" class="form-control" name="kin_email" value="<?php echo htmlspecialchars($kin['email'] ?? ''); ?>" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Phone Number</label>
                                            <input type="tel" class="form-control" name="kin_phone" value="<?php echo htmlspecialchars($kin['phone'] ?? ''); ?>" required>
                                        </div>
                                    </div>
                                    <div class="col-12">
                                        <div class="form-group">
                                            <label class="form-label">Address</label>
                                            <textarea class="form-control" name="kin_address" rows="3" required><?php echo htmlspecialchars($kin['address'] ?? ''); ?></textarea>
                                        </div>
                                    </div>
                                </div>

                                <div class="d-flex justify-content-between mt-4">
                                    <button type="button" class="btn btn-outline-secondary" onclick="prevStep(2)">
                                        <i class='bx bx-left-arrow-alt me-1'></i> Back
                                    </button>
                                    <button type="button" class="btn btn-primary" onclick="nextStep(2)">
                                        Continue <i class='bx bx-right-arrow-alt ms-1'></i>
                                    </button>
                                </div>
                            </div>

                            <!-- Step 3: Account Details -->
                            <div class="tab-pane fade" id="account" role="tabpanel">
                                <h5 class="section-header">Account Setup</h5>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Account Type</label>
                                            <select class="form-select" name="account_type" required>
                                                <option value="">Select Account Type</option>
                                                <option value="savings" <?php if ($user['account_type'] == 'savings') echo 'selected'; ?>>Savings Account</option>
                                                <option value="checking" <?php if ($user['account_type'] == 'checking') echo 'selected'; ?>>Checking Account</option>
                                                <option value="business" <?php if ($user['account_type'] == 'business') echo 'selected'; ?>>Business Account</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Currency</label>
                                            <select class="form-select" name="currency" required>
                                                <option value="">Select Currency</option>
                                                <option value="USD" <?php if ($user['currency'] == 'USD') echo 'selected'; ?>>US Dollar (USD)</option>
                                                <option value="EUR" <?php if ($user['currency'] == 'EUR') echo 'selected'; ?>>Euro (EUR)</option>
                                                <option value="GBP" <?php if ($user['currency'] == 'GBP') echo 'selected'; ?>>British Pound (GBP)</option>
                                                <option value="AUD" <?php if ($user['currency'] == 'AUD') echo 'selected'; ?>>Australian Dollar (AUD)</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Account Number</label>
                                            <input type="text" class="form-control bg-light" value="<?php echo htmlspecialchars($user['account_number'] ?? ''); ?>" readonly>
                                            <div class="form-text">Account number cannot be changed</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Account Status</label>
                                            <select class="form-select" name="status" required>
                                                <option value="pending" <?php if ($user['status'] == 'pending') echo 'selected'; ?>>Pending</option>
                                                <option value="active" <?php if ($user['status'] == 'active') echo 'selected'; ?>>Active</option>
                                                <option value="suspended" <?php if ($user['status'] == 'suspended') echo 'selected'; ?>>Suspended</option>
                                                <option value="closed" <?php if ($user['status'] == 'closed') echo 'selected'; ?>>Closed</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <!-- Account Preferences -->
                                <h5 class="section-header mt-4">Account Preferences</h5>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Debit Card Requested</label>
                                            <select class="form-select" name="request_debit_card">
                                                <option value="">Select Option</option>
                                                <option value="yes" <?php if (($user['request_debit_card'] ?? '') == 'yes') echo 'selected'; ?>>Yes</option>
                                                <option value="no" <?php if (($user['request_debit_card'] ?? '') == 'no') echo 'selected'; ?>>No</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Online Banking</label>
                                            <select class="form-select" name="online_banking">
                                                <option value="">Select Option</option>
                                                <option value="yes" <?php if (($user['online_banking'] ?? '') == 'yes') echo 'selected'; ?>>Yes</option>
                                                <option value="no" <?php if (($user['online_banking'] ?? '') == 'no') echo 'selected'; ?>>No</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Initial Deposit Range</label>
                                            <select class="form-select" name="initial_deposit">
                                                <option value="">Select Range</option>
                                                <option value="$1,000 - $5,000" <?php if (($user['initial_deposit'] ?? '') == '$1,000 - $5,000') echo 'selected'; ?>>$1,000 - $5,000</option>
                                                <option value="$5,001 - $10,000" <?php if (($user['initial_deposit'] ?? '') == '$5,001 - $10,000') echo 'selected'; ?>>$5,001 - $10,000</option>
                                                <option value="$10,001 - $25,000" <?php if (($user['initial_deposit'] ?? '') == '$10,001 - $25,000') echo 'selected'; ?>>$10,001 - $25,000</option>
                                                <option value="$25,001 - $50,000" <?php if (($user['initial_deposit'] ?? '') == '$25,001 - $50,000') echo 'selected'; ?>>$25,001 - $50,000</option>
                                                <option value="$50,001+" <?php if (($user['initial_deposit'] ?? '') == '$50,001+') echo 'selected'; ?>>$50,001+</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <!-- Account Balances Section -->
                                <?php if (!empty($balances)): ?>
                                <h5 class="section-header mt-4">Account Balances</h5>
                                <div class="table-responsive">
                                    <table class="app-table">
                                        <thead>
                                            <tr>
                                                <th>Currency</th>
                                                <th>Balance</th>
                                                <th>Last Updated</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($balances as $balance): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($balance['currency']); ?></td>
                                                <td><?php echo number_format($balance['balance'], 2); ?></td>
                                                <td><?php echo date('Y-m-d H:i:s', strtotime($balance['last_updated'])); ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="app-alert app-alert-info mt-3">
                                    <div class="app-alert-icon">
                                        <i class="bx bx-info-circle"></i>
                                    </div>
                                    <div class="app-alert-content">
                                        <div class="app-alert-title">Currency Change Notice</div>
                                        <div>Changing the user's currency will convert all existing balances to the new currency.</div>
                                    </div>
                                </div>
                                <?php endif; ?>

                                <div class="d-flex justify-content-between mt-4">
                                    <button type="button" class="btn btn-outline-secondary" onclick="prevStep(3)">
                                        <i class='bx bx-left-arrow-alt me-1'></i> Back
                                    </button>
                                    <button type="button" class="btn btn-primary" onclick="nextStep(3)">
                                        Continue <i class='bx bx-right-arrow-alt ms-1'></i>
                                    </button>
                                </div>
                            </div>

                            <!-- Step 4: Security -->
                            <div class="tab-pane fade" id="security" role="tabpanel">
                                <h5 class="section-header">Security Settings</h5>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Username</label>
                                            <input type="text" class="form-control bg-light" name="username" value="<?php echo htmlspecialchars($user['username']); ?>" readonly>
                                            <div class="form-text">Username cannot be changed</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Email Verified</label>
                                            <div class="form-control bg-light">
                                                <?php if ($user['email_verified']): ?>
                                                    <span class="text-success"><i class='bx bx-check-circle me-1'></i> Verified</span>
                                                <?php else: ?>
                                                    <span class="text-danger"><i class='bx bx-x-circle me-1'></i> Not Verified</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Two-Factor Authentication</label>
                                            <div class="form-control bg-light">
                                                <?php if ($user['two_factor_enabled']): ?>
                                                    <span class="text-success"><i class='bx bx-check-circle me-1'></i> Enabled</span>
                                                <?php else: ?>
                                                    <span class="text-danger"><i class='bx bx-x-circle me-1'></i> Disabled</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="app-alert app-alert-info mt-4">
                                    <div class="app-alert-icon">
                                        <i class="bx bx-info-circle"></i>
                                    </div>
                                    <div class="app-alert-content">
                                        <div class="app-alert-title">Password Reset</div>
                                        <div>To reset the user's password, use the "Reset Password" option from the user details page.</div>
                                    </div>
                                </div>

                                                               <div class="app-alert app-alert-warning mt-4">
                                    <div class="app-alert-icon">
                                        <i class="bx bx-shield-quarter"></i>
                                    </div>
                                    <div class="app-alert-content">
                                        <div class="app-alert-title">Security Notice</div>
                                        <div>Changing critical account information may require additional verification from the user.</div>
                                    </div>
                                </div>

                                <div class="d-flex justify-content-between mt-4">
                                    <button type="button" class="btn btn-outline-secondary" onclick="prevStep(4)">
                                        <i class='bx bx-left-arrow-alt me-1'></i> Back
                                    </button>
                                    <button type="button" class="btn btn-success" id="directSubmitBtn">
                                        <i class='bx bx-save me-1'></i> Save All Changes
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
// Form wizard navigation
let currentStep = 1;
const totalSteps = 4;

function showStep(step) {
    // Hide all steps
    document.querySelectorAll('.tab-pane').forEach(pane => {
        pane.classList.remove('show', 'active');
    });
    
    // Show the current step
    const currentPane = document.getElementById(['personal', 'profile', 'account', 'security'][step-1]);
    currentPane.classList.add('show', 'active');
    
    // Update wizard navigation
    document.querySelectorAll('.wizard-step').forEach((wizardStep, index) => {
        const stepNum = index + 1;
        wizardStep.classList.remove('active', 'completed');
        
        if (stepNum === step) {
            wizardStep.classList.add('active');
        } else if (stepNum < step) {
            wizardStep.classList.add('completed');
            // Replace number with check icon for completed steps
            const stepIcon = wizardStep.querySelector('.step-icon');
            if (stepIcon && !stepIcon.innerHTML.includes('bx-check')) {
                stepIcon.innerHTML = '<i class="bx bx-check"></i>';
            }
        } else {
            // Reset to number for future steps
            const stepIcon = wizardStep.querySelector('.step-icon');
            if (stepIcon) {
                stepIcon.textContent = stepNum;
            }
        }
    });
    
    // Update current step tracker
    currentStep = step;
    
    // Scroll to top of form
    document.querySelector('.app-card').scrollIntoView({ behavior: 'smooth', block: 'start' });
}

function nextStep(step) {
    if (step < totalSteps) {
        showStep(step + 1);
    }
}

function prevStep(step) {
    if (step > 1) {
        showStep(step - 1);
    }
}

// Allow clicking on wizard steps directly
document.querySelectorAll('.wizard-step').forEach((step, index) => {
    step.addEventListener('click', () => {
        showStep(index + 1);
    });
});

// Profile picture preview
document.getElementById('profile_picture').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
        if (file.size > 5 * 1024 * 1024) {
            Swal.fire({
                title: 'File Too Large',
                text: 'Maximum file size is 5MB.',
                icon: 'error',
                confirmButtonColor: '#4f46e5'
            });
            this.value = '';
            return;
        }

        if (!file.type.startsWith('image/')) {
            Swal.fire({
                title: 'Invalid File Type',
                text: 'Please select an image file (JPG or PNG).',
                icon: 'error',
                confirmButtonColor: '#4f46e5'
            });
            this.value = '';
            return;
        }

        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('profilePreview').src = e.target.result;
        }
        reader.readAsDataURL(file);
    }
});

// Direct form submission
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('editUserForm');
    const directSubmitBtn = document.getElementById('directSubmitBtn');
    
    if (directSubmitBtn && form) {
        directSubmitBtn.addEventListener('click', function() {
            // Use SweetAlert2 for confirmation
            Swal.fire({
                title: 'Save Changes?',
                text: 'Are you sure you want to save these changes to the user\'s profile?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#10b981',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Yes, save changes',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    form.submit();
                }
            });
        });
    }
    
    // Add click handlers to wizard steps
    document.querySelectorAll('.wizard-step').forEach((step, index) => {
        step.addEventListener('click', function() {
            showStep(index + 1);
        });
    });
});
</script>

<?php
// Include the footer
include 'includes/footer.php';
?>

