<?php
session_start();
require_once 'includes/auth_check.php';

$page = 'profile';
$database = new Database();
$db = $database->getConnection();

$success_message = '';
$error_message = '';
// Set a default active tab
$active_tab = 'personal';

// --- Handle Profile Information Update ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $active_tab = 'personal'; // Keep the personal tab active
    
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $date_of_birth = trim($_POST['date_of_birth'] ?? '');
    $gender = trim($_POST['gender'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $city = trim($_POST['city'] ?? '');
    $state = trim($_POST['state'] ?? '');
    $zip_code = trim($_POST['zip_code'] ?? '');
    $country = trim($_POST['country'] ?? '');
    $employment_status = trim($_POST['employment_status'] ?? '');
    $income_source = trim($_POST['income_source'] ?? '');
    $occupation = trim($_POST['occupation'] ?? '');
    $employer = trim($_POST['employer'] ?? '');
    
    if (empty($first_name) || empty($last_name) || empty($email)) {
        $error_message = "First name, last name, and email are required fields.";
    } else {
        try {
            $stmt = $db->prepare("UPDATE users SET 
                first_name = ?, 
                last_name = ?, 
                email = ?, 
                phone = ?, 
                date_of_birth = ?, 
                gender = ?, 
                address = ?,
                city = ?,
                state = ?,
                zip_code = ?,
                country = ?, 
                employment_status = ?, 
                income_source = ?,
                occupation = ?,
                employer = ?,
                updated_at = NOW() 
                WHERE id = ?");
            $stmt->execute([
                $first_name, 
                $last_name, 
                $email, 
                $phone, 
                $date_of_birth, 
                $gender, 
                $address,
                $city,
                $state,
                $zip_code,
                $country, 
                $employment_status, 
                $income_source,
                $occupation,
                $employer,
                $_SESSION['user_id']
            ]);
            $success_message = "Your profile has been updated successfully.";
        } catch (PDOException $e) {
            $error_message = "An error occurred while updating your profile.";
            error_log("Profile Update Error: " . $e->getMessage());
        }
    }
}

// --- Handle Password Change ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $active_tab = 'security'; // Set the active tab to 'security'
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        $error_message = "All password fields are required.";
    } elseif ($new_password !== $confirm_password) {
        $error_message = "New password and confirmation do not match.";
    } else {
        try {
            $stmt = $db->prepare("SELECT password FROM users WHERE id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$user_data || !password_verify($current_password, $user_data['password'])) {
                $error_message = "Your current password is not correct.";
            } else {
                $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                $stmt = $db->prepare("UPDATE users SET password = ? WHERE id = ?");
                $stmt->execute([$hashed_password, $_SESSION['user_id']]);
                $success_message = "Your password has been updated successfully.";
            }
        } catch (PDOException $e) {
            $error_message = "An error occurred while updating your password.";
            error_log("Password Update Error: " . $e->getMessage());
        }
    }
}

// --- Handle Profile Picture Upload ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_picture'])) {
    $active_tab = 'security'; // Keep the security tab active
    $root_path = dirname(__DIR__); 
    $upload_dir = $root_path . '/uploads/profiles/';

    if (!isset($_FILES['profile_picture']) || $_FILES['profile_picture']['error'] !== UPLOAD_ERR_OK) {
        $error_message = "No file was uploaded or an upload error occurred.";
    } elseif (!file_exists($upload_dir) || !is_dir($upload_dir)) {
        $error_message = "Configuration Error: The upload directory does not exist.";
    } elseif (!is_writable($upload_dir)) {
        $error_message = "Configuration Error: The directory '{$upload_dir}' is not writable. Please check permissions.";
    } else {
        $file = $_FILES['profile_picture'];
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
        $file_type = mime_content_type($file['tmp_name']);
        if (!in_array($file_type, $allowed_types)) {
            $error_message = "Invalid file type. Only JPG, PNG, and GIF are allowed.";
        } elseif ($file['size'] > 5000000) {
            $error_message = "File is too large. Maximum size is 5MB.";
        } else {
            $file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);
            $new_filename = 'profile_' . $_SESSION['user_id'] . '_' . time() . '.' . $file_extension;
            $upload_path = $upload_dir . $new_filename;
            if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                if (!empty($user['profile_picture']) && file_exists($upload_dir . $user['profile_picture'])) {
                    @unlink($upload_dir . $user['profile_picture']);
                }
                $stmt = $db->prepare("UPDATE users SET profile_picture = ? WHERE id = ?");
                $stmt->execute([$new_filename, $_SESSION['user_id']]);
                $success_message = "Your profile picture has been updated successfully.";
            } else {
                $error_message = "An unknown error occurred while moving the file.";
            }
        }
    }
}

