<?php
// Enable error reporting for debugging purposes
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/notification.php';
require_once '../includes/session_manager.php';

redirectIfNotLoggedIn();

$userId = $_SESSION['user_id'];
$error = '';
$success = '';

// Get user account information
$stmt = $pdo->prepare("
    SELECT u.*, a.account_number, a.balance 
    FROM users u 
    JOIN accounts a ON u.user_id = a.user_id 
    WHERE u.user_id = ?
");
$stmt->execute([$userId]);
$user = $stmt->fetch();

if (!$user) {
    die('User account not found.');
}

// Check if the user has a profile picture
$profilePic = (!empty($user['profile_picture']) && file_exists('../uploads/' . $user['profile_picture']))
    ? '../uploads/' . $user['profile_picture']
    : '../assets/images/default-avatars.png';

// CSRF token for forms
if (empty($_SESSION['profile_token'])) {
    $_SESSION['profile_token'] = bin2hex(random_bytes(32));
}
if (empty($_SESSION['password_token'])) {
    $_SESSION['password_token'] = bin2hex(random_bytes(32));
}
$profile_token = $_SESSION['profile_token'];
$password_token = $_SESSION['password_token'];

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'update_profile':
                if (!isset($_POST['profile_token']) || $_POST['profile_token'] !== $_SESSION['profile_token']) {
                    $error = "Invalid security token. Please try again.";
                } else {
                    $full_name = htmlspecialchars($_POST['full_name'], ENT_QUOTES, 'UTF-8');
                    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
                    $age = intval($_POST['age']);
                    $birth_year = intval($_POST['birth_year']);
                    $address = htmlspecialchars($_POST['address'], ENT_QUOTES, 'UTF-8');
                    $occupation = htmlspecialchars($_POST['occupation'], ENT_QUOTES, 'UTF-8');
                    $phone = htmlspecialchars($_POST['phone'], ENT_QUOTES, 'UTF-8');

                    try {
                        $stmt = $pdo->prepare("
                            UPDATE users 
                            SET full_name=?, email=?, age=?, birth_year=?, address=?, occupation=?, phone=?
                            WHERE user_id=?
                        ");
                        $stmt->execute([
                            $full_name,
                            $email,
                            $age,
                            $birth_year,
                            $address,
                            $occupation,
                            $phone,
                            $userId
                        ]);

                        $_SESSION['profile_token'] = bin2hex(random_bytes(32));
                        $success = "Profile updated successfully!";

                        // Refresh user data
                        $stmt = $pdo->prepare("SELECT * FROM users WHERE user_id = ?");
                        $stmt->execute([$userId]);
                        $user = $stmt->fetch();
                    } catch (Exception $e) {
                        $error = "Failed to update profile: " . $e->getMessage();
                    }
                }
                break;

            case 'change_password':
                if (!isset($_POST['password_token']) || $_POST['password_token'] !== $_SESSION['password_token']) {
                    $error = "Invalid security token for password change.";
                } else {
                    $currentPassword = $_POST['current_password'];
                    $newPassword = $_POST['new_password'];
                    $confirmPassword = $_POST['confirm_password'];

                    // Verify current password
                    $stmt = $pdo->prepare("SELECT password_hash FROM users WHERE user_id = ?");
                    $stmt->execute([$userId]);
                    $userData = $stmt->fetch();

                    if (!password_verify($currentPassword, $userData['password_hash'])) {
                        $error = "Current password is incorrect";
                    } elseif ($newPassword !== $confirmPassword) {
                        $error = "New passwords do not match";
                    } elseif (strlen($newPassword) < 8) {
                        $error = "Password must be at least 8 characters long";
                    } elseif (!preg_match('/[A-Z]/', $newPassword)) {
                        $error = "Password must contain at least one uppercase letter";
                    } elseif (!preg_match('/[a-z]/', $newPassword)) {
                        $error = "Password must contain at least one lowercase letter";
                    } elseif (!preg_match('/[0-9]/', $newPassword)) {
                        $error = "Password must contain at least one number";
                    } else {
                        try {
                            $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
                            $stmt = $pdo->prepare("UPDATE users SET password_hash = ? WHERE user_id = ?");
                            $stmt->execute([$hashedPassword, $userId]);

                            // Send notification email
                            $userStmt = $pdo->prepare("SELECT full_name, email FROM users WHERE user_id = ?");
                            $userStmt->execute([$userId]);
                            $userData = $userStmt->fetch();

                            if ($userData) {
                                $emailSubject = "Password Change Alert - Oakshire Finance";
                                $emailMessage = "
                                    <html>
                                    <body style='font-family: Arial, sans-serif;'>
                                        <h2 style='color: #0a2540;'>Password Change Notification</h2>
                                        <p>Dear " . htmlspecialchars($userData['full_name']) . ",</p>
                                        <p>Your password was recently changed on your Oakshire Finance account.</p>
                                        <p>If you did not make this change, please contact our support team immediately.</p>
                                        <p><strong>Time of change:</strong> " . date('Y-m-d H:i:s') . "</p>
                                        <br>
                                        <p>Best regards,</p>
                                        <p><strong>Oakshire Finance Security Team</strong></p>
                                    </body>
                                    </html>
                                ";

                                sendNotification($userData['email'], $emailSubject, $emailMessage);
                            }

                            $_SESSION['password_token'] = bin2hex(random_bytes(32));
                            $success = "Password updated successfully!";

                            header("Location: profile.php?tab=security&success=1&message=" . urlencode($success));
                            exit();
                        } catch (Exception $e) {
                            $error = "Failed to update password: " . $e->getMessage();
                        }
                    }
                }
                break;
        }
    }
}

