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

// --- Handle Form Submission (POST Request) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 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']);
    
    // 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'];
    $status = $_POST['status'];
    
    // 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();
            
            // 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,
                        account_type = :account_type,
                        currency = :currency,
                        employment_status = :employment_status,
                        income_source = :income_source,
                        status = :status";
            
            // 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(':account_type', $account_type);
            $stmt->bindParam(':currency', $currency);
            $stmt->bindParam(':employment_status', $employment_status);
            $stmt->bindParam(':income_source', $income_source);
            $stmt->bindParam(':status', $status);
            
            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();
            
            // 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
                    ]);
                } 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
                    ]);
                }
            }
            
            // 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) {
                    // 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']]);
                    } 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']]);
                    }
                    
                    // Add a transaction record for the currency change if transactions table exists
                    if (tableExists($db, 'transactions')) {
                        $trans_stmt = $db->prepare("
                            INSERT INTO transactions (
                                user_id, type, amount, currency, description, status, created_at
                            ) VALUES (?, 'system', ?, ?, ?, 'completed', NOW())
                        ");
                        $trans_stmt->execute([
                            $user_id, 
                            $old_balance['balance'], 
                            $currency, 
                            "Currency changed from {$old_balance['currency']} to {$currency}"
                        ]);
                    }
                }
            }

            // Commit all changes
            $db->commit();
            
            $_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';