// --- Handle PIN Change ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_pin'])) {
    $active_tab = 'security'; // Set the active tab to 'security'
    $current_pin = $_POST['current_pin'] ?? '';
    $new_pin = $_POST['new_pin'] ?? '';
    $confirm_pin = $_POST['confirm_pin'] ?? '';
    
    if (empty($current_pin) || empty($new_pin) || empty($confirm_pin)) {
        $error_message = "All PIN fields are required.";
    } elseif (strlen($new_pin) !== 4 || !ctype_digit($new_pin)) {
        $error_message = "PIN must be exactly 4 digits.";
    } elseif ($new_pin !== $confirm_pin) {
        $error_message = "New PIN and confirmation do not match.";
    } else {
        try {
            $stmt = $db->prepare("SELECT pin FROM users WHERE id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$user_data || !password_verify($current_pin, $user_data['pin'])) {
                $error_message = "Your current PIN is not correct.";
            } else {
                $hashed_pin = password_hash($new_pin, PASSWORD_DEFAULT);
                $stmt = $db->prepare("UPDATE users SET pin = ? WHERE id = ?");
                $stmt->execute([$hashed_pin, $_SESSION['user_id']]);
                $success_message = "Your PIN has been updated successfully.";
            }
        } catch (PDOException $e) {
            $error_message = "An error occurred while updating your PIN.";
            error_log("PIN Update Error: " . $e->getMessage());
        }
    }
}

// Get the latest user data to display
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Fetch next of kin data if available
$kin = null;
try {
    $kin_stmt = $db->prepare("SELECT * FROM next_of_kin WHERE user_id = ?");
    $kin_stmt->execute([$_SESSION['user_id']]);
    $kin = $kin_stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Next of Kin Fetch Error: " . $e->getMessage());
}

include 'includes/header.php';
include 'includes/sidebar.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 */
.main-content {
    background-color: #f9fafb;
    min-height: calc(100vh - 60px);
    padding: 2rem 0;
}

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

.profile-header {
    background: linear-gradient(135deg, var(--primary-dark), var(--primary-color));
    color: white;
    padding: 3rem 2rem;
    text-align: center;
    position: relative;
}

.profile-picture-container {
    position: relative;
    width: 120px;
    height: 120px;
    margin: 0 auto 1.5rem;
}