// Handle success message from redirect
if (isset($_GET['success']) && $_GET['success'] == 1 && isset($_GET['message'])) {
    $success = urldecode($_GET['message']);
}

$activeTab = isset($_GET['tab']) ? $_GET['tab'] : 'profile';
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Oakshire Finance - Profile Settings</title>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700;14..32,800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary-navy: #0a2540;
            --primary-dark: #0a1c2f;
            --primary-blue: #1a4d8c;
            --accent-blue: #2c7da0;
            --success-green: #2e7d32;
            --warning-orange: #f39c12;
            --error-red: #dc3545;
            --info-blue: #17a2b8;
            --gray-50: #f8f9fc;
            --gray-100: #f1f3f9;
            --gray-200: #e9ecef;
            --gray-300: #dee2e6;
            --gray-400: #ced4da;
            --gray-500: #adb5bd;
            --gray-600: #6c757d;
            --gray-700: #495057;
            --gray-800: #343a40;
            --gray-900: #212529;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.05);
            --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.08);
            --shadow-hover: 0 12px 28px rgba(0, 0, 0, 0.12);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background: var(--gray-50);
            color: var(--gray-800);
            line-height: 1.5;
            overflow-x: hidden;
        }

        /* Layout */
        .dashboard-wrapper {
            display: flex;
            min-height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            width: 280px;
            background: var(--white);
            border-right: 1px solid var(--gray-200);
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            transition: transform 0.3s ease;
            z-index: 100;
        }

        .sidebar-header {
            padding: 24px;
            border-bottom: 1px solid var(--gray-200);
            text-align: center;
        }

        .logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            text-decoration: none;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: var(--primary-navy);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logo-icon i {
            font-size: 20px;
            color: white;
        }

        .logo-text {
            font-size: 22px;
            font-weight: 700;
            color: var(--primary-navy);
            letter-spacing: -0.3px;
        }

        .profile-section {
            padding: 24px;
            text-align: center;
            border-bottom: 1px solid var(--gray-200);
        }

        .profile-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            margin: 0 auto 12px;
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-blue));
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }

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

        .profile-avatar i {
            font-size: 40px;
            color: white;
        }

        .profile-section h5 {
            font-size: 16px;
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 4px;
        }

        .profile-section p {
            font-size: 12px;
            color: var(--gray-500);
        }

        .nav-menu {
            padding: 16px;
        }

        .nav-item {
            margin-bottom: 4px;
        }

        .nav-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--gray-700);
            transition: var(--transition);
            font-weight: 500;
            font-size: 14px;
        }

        .nav-link i {
            width: 20px;
            font-size: 18px;
        }

        .nav-link:hover {
            background: var(--gray-100);
            color: var(--primary-blue);
        }

        .nav-link.active {
            background: var(--primary-navy);
            color: white;
        }

        .nav-link.active i {
            color: white;
        }

        .logout-section {
            padding: 16px;
            border-top: 1px solid var(--gray-200);
            margin-top: auto;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: var(--white);
        }

        .logout-btn {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--error-red);
            transition: var(--transition);
            font-weight: 500;
        }

        .logout-btn:hover {
            background: rgba(220, 53, 69, 0.1);
        }

        /* Main Content */
        .main-content {
            flex: 1;
            margin-left: 280px;
            min-height: 100vh;
        }

        /* Top Header */
        .top-header {
            background: var(--white);
            border-bottom: 1px solid var(--gray-200);
            padding: 16px 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 99;
        }

        .page-title h1 {
            font-size: 24px;
            font-weight: 700;
            color: var(--gray-900);
        }

        .user-menu {
            display: flex;
            align-items: center;
            gap: 24px;
        }

        .notification-btn {
            position: relative;
            background: none;
            border: none;
            font-size: 20px;
            color: var(--gray-600);
            cursor: pointer;
            transition: var(--transition);
        }

        .notification-btn:hover {
            color: var(--primary-blue);
        }

        /* Content Area */
        .content-area {
            padding: 32px;
        }

        /* Profile Card */
        .profile-card {
            background: var(--white);
            border-radius: 24px;
            border: 1px solid var(--gray-200);
            overflow: hidden;
        }

        .profile-header {
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-dark));
            padding: 48px 32px;
            text-align: center;
            color: white;
        }

        .profile-avatar-large {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            margin: 0 auto 16px;
            border: 4px solid white;
            box-shadow: var(--shadow-lg);
            overflow: hidden;
        }

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

        .profile-header h2 {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 4px;
        }

        .profile-header p {
            opacity: 0.8;
            font-size: 14px;
        }

        /* Tabs */
        .tabs {
            display: flex;
            border-bottom: 1px solid var(--gray-200);
            background: var(--white);
            padding: 0 24px;
        }

        .tab {
            padding: 16px 24px;
            cursor: pointer;
            font-weight: 500;
            color: var(--gray-600);
            transition: var(--transition);
            position: relative;
        }

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

        .tab.active {
            color: var(--primary-blue);
        }

        .tab.active::after {
            content: '';
            position: absolute;
            bottom: -1px;
            left: 0;
            right: 0;
            height: 2px;
            background: var(--primary-blue);
        }

        /* Tab Content */
        .tab-content {
            display: none;
            padding: 32px;
        }

        .tab-content.active {
            display: block;
        }

        /* Form Grid */
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 24px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            font-size: 13px;
            font-weight: 500;
            color: var(--gray-700);
            margin-bottom: 8px;
        }

        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 12px 16px;
            font-size: 14px;
            font-family: 'Inter', sans-serif;
            border: 1.5px solid var(--gray-200);
            border-radius: 12px;
            transition: var(--transition);
            outline: none;
            background: var(--gray-50);
        }

        .form-group input:focus,
        .form-group textarea:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(26, 77, 140, 0.1);
            background: var(--white);
        }

        .form-group input:not([disabled]):focus,
        .form-group textarea:not([disabled]):focus {
            background: var(--white);
        }

        .form-group input[disabled],
        .form-group textarea[disabled] {
            background: var(--gray-100);
            cursor: not-allowed;
        }

        .full-width {
            grid-column: span 2;
        }

        /* Buttons */
        .btn-primary {
            padding: 12px 24px;
            background: var(--primary-navy);
            color: white;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
        }

        .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-1px);
        }

        .btn-secondary {
            padding: 12px 24px;
            background: var(--gray-100);
            color: var(--gray-700);
            border: none;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
        }

        .btn-secondary:hover {
            background: var(--gray-200);
        }

        .form-actions {
            margin-top: 32px;
            display: flex;
            gap: 16px;
            justify-content: flex-end;
        }

        /* Upload Section */
        .upload-section {
            margin-bottom: 32px;
            padding-bottom: 24px;
            border-bottom: 1px solid var(--gray-200);
        }

        .upload-section h3 {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 16px;
        }

        .upload-area {
            display: flex;
            align-items: center;
            gap: 20px;
            flex-wrap: wrap;
        }

        .upload-btn {
            padding: 10px 20px;
            background: var(--gray-100);
            color: var(--gray-700);
            border: 1px solid var(--gray-200);
            border-radius: 10px;
            cursor: pointer;
            transition: var(--transition);
        }

        .upload-btn:hover {
            background: var(--gray-200);
        }

        /* Security Section */
        .security-section {
            max-width: 500px;
            margin: 0 auto;
        }

        .security-section h3 {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 8px;
        }

        .security-section .description {
            color: var(--gray-600);
            margin-bottom: 24px;
            font-size: 14px;
        }

        /* Alerts */
        .alert {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 24px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 14px;
        }

        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border-left: 3px solid var(--error-red);
            color: var(--error-red);
        }

        .alert-success {
            background: rgba(46, 125, 50, 0.1);
            border-left: 3px solid var(--success-green);
            color: var(--success-green);
        }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.8);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal.active {
            display: flex;
        }

        .modal-content {
            max-width: 90%;
            max-height: 90%;
            position: relative;
        }

        .modal-content img {
            max-width: 100%;
            max-height: 90vh;
            border-radius: 12px;
        }

        .modal-close {
            position: absolute;
            top: -40px;
            right: 0;
            background: none;
            border: none;
            color: white;
            font-size: 28px;
            cursor: pointer;
        }

        /* Hamburger Menu */
        .hamburger {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: var(--gray-700);
        }

        /* Mobile Responsive */
        @media (max-width: 1024px) {
            .sidebar {
                transform: translateX(-100%);
                z-index: 1000;
            }

            .sidebar.mobile-open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .hamburger {
                display: block;
            }
        }

        @media (max-width: 768px) {
            .content-area {
                padding: 20px;
            }

            .top-header {
                padding: 12px 20px;
            }

            .page-title h1 {
                font-size: 20px;
            }

            .profile-header {
                padding: 32px 20px;
            }

            .tabs {
                padding: 0 16px;
                overflow-x: auto;
            }

            .tab {
                padding: 12px 16px;
                white-space: nowrap;
            }

            .tab-content {
                padding: 20px;
            }

            .form-grid {
                grid-template-columns: 1fr;
            }

            .full-width {
                grid-column: span 1;
            }

            .form-actions {
                flex-direction: column;
            }

            .btn-primary,
            .btn-secondary {
                width: 100%;
                text-align: center;
            }
        }
    </style>
    <link rel="stylesheet" href="../assets/css/nexus-theme.css">