?>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Edit User: <?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></h1>

    <?php if (isset($pageError)): ?>
        <div class="alert alert-danger"><?php echo $pageError; ?></div>
    <?php else: ?>
        <!-- Display Success/Error Messages from redirects -->
        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">User Information</h6>
                <div>
                    <a href="view_user.php?id=<?php echo $user_id; ?>" class="btn btn-sm btn-secondary me-2">
                        <i class='bx bx-show me-1'></i>View User
                    </a>
                    <a href="manage_users.php" class="btn btn-sm btn-secondary">
                        <i class='bx bx-arrow-back me-1'></i>Back to Users
                    </a>
                </div>
            </div>
            <div class="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']); ?>">
                    
                    <!-- Step Progress Indicator -->
                    <div class="mb-4">
                        <ul class="nav nav-pills nav-justified step-progress" id="userFormTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="personal-tab" data-bs-toggle="pill" data-bs-target="#personal" type="button" role="tab" aria-selected="true">
                                    <span class="step-number">1</span>
                                    <span class="d-none d-md-inline ms-2">Personal Info</span>
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="profile-tab" data-bs-toggle="pill" data-bs-target="#profile" type="button" role="tab" aria-selected="false">
                                    <span class="step-number">2</span>
                                    <span class="d-none d-md-inline ms-2">Profile</span>
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="account-tab" data-bs-toggle="pill" data-bs-target="#account" type="button" role="tab" aria-selected="false">
                                    <span class="step-number">3</span>
                                    <span class="d-none d-md-inline ms-2">Account</span>
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="security-tab" data-bs-toggle="pill" data-bs-target="#security" type="button" role="tab" aria-selected="false">
                                    <span class="step-number">4</span>
                                    <span class="d-none d-md-inline ms-2">Security</span>
                                </button>
                            </li>
                        </ul>
                    </div>
                    
                    <!-- Form Content -->
                    <div class="tab-content" id="userFormContent">
                        <!-- Step 1: Personal Information -->
                        <div class="tab-pane fade show active" id="personal" role="tabpanel" aria-labelledby="personal-tab">
                            <h5 class="mb-4">Personal Information</h5>
                            <div class="row g-3">
                                <div class="col-md-6 mb-3">
                                    <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 class="col-md-6 mb-3">
                                    <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 class="col-md-6 mb-3">
                                    <label class="form-label">Email Address</label>
                                    <input type="email" class="form-control" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Phone Number</label>
                                    <input type="tel" class="form-control" name="phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <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 class="col-md-6 mb-3">
                                    <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 class="col-md-6 mb-3">
                                    <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 class="col-12 mb-3">
                                    <label class="form-label">Address</label>
                                    <textarea class="form-control" name="address" rows="3" required><?php echo htmlspecialchars($user['address'] ?? ''); ?></textarea>
                                </div>
                            </div>

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

                        <!-- Step 2: Profile & Documents -->
                        <div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">
                            <h5 class="mb-4">Profile Setup</h5>
                            
                            <!-- Profile Picture Upload -->
                            <div class="row mb-4">
                                <div class="col-md-6">
                                    <div class="d-flex align-items-center">
                                        <div class="profile-preview me-4">
                                            <img src="../<?php echo !empty($user['profile_picture']) ? 'uploads/profiles/' . htmlspecialchars($user['profile_picture']) : 'assets/images/default-avatar.png'; ?>" 
                                                 id="profilePreview" alt="Profile Preview" 
                                                 style="width: 100px; height: 100px; border-radius: 50%; object-fit: cover; border: 3px solid #e2e8f0;">
                                        </div>
                                        <div>
                                            <h6 class="mb-2">Profile Picture</h6>
                                            <p class="text-muted mb-2">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'] ?? ''); ?>">
                                            <small class="text-muted">Max file size: 5MB (JPG or PNG)</small>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Next of Kin Information -->
                            <h5 class="mb-4">Next of Kin Details</h5>
                            <div class="row g-3">
                                <div class="col-md-6 mb-3">
                                    <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 class="col-md-6 mb-3">
                                    <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 class="col-md-6 mb-3">
                                    <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 class="col-md-6 mb-3">
                                    <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 class="col-12 mb-3">
                                    <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 class="d-flex justify-content-between mt-4">
                                <button type="button" class="btn btn-outline-secondary" onclick="nextTab('personal-tab')">
                                    <i class='bx bx-left-arrow-alt'></i> Back
                                </button>
                                <button type="button" class="btn btn-primary" onclick="nextTab('account-tab')">
                                    Continue <i class='bx bx-right-arrow-alt'></i>
                                </button>
                            </div>
                        </div>

                        <!-- Step 3: Account Details -->
                        <div class="tab-pane fade" id="account" role="tabpanel" aria-labelledby="account-tab">
                            <h5 class="mb-4">Account Setup</h5>
                            <div class="row g-3">
                                <div class="col-md-6 mb-3">
                                    <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 class="col-md-6 mb-3">
                                    <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 class="col-md-6 mb-3">
                                    <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 mb-3">
                                    <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 class="col-md-6 mb-3">
                                    <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 class="col-md-6 mb-3">
                                    <label class="form-label">Account Number</label>
                                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['account_number'] ?? ''); ?>" readonly>
                                    <small class="text-muted">Account number cannot be changed</small>
                                </div>
                            </div>

                            <!-- Account Balances Section -->
                            <?php if (!empty($balances)): ?>
                            <h5 class="mt-4 mb-3">Account Balances</h5>
                            <div class="table-responsive">
                                <table class="table table-bordered">
                                    <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="alert alert-info">
                                <i class='bx bx-info-circle me-2'></i>
                                Changing the user's currency will convert all existing balances to the new currency.
                            </div>
                            <?php endif; ?>

                            <div class="d-flex justify-content-between mt-4">
                                <button type="button" class="btn btn-outline-secondary" onclick="nextTab('profile-tab')">
                                    <i class='bx bx-left-arrow-alt'></i> Back
                                </button>
                                <button type="button" class="btn btn-primary" onclick="nextTab('security-tab')">
                                    Continue <i class='bx bx-right-arrow-alt'></i>
                                </button>
                            </div>
                        </div>

                        <!-- Step 4: Security -->
                        <div class="tab-pane fade" id="security" role="tabpanel" aria-labelledby="security-tab">
                            <h5 class="mb-4">Security Settings</h5>
                            <div class="row g-3">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Username</label>
                                    <input type="text" class="form-control" name="username" value="<?php echo htmlspecialchars($user['username']); ?>" readonly>
                                    <small class="text-muted">Username cannot be changed</small>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <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="alert alert-info mt-4">
                                <i class='bx bx-info-circle me-2'></i>
                                To reset the user's password, use the "Reset Password" option from the user details page.
                            </div>

                            <div class="alert alert-warning mt-4">
                                <i class='bx bx-shield-quarter me-2'></i>
                                <strong>Security Notice:</strong> Changing critical account information may require additional verification from the user.
                            </div>

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

<script>
function nextTab(tabId) {
    document.getElementById(tabId).click();
}

// 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) {
            alert('File size too large. Maximum size is 5MB.');
            this.value = '';
            return;
        }

        if (!file.type.startsWith('image/')) {
            alert('Please select an image file.');
            this.value = '';
            return;
        }

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

// Form submission confirmation
document.getElementById('editUserForm').addEventListener('submit', function(event) {
    // Prevent the form from submitting immediately
    event.preventDefault();

    Swal.fire({
        title: 'Confirm Changes',
        text: "Are you sure you want to save these changes to the user's profile?",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, save changes',
        reverseButtons: true
    }).then((result) => {
        // If the admin clicks "Yes, save changes!"
        if (result.isConfirmed) {
            // Submit the form
            this.submit();
        }
    });
});
</script>

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