.profile-picture, .profile-picture-initial {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
    border: 4px solid white;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.profile-picture-initial {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 3rem;
    font-weight: 700;
    color: white;
    background: linear-gradient(135deg, var(--primary-color), #818cf8);
}

.profile-name {
    font-size: 1.75rem;
    font-weight: 700;
    margin-bottom: 0.25rem;
}

.profile-email {
    opacity: 0.9;
    margin-bottom: 0;
    font-size: 1.1rem;
}

/* Tab Navigation */
.profile-tabs {
    display: flex;
    border-bottom: 1px solid var(--border-color);
    padding: 0 1.5rem;
    overflow-x: auto;
    scrollbar-width: none; /* Firefox */
}

.profile-tabs::-webkit-scrollbar {
    display: none; /* Chrome, Safari, Edge */
}

.profile-tab {
    padding: 1rem 1.5rem;
    font-weight: 600;
    color: var(--secondary-color);
    cursor: pointer;
    white-space: nowrap;
    border-bottom: 2px solid transparent;
    transition: var(--transition-base);
}

.profile-tab:hover {
    color: var(--primary-color);
}

.profile-tab.active {
    color: var(--primary-color);
    border-bottom-color: var(--primary-color);
}

.profile-tab i {
    margin-right: 0.5rem;
}

/* Tab Content */
.tab-content {
    padding: 2rem;
}

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

.section-header i {
    margin-right: 0.75rem;
    font-size: 1.5rem;
    color: var(--primary-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-control:disabled,
.form-control[readonly] {
    background-color: #f1f5f9;
    opacity: 1;
}

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

/* Form Footer */
.form-footer {
    padding: 1.5rem 2rem;
    border-top: 1px solid var(--border-color);
    background-color: #f8fafc;
    display: flex;
    justify-content: flex-end;
}

/* 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);
    transform: translateY(-2px);
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.btn-outline-primary {
    color: var(--primary-color);
    border-color: var(--primary-color);
}

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

/* 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;
}

/* Responsive Adjustments */
@media (max-width: 768px) {
    .profile-tabs {
        padding: 0;
    }
    
    .profile-tab {
        padding: 1rem;
    }
    
    .tab-content {
        padding: 1.5rem;
    }
    
    .form-footer {
        padding: 1.25rem 1.5rem;
    }
}
</style>

<div class="main-content">
    <div class="container">
        <?php if (!empty($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 $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 (!empty($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 $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="profile-card">
            <div class="profile-header">
                <div class="profile-picture-container">
                    <?php if (!empty($user['profile_picture'])): ?>
                        <img src="<?php echo BASE_URL . 'uploads/profiles/' . htmlspecialchars($user['profile_picture']); ?>" alt="Profile" class="profile-picture" onerror="this.onerror=null; this.src='<?php echo BASE_URL; ?>assets/images/default-avatar.png';">
                    <?php else: ?>
                        <div class="profile-picture-initial"><?php echo strtoupper(substr($user['first_name'] ?? 'U', 0, 1)); ?></div>
                    <?php endif; ?>
                </div>
                <h2 class="profile-name"><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></h2>
                <p class="profile-email"><?php echo htmlspecialchars($user['email']); ?></p>
            </div>
            
            <!-- Tab Navigation -->
            <div class="profile-tabs">
                <div class="profile-tab <?php echo ($active_tab == 'personal') ? 'active' : ''; ?>" data-tab="personal">
                    <i class='bx bx-user'></i> Personal Information
                </div>
                <div class="profile-tab <?php echo ($active_tab == 'security') ? 'active' : ''; ?>" data-tab="security">
                    <i class='bx bx-lock-alt'></i> Security
                </div>
                <div class="profile-tab" data-tab="account">
                    <i class='bx bx-credit-card'></i> Account Details
                </div>
                <?php if ($kin): ?>
                <div class="profile-tab" data-tab="kin">
                    <i class='bx bx-group'></i> Next of Kin
                </div>
                <?php endif; ?>
            </div>

            <!-- Tab Content -->
            <div class="tab-content">
                <!-- Personal Information Tab -->
                <div class="tab-pane <?php echo ($active_tab == 'personal') ? 'active' : ''; ?>" id="personal">
                    <form method="post" action="profile.php">
                        <div class="section-header">
                            <i class='bx bx-user-circle'></i> Personal Details
                        </div>
                        <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'] ?? ''); ?>">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label">Username</label>
                                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['username']); ?>" readonly disabled>
                                    <div class="form-text">Username cannot be changed</div>
                                </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="date_of_birth" value="<?php echo htmlspecialchars($user['date_of_birth'] ?? ''); ?>">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label">Gender</label>
                                    <select class="form-select" name="gender">
                                        <option value="">Select Gender</option>
                                        <option value="male" <?php echo (strtolower($user['gender'] ?? '') == 'male') ? 'selected' : ''; ?>>Male</option>
                                        <option value="female" <?php echo (strtolower($user['gender'] ?? '') == 'female') ? 'selected' : ''; ?>>Female</option>
                                        <option value="other" <?php echo (strtolower($user['gender'] ?? '') == 'other') ? 'selected' : ''; ?>>Other</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" value="<?php echo htmlspecialchars($user['account_number'] ?? ''); ?>" readonly disabled>
                                    <div class="form-text">Account number cannot be changed</div>
                                </div>
                            </div>
                        </div>

                        <div class="section-header mt-4">
                            <i class='bx bx-map'></i> Address Information
                        </div>
                        <div class="row g-3">
                            <div class="col-12">
                                <div class="form-group">
                                    <label class="form-label">Street Address</label>
                                    <input type="text" class="form-control" name="address" value="<?php echo htmlspecialchars($user['address'] ?? ''); ?>">
                                </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>
                                    <input type="text" class="form-control" name="country" value="<?php echo htmlspecialchars($user['country'] ?? ''); ?>">
                                </div>
                            </div>
                        </div>

                        <div class="section-header mt-4">
                            <i class='bx bx-briefcase'></i> Employment Information
                        </div>
                        <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">
                                        <option value="">Select Status</option>
                                        <option value="employed" <?php echo (strtolower($user['employment_status'] ?? '') == 'employed') ? 'selected' : ''; ?>>Employed</option>
                                        <option value="self-employed" <?php echo (strtolower($user['employment_status'] ?? '') == 'self-employed') ? 'selected' : ''; ?>>Self-Employed</option>
                                        <option value="unemployed" <?php echo (strtolower($user['employment_status'] ?? '') == 'unemployed') ? 'selected' : ''; ?>>Unemployed</option>
                                        <option value="student" <?php echo (strtolower($user['employment_status'] ?? '') == 'student') ? 'selected' : ''; ?>>Student</option>
                                        <option value="retired" <?php echo (strtolower($user['employment_status'] ?? '') == 'retired') ? 'selected' : ''; ?>>Retired</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label">Primary Income Source</label>
                                    <select class="form-select" name="income_source">
                                        <option value="">Select Source</option>
                                                                                <option value="salary" <?php echo (strtolower($user['income_source'] ?? '') == 'salary') ? 'selected' : ''; ?>>Salary</option>
                                        <option value="business" <?php echo (strtolower($user['income_source'] ?? '') == 'business') ? 'selected' : ''; ?>>Business</option>
                                        <option value="investments" <?php echo (strtolower($user['income_source'] ?? '') == 'investments') ? 'selected' : ''; ?>>Investments</option>
                                        <option value="other" <?php echo (strtolower($user['income_source'] ?? '') == 'other') ? '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>

                        <div class="form-footer">
                            <button type="submit" name="update_profile" value="1" class="btn btn-primary">
                                <i class='bx bx-save me-1'></i> Save Changes
                            </button>
                        </div>
                    </form>
                </div>
                
                <!-- Security Tab -->
                <div class="tab-pane <?php echo ($active_tab == 'security') ? 'active' : ''; ?>" id="security">
                    <!-- Change Password Form -->
                    <div class="mb-5">
                        <div class="section-header">
                            <i class='bx bx-lock-alt'></i> Change Password
                        </div>
                        <form method="post" action="profile.php">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label">Current Password</label>
                                        <input type="password" class="form-control" name="current_password" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label">New Password</label>
                                        <input type="password" class="form-control" name="new_password" required>
                                        <div class="form-text">Password must be at least 8 characters long</div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label">Confirm New Password</label>
                                        <input type="password" class="form-control" name="confirm_password" required>
                                    </div>
                                </div>
                            </div>
                            <div class="mt-3">
                                <button type="submit" name="change_password" value="1" class="btn btn-primary">
                                    <i class='bx bx-lock me-1'></i> Update Password
                                </button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- Change PIN Form -->
                    <div class="mb-5">
                        <div class="section-header">
                            <i class='bx bx-key'></i> Change Transaction PIN
                        </div>
                        <form method="post" action="profile.php">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">Current PIN</label>
                                        <input type="password" class="form-control" name="current_pin" maxlength="4" required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">New PIN</label>
                                        <input type="password" class="form-control" name="new_pin" maxlength="4" required>
                                        <div class="form-text">PIN must be exactly 4 digits</div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">Confirm New PIN</label>
                                        <input type="password" class="form-control" name="confirm_pin" maxlength="4" required>
                                    </div>
                                </div>
                            </div>
                            <div class="mt-3">
                                <button type="submit" name="change_pin" value="1" class="btn btn-primary">
                                    <i class='bx bx-key me-1'></i> Update PIN
                                </button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- Change Profile Picture Form -->
                    <div>
                        <div class="section-header">
                            <i class='bx bx-image'></i> Change Profile Picture
                        </div>
                        <form method="post" enctype="multipart/form-data" action="profile.php">
                            <div class="row">
                                <div class="col-md-8">
                                    <div class="form-group">
                                        <label class="form-label">Select a new profile picture</label>
                                        <input type="file" class="form-control" name="profile_picture" id="profile-picture-input" accept="image/jpeg, image/png, image/gif" required>
                                        <div class="form-text">Maximum file size: 5MB. Supported formats: JPG, PNG, GIF</div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="d-flex align-items-center h-100">
                                        <div class="mt-4">
                                            <button type="submit" name="upload_picture" value="1" class="btn btn-primary">
                                                <i class='bx bx-upload me-1'></i> Upload Picture
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- Account Details Tab -->
                <div class="tab-pane" id="account">
                    <div class="section-header">
                        <i class='bx bx-credit-card'></i> Account Information
                    </div>
                    
                    <div class="row g-3">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Account Number</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['account_number'] ?? ''); ?>" readonly>
                                    <button class="btn btn-outline-primary" type="button" onclick="copyToClipboard('<?php echo htmlspecialchars($user['account_number'] ?? ''); ?>')">
                                        <i class='bx bx-copy'></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Account Type</label>
                                <input type="text" class="form-control" value="<?php echo ucfirst(htmlspecialchars($user['account_type'] ?? '')); ?>" readonly>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Currency</label>
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['currency'] ?? ''); ?>" readonly>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Account Status</label>
                                <?php
                                $statusClass = [
                                    'active' => 'success',
                                    'pending' => 'warning',
                                    'suspended' => 'danger',
                                    'closed' => 'secondary'
                                ];
                                $status = strtolower($user['status'] ?? 'pending');
                                $badgeClass = $statusClass[$status] ?? 'secondary';
                                ?>
                                <div class="form-control bg-<?php echo $badgeClass; ?>-light text-<?php echo $badgeClass; ?> fw-bold">
                                    <?php echo ucfirst($status); ?>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6" style="display: none;">
                            <div class="form-group">
                                <label class="form-label">Date Opened</label>
                                <input type="text" class="form-control" value="<?php echo date('F j, Y', strtotime($user['created_at'] ?? 'now')); ?>" readonly>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Last Login</label>
                                <input type="text" class="form-control" value="<?php echo !empty($user['last_login']) ? date('F j, Y H:i', strtotime($user['last_login'])) : 'N/A'; ?>" readonly>
                            </div>
                        </div>
                    </div>
                    
                    <div class="section-header mt-4">
                        <i class='bx bx-cog'></i> Account Preferences
                    </div>
                    
                    <div class="row g-3">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Online Banking</label>
                                <input type="text" class="form-control" value="<?php echo ($user['online_banking'] ?? '') == 'yes' ? 'Enabled' : 'Disabled'; ?>" readonly>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Debit Card</label>
                                <input type="text" class="form-control" value="<?php echo ($user['request_debit_card'] ?? '') == 'yes' ? 'Requested' : 'Not Requested'; ?>" readonly>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Two-Factor Authentication</label>
                                <input type="text" class="form-control" value="<?php echo ($user['two_factor_enabled'] ?? 0) ? 'Enabled' : 'Disabled'; ?>" readonly>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Email Verification</label>
                                <input type="text" class="form-control" value="<?php echo ($user['email_verified'] ?? 0) ? 'Verified' : 'Not Verified'; ?>" readonly>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Next of Kin Tab -->
                <?php if ($kin): ?>
                <div class="tab-pane" id="kin">
                    <div class="section-header">
                        <i class='bx bx-group'></i> Next of Kin Information
                    </div>
                    
                    <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" value="<?php echo htmlspecialchars($kin['full_name'] ?? ''); ?>" readonly>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Relationship</label>
                                <input type="text" class="form-control" value="<?php echo ucfirst(htmlspecialchars($kin['relationship'] ?? '')); ?>" readonly>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Email Address</label>
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($kin['email'] ?? ''); ?>" readonly>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Phone Number</label>
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($kin['phone'] ?? ''); ?>" readonly>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-group">
                                <label class="form-label">Address</label>
                                <textarea class="form-control" rows="3" readonly><?php echo htmlspecialchars($kin['address'] ?? ''); ?></textarea>
                            </div>
                        </div>
                    </div>
                    
                    <div class="alert alert-info mt-4">
                        <div class="d-flex">
                            <div class="me-3">
                                <i class='bx bx-info-circle fs-4'></i>
                            </div>
                            <div>
                                <h5 class="alert-heading">Information</h5>
                                <p class="mb-0">To update your next of kin information, please contact customer support or visit your nearest branch.</p>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
// Tab Navigation
document.addEventListener('DOMContentLoaded', function() {
    const tabs = document.querySelectorAll('.profile-tab');
    const tabPanes = document.querySelectorAll('.tab-pane');
    
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // Remove active class from all tabs
            tabs.forEach(t => t.classList.remove('active'));
            
            // Add active class to clicked tab
            this.classList.add('active');
            
            // Hide all tab panes
            tabPanes.forEach(pane => {
                pane.classList.remove('active');
            });
            
            // Show the corresponding tab pane
            const tabId = this.getAttribute('data-tab');
            document.getElementById(tabId).classList.add('active');
        });
    });
    
    // Preview profile picture before upload
    const profilePictureInput = document.getElementById('profile-picture-input');
    if (profilePictureInput) {
        profilePictureInput.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.match('image.*')) {
                    alert('Please select an image file.');
                    this.value = '';
                    return;
                }
            }
        });
    }
});

// Copy to clipboard function
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(function() {
        // Show a toast notification
        const toast = document.createElement('div');
        toast.className = 'position-fixed bottom-0 end-0 p-3';
        toast.style.zIndex = '5';
        toast.innerHTML = `
            <div class="toast align-items-center text-white bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true">
                <div class="d-flex">
                    <div class="toast-body">
                        <i class="bx bx-check me-2"></i> Copied to clipboard!
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            </div>
        `;
        document.body.appendChild(toast);
        
        const toastEl = new bootstrap.Toast(toast.querySelector('.toast'));
        toastEl.show();
        
        setTimeout(() => {
            toast.remove();
        }, 3000);
    }).catch(function(err) {
        console.error('Could not copy text: ', err);
    });
}
</script>

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