</head>

<body>
    <div class="dashboard-wrapper">
        <!-- Sidebar Navigation -->
        <aside class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <a href="dashboard.php" class="logo">
                    <div class="logo-icon">
                        <i class="fas fa-building-columns"></i>
                    </div>
                    <span class="logo-text">Oakshire Finance</span>
                </a>
            </div>

            <div class="profile-section">
                <div class="profile-avatar">
                    <img src="<?= $profilePic ?>" alt="Profile Picture">
                </div>
                <h5><?= htmlspecialchars($user['full_name']) ?></h5>
                <p><?= htmlspecialchars($user['account_number']) ?></p>
            </div>

            <nav class="nav-menu">
                <div class="nav-item">
                    <a href="dashboard.php" class="nav-link">
                        <i class="fas fa-chart-line"></i>
                        <span>Dashboard</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="deposit.php" class="nav-link">
                        <i class="fas fa-arrow-down"></i>
                        <span>Deposit</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="withdraw.php" class="nav-link">
                        <i class="fas fa-arrow-up"></i>
                        <span>Withdraw</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="transfer.php" class="nav-link">
                        <i class="fas fa-exchange-alt"></i>
                        <span>Transfer</span>
                    </a>
                </div>
                <div class="nav-item"><a href="cards.php" class="nav-link "><i class="fas fa-credit-card"></i> My
                        Cards</a></div>
                <div class="nav-item">
                    <a href="transactions.php" class="nav-link">
                        <i class="fas fa-receipt"></i>
                        <span>Transactions</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="investment.php" class="nav-link">
                        <i class="fas fa-chart-pie"></i>
                        <span>Investment</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="loan.php" class="nav-link">
                        <i class="fas fa-hand-holding-usd"></i>
                        <span>Loans</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="profile.php" class="nav-link active">
                        <i class="fas fa-user-circle"></i>
                        <span>Settings</span>
                    </a>
                </div>
            </nav>

            <div class="logout-section">
                <a href="../logout.php" class="logout-btn">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>Logout</span>
                </a>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            <!-- Top Header -->
            <header class="top-header">
                <button class="hamburger" id="hamburger">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="page-title">
                    <h1>Profile Settings</h1>
                </div>
                <div class="user-menu">
                    <button class="notification-btn">
                        <i class="fas fa-bell"></i>
                    </button>
                </div>
            </header>

            <!-- Content Area -->
            <div class="content-area">
                <!-- Profile Card -->
                <div class="profile-card">
                    <div class="profile-header">
                        <div class="profile-avatar-large" id="profileAvatar">
                            <img src="<?= $profilePic ?>" alt="Profile Picture">
                        </div>
                        <h2><?= htmlspecialchars($user['full_name']) ?></h2>
                        <p>Member since <?= date('F Y', strtotime($user['created_at'])) ?></p>
                    </div>

                    <!-- Tabs -->
                    <div class="tabs">
                        <div class="tab <?= $activeTab === 'profile' ? 'active' : '' ?>" data-tab="profile">Edit Profile
                        </div>
                        <div class="tab <?= $activeTab === 'security' ? 'active' : '' ?>" data-tab="security">Security
                        </div>
                    </div>

                    <!-- Alerts -->
                    <?php if ($error): ?>
                        <div style="padding: 0 32px; padding-top: 20px;">
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-circle"></i>
                                <span><?= $error ?></span>
                            </div>
                        </div>
                    <?php endif; ?>

                    <?php if ($success): ?>
                        <div style="padding: 0 32px; padding-top: 20px;">
                            <div class="alert alert-success">
                                <i class="fas fa-check-circle"></i>
                                <span><?= $success ?></span>
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- Profile Tab Content -->
                    <div class="tab-content <?= $activeTab === 'profile' ? 'active' : '' ?>" id="profile-tab">
                        <!-- Upload Profile Picture -->
                        <div class="upload-section">
                            <h3><i class="fas fa-camera"></i> Profile Picture</h3>
                            <div class="upload-area">
                                <form action="upload_picture.php" method="POST" enctype="multipart/form-data"
                                    style="display: flex; gap: 12px; align-items: center; flex-wrap: wrap;">
                                    <input type="file" name="profile_picture" accept="image/*" required
                                        style="padding: 8px;">
                                    <button type="submit" class="upload-btn">
                                        <i class="fas fa-upload"></i> Upload New Picture
                                    </button>
                                </form>
                            </div>
                        </div>

                        <!-- Edit Profile Form -->
                        <form method="POST" id="profileForm">
                            <input type="hidden" name="action" value="update_profile">
                            <input type="hidden" name="profile_token" value="<?= htmlspecialchars($profile_token) ?>">

                            <div class="form-grid">
                                <div class="form-group">
                                    <label>Account Number</label>
                                    <input type="text" value="<?= htmlspecialchars($user['account_number']) ?>"
                                        disabled>
                                </div>
                                <div class="form-group">
                                    <label>Account Status</label>
                                    <input type="text" value="<?= ucfirst($user['status']) ?>" disabled>
                                </div>
                                <div class="form-group">
                                    <label>Full Name</label>
                                    <input type="text" name="full_name" id="full_name"
                                        value="<?= htmlspecialchars($user['full_name']) ?>" disabled>
                                </div>
                                <div class="form-group">
                                    <label>Email Address</label>
                                    <input type="email" name="email" id="email"
                                        value="<?= htmlspecialchars($user['email']) ?>" disabled>
                                </div>
                                <div class="form-group">
                                    <label>Phone Number</label>
                                    <input type="text" name="phone" id="phone"
                                        value="<?= htmlspecialchars($user['phone']) ?>" disabled>
                                </div>
                                <div class="form-group">
                                    <label>Age</label>
                                    <input type="number" name="age" id="age"
                                        value="<?= htmlspecialchars($user['age']) ?>" disabled>
                                </div>
                                <div class="form-group">
                                    <label>Birth Year</label>
                                    <input type="number" name="birth_year" id="birth_year"
                                        value="<?= htmlspecialchars($user['birth_year']) ?>" disabled>
                                </div>
                                <div class="form-group">
                                    <label>Occupation</label>
                                    <input type="text" name="occupation" id="occupation"
                                        value="<?= htmlspecialchars($user['occupation']) ?>" disabled>
                                </div>
                                <div class="form-group full-width">
                                    <label>Address</label>
                                    <textarea name="address" id="address" rows="3"
                                        disabled><?= htmlspecialchars($user['address']) ?></textarea>
                                </div>
                            </div>

                            <div class="form-actions">
                                <button type="button" id="editProfileBtn" class="btn-secondary">
                                    <i class="fas fa-edit"></i> Edit Profile
                                </button>
                                <button type="submit" id="saveProfileBtn" class="btn-primary" style="display: none;">
                                    <i class="fas fa-save"></i> Save Changes
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- Security Tab Content -->
                    <div class="tab-content <?= $activeTab === 'security' ? 'active' : '' ?>" id="security-tab">
                        <div class="security-section">
                            <h3>Change Password</h3>
                            <p class="description">Update your password to keep your account secure. Make sure to use a
                                strong password that's at least 8 characters long with uppercase, lowercase, and
                                numbers.</p>

                            <form method="POST" id="passwordForm">
                                <input type="hidden" name="action" value="change_password">
                                <input type="hidden" name="password_token"
                                    value="<?= htmlspecialchars($password_token) ?>">

                                <div class="form-group">
                                    <label for="current_password">Current Password</label>
                                    <input type="password" id="current_password" name="current_password" required>
                                </div>

                                <div class="form-group">
                                    <label for="new_password">New Password</label>
                                    <input type="password" id="new_password" name="new_password" required>
                                    <small style="display: block; margin-top: 4px; color: var(--gray-500);">
                                        Password must be at least 8 characters with uppercase, lowercase, and numbers
                                    </small>
                                </div>

                                <div class="form-group">
                                    <label for="confirm_password">Confirm New Password</label>
                                    <input type="password" id="confirm_password" name="confirm_password" required>
                                </div>

                                <div class="form-actions">
                                    <button type="submit" class="btn-primary">
                                        <i class="fas fa-key"></i> Change Password
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- Image Modal -->
    <div id="imageModal" class="modal">
        <div class="modal-content">
            <button class="modal-close" onclick="closeModal()">&times;</button>
            <img id="modalImage" src="" alt="Profile Picture">
        </div>
    </div>

    <script>
        // Mobile sidebar toggle
        const hamburger = document.getElementById('hamburger');
        const sidebar = document.getElementById('sidebar');

        if (hamburger) {
            hamburger.addEventListener('click', function () {
                sidebar.classList.toggle('mobile-open');
            });
        }

        // Close sidebar when clicking outside on mobile
        document.addEventListener('click', function (event) {
            if (window.innerWidth <= 1024) {
                const isClickInside = sidebar.contains(event.target) || hamburger.contains(event.target);
                if (!isClickInside && sidebar.classList.contains('mobile-open')) {
                    sidebar.classList.remove('mobile-open');
                }
            }
        });

        // Tab switching
        const tabs = document.querySelectorAll('.tab');
        const tabContents = document.querySelectorAll('.tab-content');

        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                const tabName = tab.getAttribute('data-tab');

                tabs.forEach(t => t.classList.remove('active'));
                tab.classList.add('active');

                tabContents.forEach(content => content.classList.remove('active'));
                document.getElementById(`${tabName}-tab`).classList.add('active');

                // Update URL without reload
                const url = new URL(window.location.href);
                url.searchParams.set('tab', tabName);
                window.history.pushState({}, '', url);
            });
        });

        // Profile edit functionality
        const editBtn = document.getElementById('editProfileBtn');
        const saveBtn = document.getElementById('saveProfileBtn');
        const profileForm = document.getElementById('profileForm');
        const editableFields = ['full_name', 'email', 'phone', 'age', 'birth_year', 'occupation', 'address'];

        if (editBtn && saveBtn) {
            editBtn.addEventListener('click', () => {
                editableFields.forEach(field => {
                    const input = document.getElementById(field);
                    if (input) input.disabled = false;
                });
                editBtn.style.display = 'none';
                saveBtn.style.display = 'inline-flex';
            });
        }

        // Password validation
        const passwordForm = document.getElementById('passwordForm');
        if (passwordForm) {
            passwordForm.addEventListener('submit', function (e) {
                const newPass = document.getElementById('new_password').value;
                const confirmPass = document.getElementById('confirm_password').value;

                if (newPass !== confirmPass) {
                    e.preventDefault();
                    alert('New passwords do not match!');
                    return false;
                }

                if (newPass.length < 8) {
                    e.preventDefault();
                    alert('Password must be at least 8 characters long!');
                    return false;
                }

                if (!/[A-Z]/.test(newPass)) {
                    e.preventDefault();
                    alert('Password must contain at least one uppercase letter!');
                    return false;
                }

                if (!/[a-z]/.test(newPass)) {
                    e.preventDefault();
                    alert('Password must contain at least one lowercase letter!');
                    return false;
                }

                if (!/[0-9]/.test(newPass)) {
                    e.preventDefault();
                    alert('Password must contain at least one number!');
                    return false;
                }
            });
        }

        // Modal functionality
        const modal = document.getElementById('imageModal');
        const modalImage = document.getElementById('modalImage');
        const profileAvatar = document.querySelector('.profile-avatar-large img');

        if (profileAvatar) {
            profileAvatar.addEventListener('click', function () {
                modalImage.src = this.src;
                modal.classList.add('active');
            });
        }

        function closeModal() {
            modal.classList.remove('active');
        }

        modal.addEventListener('click', function (e) {
            if (e.target === modal) {
                closeModal();
            }
        });

        // Auto-dismiss alerts after 5 seconds
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            setTimeout(() => {
                alert.style.transition = 'opacity 0.3s ease';
                alert.style.opacity = '0';
                setTimeout(() => alert.remove(), 300);
            }, 5000);
        });
    </script>
</body>

</html>