<?php
session_start();
require_once 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$error_message = '';
$success_message = '';

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    try {
        $full_name = $conn->real_escape_string(trim($_POST['full_name']));
        $email = $conn->real_escape_string(trim($_POST['email']));
        $phone = $conn->real_escape_string(trim($_POST['phone']));
        $username = $conn->real_escape_string(trim($_POST['username']));
        
        // Validate inputs
        if (empty($full_name) || empty($email) || empty($username)) {
            throw new Exception('Full name, email, and username are required');
        }
        
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new Exception('Please enter a valid email address');
        }
        
        // Check if email or username already exists for other users
        $sql_check = "SELECT user_id FROM users WHERE (email = ? OR username = ?) AND user_id != ?";
        $stmt_check = $conn->prepare($sql_check);
        $stmt_check->bind_param("ssi", $email, $username, $user_id);
        $stmt_check->execute();
        $existing_user = $stmt_check->get_result()->fetch_assoc();
        
        if ($existing_user) {
            throw new Exception('Email or username already exists for another user');
        }
        
        // Update user profile
        $sql_update = "UPDATE users SET full_name = ?, email = ?, phone = ?, username = ? WHERE user_id = ?";
        $stmt_update = $conn->prepare($sql_update);
        $stmt_update->bind_param("ssssi", $full_name, $email, $phone, $username, $user_id);
        
        if ($stmt_update->execute()) {
            // Log activity
            $sql_log = "INSERT INTO activity_log (user_id, action, module, record_id, old_values, new_values, ip_address, user_agent, logged_at) 
                       VALUES (?, 'UPDATE', 'USERS', ?, ?, ?, ?, ?, NOW())";
            $stmt_log = $conn->prepare($sql_log);
            
            $old_values = json_encode(['action' => 'profile_update']);
            $new_values = json_encode(['full_name' => $full_name, 'email' => $email, 'phone' => $phone, 'username' => $username]);
            
            $stmt_log->bind_param("iissss", $user_id, $user_id, $old_values, $new_values, 
                                 $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']);
            $stmt_log->execute();
            
            $success_message = 'Profile updated successfully!';
        } else {
            throw new Exception('Failed to update profile');
        }
        
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// Handle password change
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    try {
        $current_password = $_POST['current_password'];
        $new_password = $_POST['new_password'];
        $confirm_password = $_POST['confirm_password'];
        
        // Validate inputs
        if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
            throw new Exception('All password fields are required');
        }
        
        if ($new_password !== $confirm_password) {
            throw new Exception('New passwords do not match');
        }
        
        if (strlen($new_password) < 6) {
            throw new Exception('New password must be at least 6 characters long');
        }
        
        // Get current password hash
        $sql_current = "SELECT password FROM users WHERE user_id = ?";
        $stmt_current = $conn->prepare($sql_current);
        $stmt_current->bind_param("i", $user_id);
        $stmt_current->execute();
        $current_hash = $stmt_current->get_result()->fetch_assoc()['password'];
        
        // Verify current password
        if (!password_verify($current_password, $current_hash)) {
            throw new Exception('Current password is incorrect');
        }
        
        // Hash new password
        $new_hash = password_hash($new_password, PASSWORD_DEFAULT);
        
        // Update password
        $sql_update_pwd = "UPDATE users SET password = ?, last_password_change = NOW() WHERE user_id = ?";
        $stmt_update_pwd = $conn->prepare($sql_update_pwd);
        $stmt_update_pwd->bind_param("si", $new_hash, $user_id);
        
        if ($stmt_update_pwd->execute()) {
            // Log activity
            $sql_log = "INSERT INTO activity_log (user_id, action, module, record_id, new_values, ip_address, user_agent, logged_at) 
                       VALUES (?, 'UPDATE', 'USERS', ?, ?, ?, ?, NOW())";
            $stmt_log = $conn->prepare($sql_log);
            
            $new_values = json_encode(['action' => 'password_change']);
            
            $stmt_log->bind_param("iisss", $user_id, $user_id, $new_values, 
                                 $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']);
            $stmt_log->execute();
            
            $success_message = 'Password changed successfully!';
        } else {
            throw new Exception('Failed to change password');
        }
        
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// Handle avatar upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_avatar'])) {
    try {
        if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('Please select a valid image file');
        }
        
        $file = $_FILES['avatar'];
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
        $max_size = 2 * 1024 * 1024; // 2MB
        
        // Validate file type
        if (!in_array($file['type'], $allowed_types)) {
            throw new Exception('Only JPEG, PNG, and GIF images are allowed');
        }
        
        // Validate file size
        if ($file['size'] > $max_size) {
            throw new Exception('Image size must be less than 2MB');
        }
        
        // Create upload directory if it doesn't exist
        $upload_dir = 'uploads/avatars/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        
        // Generate unique filename
        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = 'avatar_' . $user_id . '_' . time() . '.' . $extension;
        $filepath = $upload_dir . $filename;
        
        // Move uploaded file
        if (move_uploaded_file($file['tmp_name'], $filepath)) {
            // Update user avatar in database
            $sql_avatar = "UPDATE users SET avatar = ? WHERE user_id = ?";
            $stmt_avatar = $conn->prepare($sql_avatar);
            $stmt_avatar->bind_param("si", $filepath, $user_id);
            
            if ($stmt_avatar->execute()) {
                $success_message = 'Avatar updated successfully!';
            } else {
                throw new Exception('Failed to update avatar in database');
            }
        } else {
            throw new Exception('Failed to upload avatar');
        }
        
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// Get user details
$sql_user = "SELECT 
    u.*,
    ur.role_name,
    ur.description as role_description
FROM users u
INNER JOIN user_roles ur ON u.role_id = ur.role_id
WHERE u.user_id = ?";

$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details) {
    header('Location: logout.php');
    exit();
}

// Get user activity statistics
$sql_stats = "SELECT 
    COUNT(*) as total_logins,
    MAX(logged_at) as last_activity,
    COUNT(CASE WHEN DATE(logged_at) = CURDATE() THEN 1 END) as today_activities,
    COUNT(CASE WHEN logged_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as week_activities
FROM activity_log 
WHERE user_id = ? AND action IN ('LOGIN', 'CREATE', 'UPDATE', 'DELETE')";

$stmt_stats = $conn->prepare($sql_stats);
$stmt_stats->bind_param("i", $user_id);
$stmt_stats->execute();
$user_stats = $stmt_stats->get_result()->fetch_assoc();

// Get recent activity
$sql_recent = "SELECT 
    action,
    module,
    logged_at,
    ip_address
FROM activity_log 
WHERE user_id = ? 
ORDER BY logged_at DESC 
LIMIT 10";

$stmt_recent = $conn->prepare($sql_recent);
$stmt_recent->bind_param("i", $user_id);
$stmt_recent->execute();
$recent_activities = $stmt_recent->get_result();

// Get account security info
$password_age = 0;
if ($user_details['last_password_change']) {
    $password_age = floor((time() - strtotime($user_details['last_password_change'])) / (60 * 60 * 24));
}

$account_age = floor((time() - strtotime($user_details['created_at'])) / (60 * 60 * 24));
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My Profile - Laundry Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .page-content {
            background-color: #f8fafc;
        }
        
        .profile-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .card-header {
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
            padding: 1.5rem;
            border-radius: 12px 12px 0 0;
        }
        
        .card-body {
            padding: 1.5rem;
        }
        
        .card-title {
            font-size: 1.25rem;
            font-weight: 600;
            margin: 0;
            color: #1e293b;
        }
        
        .profile-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            position: relative;
            overflow: hidden;
        }
        
        .profile-header::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 200px;
            height: 200px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
            transform: translate(50px, -50px);
        }
        
        .profile-avatar {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: rgba(255,255,255,0.2);
            backdrop-filter: blur(10px);
            border: 4px solid rgba(255,255,255,0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 3rem;
            font-weight: 700;
            color: white;
            margin-bottom: 1rem;
            position: relative;
            z-index: 2;
            overflow: hidden;
        }
        
        .profile-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 50%;
        }
        
        .profile-info h2 {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
            position: relative;
            z-index: 2;
        }
        
        .profile-meta {
            opacity: 0.9;
            position: relative;
            z-index: 2;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #059669;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            color: #64748b;
            font-size: 0.875rem;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .form-control, .form-select {
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #059669;
            box-shadow: 0 0 0 3px rgba(5, 150, 105, 0.1);
            outline: none;
        }
        
        .btn-primary {
            background: #059669;
            border-color: #059669;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 500;
        }
        
        .btn-primary:hover {
            background: #047857;
            border-color: #047857;
        }
        
        .btn-secondary {
            background: #64748b;
            border-color: #64748b;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 500;
        }
        
        .btn-danger {
            background: #dc2626;
            border-color: #dc2626;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 500;
        }
        
        .alert {
            border-radius: 8px;
            border: none;
            padding: 1rem 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .alert-success {
            background: #f0fdf4;
            color: #166534;
            border-left: 4px solid #059669;
        }
        
        .alert-danger {
            background: #fef2f2;
            color: #991b1b;
            border-left: 4px solid #dc2626;
        }
        
        .activity-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .activity-item:last-child {
            border-bottom: none;
        }
        
        .activity-action {
            font-weight: 600;
            color: #1e293b;
        }
        
        .activity-module {
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .activity-time {
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .security-indicator {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin-bottom: 1rem;
        }
        
        .security-icon {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
        }
        
        .security-good {
            background: #dcfce7;
            color: #166534;
        }
        
        .security-warning {
            background: #fef3c7;
            color: #92400e;
        }
        
        .security-danger {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .nav-tabs {
            border-bottom: 2px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .nav-tabs .nav-link {
            border: none;
            border-bottom: 2px solid transparent;
            color: #64748b;
            font-weight: 500;
            padding: 1rem 1.5rem;
        }
        
        .nav-tabs .nav-link.active {
            color: #059669;
            border-bottom-color: #059669;
            background: none;
        }
        
        .avatar-upload {
            position: relative;
            display: inline-block;
        }
        
        .avatar-upload-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.7);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s;
            cursor: pointer;
        }
        
        .avatar-upload:hover .avatar-upload-overlay {
            opacity: 1;
        }
        
        .file-input-hidden {
            position: absolute;
            opacity: 0;
            width: 0;
            height: 0;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">My Profile</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">My Profile</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Success/Error Messages -->
                    <?php if ($success_message): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle me-2"></i>
                        <?php echo $success_message; ?>
                    </div>
                    <?php endif; ?>

                    <?php if ($error_message): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle me-2"></i>
                        <?php echo $error_message; ?>
                    </div>
                    <?php endif; ?>

                    <!-- Profile Header -->
                    <div class="profile-header">
                        <div class="row align-items-center">
                            <div class="col-md-3 text-center">
                                <div class="avatar-upload">
                                    <div class="profile-avatar">
                                        <?php if ($user_details['avatar'] && file_exists($user_details['avatar'])): ?>
                                            <img src="<?php echo $user_details['avatar']; ?>" alt="Avatar">
                                        <?php else: ?>
                                            <?php echo strtoupper(substr($user_details['full_name'], 0, 2)); ?>
                                        <?php endif; ?>
                                    </div>
                                    <div class="avatar-upload-overlay" onclick="document.getElementById('avatarInput').click()">
                                        <i class="fas fa-camera" style="color: white; font-size: 1.5rem;"></i>
                                    </div>
                                </div>
                                
                                <form method="POST" enctype="multipart/form-data" id="avatarForm">
                                    <input type="file" id="avatarInput" name="avatar" accept="image/*" class="file-input-hidden" onchange="document.getElementById('avatarForm').submit()">
                                    <input type="hidden" name="upload_avatar" value="1">
                                </form>
                            </div>
                            <div class="col-md-9">
                                <div class="profile-info">
                                    <h2><?php echo htmlspecialchars($user_details['full_name']); ?></h2>
                                    <div class="profile-meta">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <p class="mb-1"><i class="fas fa-user-tag me-2"></i><?php echo $user_details['role_name']; ?></p>
                                                <p class="mb-1"><i class="fas fa-envelope me-2"></i><?php echo $user_details['email']; ?></p>
                                                <p class="mb-1"><i class="fas fa-phone me-2"></i><?php echo $user_details['phone'] ?: 'Not provided'; ?></p>
                                            </div>
                                            <div class="col-md-6">
                                                <p class="mb-1"><i class="fas fa-calendar me-2"></i>Joined <?php echo date('M j, Y', strtotime($user_details['created_at'])); ?></p>
                                                <p class="mb-1"><i class="fas fa-clock me-2"></i>Last login: <?php echo $user_details['last_login'] ? date('M j, Y g:i A', strtotime($user_details['last_login'])) : 'Never'; ?></p>
                                                <p class="mb-1"><i class="fas fa-circle text-success me-2"></i>Status: <?php echo ucfirst(strtolower($user_details['status'])); ?></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics -->
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $user_stats['total_logins']; ?></div>
                            <div class="stat-label">Total Activities</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $user_stats['today_activities']; ?></div>
                            <div class="stat-label">Today's Activities</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $user_stats['week_activities']; ?></div>
                            <div class="stat-label">This Week</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $account_age; ?></div>
                            <div class="stat-label">Days Since Joined</div>
                        </div>
                    </div>

                    <!-- Tabs Navigation -->
                    <ul class="nav nav-tabs" id="profileTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile" type="button" role="tab">
                                <i class="fas fa-user me-2"></i>Profile Information
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="security-tab" data-bs-toggle="tab" data-bs-target="#security" type="button" role="tab">
                                <i class="fas fa-shield-alt me-2"></i>Security
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="activity-tab" data-bs-toggle="tab" data-bs-target="#activity" type="button" role="tab">
                                <i class="fas fa-history me-2"></i>Recent Activity
                            </button>
                        </li>
                    </ul>

                    <!-- Tab Content -->
                    <div class="tab-content" id="profileTabContent">
                        <!-- Profile Information Tab -->
                        <div class="tab-pane fade show active" id="profile" role="tabpanel">
                            <div class="row">
                                <div class="col-xl-8">
                                    <div class="profile-card">
                                        <div class="card-header">
                                            <h5 class="card-title">Edit Profile Information</h5>
                                        </div>
                                        <div class="card-body">
                                            <form method="POST">
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="mb-3">
                                                            <label class="form-label">Full Name *</label>
                                                            <input type="text" class="form-control" name="full_name" 
                                                                   value="<?php echo htmlspecialchars($user_details['full_name']); ?>" required>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="mb-3">
                                                            <label class="form-label">Username *</label>
                                                            <input type="text" class="form-control" name="username" 
                                                                   value="<?php echo htmlspecialchars($user_details['username']); ?>" required>
                                                        </div>
                                                    </div>
                                                </div>

                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="mb-3">
                                                            <label class="form-label">Email Address *</label>
                                                            <input type="email" class="form-control" name="email" 
                                                                   value="<?php echo htmlspecialchars($user_details['email']); ?>" required>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="mb-3">
                                                            <label class="form-label">Phone Number</label>
                                                            <input type="tel" class="form-control" name="phone" 
                                                                   value="<?php echo htmlspecialchars($user_details['phone']); ?>">
                                                        </div>
                                                    </div>
                                                </div>

                                                <div class="d-flex gap-2">
                                                    <button type="submit" name="update_profile" class="btn btn-primary">
                                                        <i class="fas fa-save me-2"></i>Update Profile
                                                    </button>
                                                    <button type="reset" class="btn btn-secondary">
                                                        <i class="fas fa-undo me-2"></i>Reset
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-xl-4">
                                    <div class="profile-card">
                                        <div class="card-header">
                                            <h5 class="card-title">Account Information</h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="mb-3">
                                                <label class="form-label">User Role</label>
                                                <input type="text" class="form-control" value="<?php echo $user_details['role_name']; ?>" readonly>
                                                <div class="form-text"><?php echo $user_details['role_description']; ?></div>
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label">Account Status</label>
                                                <input type="text" class="form-control" value="<?php echo ucfirst(strtolower($user_details['status'])); ?>" readonly>
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label">Member Since</label>
                                                <input type="text" class="form-control" value="<?php echo date('F j, Y', strtotime($user_details['created_at'])); ?>" readonly>
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label">User ID</label>
                                                <input type="text" class="form-control" value="#<?php echo str_pad($user_details['user_id'], 4, '0', STR_PAD_LEFT); ?>" readonly>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Security Tab -->
                        <div class="tab-pane fade" id="security" role="tabpanel">
                            <div class="row">
                                <div class="col-xl-8">
                                    <div class="profile-card">
                                        <div class="card-header">
                                            <h5 class="card-title">Change Password</h5>
                                        </div>
                                        <div class="card-body">
                                            <form method="POST" id="passwordForm">
                                                <div class="mb-3">
                                                    <label class="form-label">Current Password *</label>
                                                    <input type="password" class="form-control" name="current_password" required>
                                                </div>

                                                <div class="mb-3">
                                                    <label class="form-label">New Password *</label>
                                                    <input type="password" class="form-control" name="new_password" id="newPassword" required>
                                                    <div class="form-text">Password must be at least 6 characters long</div>
                                                </div>

                                                <div class="mb-3">
                                                    <label class="form-label">Confirm New Password *</label>
                                                    <input type="password" class="form-control" name="confirm_password" id="confirmPassword" required>
                                                    <div id="passwordMatch" class="form-text"></div>
                                                </div>

                                                <div class="d-flex gap-2">
                                                    <button type="submit" name="change_password" class="btn btn-danger">
                                                        <i class="fas fa-key me-2"></i>Change Password
                                                    </button>
                                                    <button type="reset" class="btn btn-secondary">
                                                        <i class="fas fa-times me-2"></i>Cancel
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-xl-4">
                                    <div class="profile-card">
                                        <div class="card-header">
                                            <h5 class="card-title">Security Status</h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="security-indicator">
                                                <?php if ($password_age <= 90): ?>
                                                <div class="security-icon security-good">✓</div>
                                                <div>
                                                    <div class="fw-semibold">Password Fresh</div>
                                                    <div class="text-muted small">Changed <?php echo $password_age; ?> days ago</div>
                                                </div>
                                                <?php elseif ($password_age <= 180): ?>
                                                <div class="security-icon security-warning">!</div>
                                                <div>
                                                    <div class="fw-semibold">Password Aging</div>
                                                    <div class="text-muted small">Changed <?php echo $password_age; ?> days ago</div>
                                                </div>
                                                <?php else: ?>
                                                <div class="security-icon security-danger">⚠</div>
                                                <div>
                                                    <div class="fw-semibold">Password Old</div>
                                                    <div class="text-muted small">Changed <?php echo $password_age; ?> days ago</div>
                                                </div>
                                                <?php endif; ?>
                                            </div>

                                            <div class="security-indicator">
                                                <?php if ($user_details['failed_attempts'] == 0): ?>
                                                <div class="security-icon security-good">✓</div>
                                                <div>
                                                    <div class="fw-semibold">No Failed Attempts</div>
                                                    <div class="text-muted small">Account secure</div>
                                                </div>
                                                <?php elseif ($user_details['failed_attempts'] <= 3): ?>
                                                <div class="security-icon security-warning">!</div>
                                                <div>
                                                    <div class="fw-semibold"><?php echo $user_details['failed_attempts']; ?> Failed Attempts</div>
                                                    <div class="text-muted small">Monitor account security</div>
                                                </div>
                                                <?php else: ?>
                                                <div class="security-icon security-danger">⚠</div>
                                                <div>
                                                    <div class="fw-semibold"><?php echo $user_details['failed_attempts']; ?> Failed Attempts</div>
                                                    <div class="text-muted small">High security risk</div>
                                                </div>
                                                <?php endif; ?>
                                            </div>

                                            <div class="security-indicator">
                                                <?php if ($user_details['status'] === 'ACTIVE'): ?>
                                                <div class="security-icon security-good">✓</div>
                                                <div>
                                                    <div class="fw-semibold">Account Active</div>
                                                    <div class="text-muted small">Full access enabled</div>
                                                </div>
                                                <?php else: ?>
                                                <div class="security-icon security-danger">⚠</div>
                                                <div>
                                                    <div class="fw-semibold">Account <?php echo ucfirst(strtolower($user_details['status'])); ?></div>
                                                    <div class="text-muted small">Contact administrator</div>
                                                </div>
                                                <?php endif; ?>
                                            </div>

                                            <hr>

                                            <h6 class="mb-3">Security Recommendations</h6>
                                            <ul class="list-unstyled mb-0">
                                                <li class="mb-2">
                                                    <i class="fas fa-check text-success me-2"></i>
                                                    Use a strong, unique password
                                                </li>
                                                <li class="mb-2">
                                                    <i class="fas fa-check text-success me-2"></i>
                                                    Change password every 90 days
                                                </li>
                                                <li class="mb-2">
                                                    <i class="fas fa-check text-success me-2"></i>
                                                    Log out from shared computers
                                                </li>
                                                <li class="mb-2">
                                                    <i class="fas fa-check text-success me-2"></i>
                                                    Report suspicious activity
                                                </li>
                                                <li class="mb-0">
                                                    <i class="fas fa-check text-success me-2"></i>
                                                    Keep contact info updated
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Activity Tab -->
                        <div class="tab-pane fade" id="activity" role="tabpanel">
                            <div class="row">
                                <div class="col-xl-8">
                                    <div class="profile-card">
                                        <div class="card-header">
                                            <h5 class="card-title">Recent Activity</h5>
                                        </div>
                                        <div class="card-body">
                                            <?php if ($recent_activities->num_rows > 0): ?>
                                                <?php while ($activity = $recent_activities->fetch_assoc()): ?>
                                                <div class="activity-item">
                                                    <div>
                                                        <div class="activity-action">
                                                            <?php 
                                                            $action_text = match($activity['action']) {
                                                                'LOGIN' => 'Logged into system',
                                                                'CREATE' => 'Created new record',
                                                                'UPDATE' => 'Updated record',
                                                                'DELETE' => 'Deleted record',
                                                                'EXPORT' => 'Exported data',
                                                                'IMPORT' => 'Imported data',
                                                                default => ucfirst(strtolower($activity['action']))
                                                            };
                                                            echo $action_text;
                                                            ?>
                                                        </div>
                                                        <div class="activity-module">
                                                            Module: <?php echo ucfirst(strtolower(str_replace('_', ' ', $activity['module']))); ?>
                                                        </div>
                                                        <div class="text-muted small">
                                                            IP: <?php echo $activity['ip_address']; ?>
                                                        </div>
                                                    </div>
                                                    <div class="activity-time">
                                                        <?php echo date('M j, g:i A', strtotime($activity['logged_at'])); ?>
                                                    </div>
                                                </div>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <div class="text-center py-4">
                                                    <i class="fas fa-history fa-3x text-muted mb-3"></i>
                                                    <p class="text-muted">No recent activity found</p>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-xl-4">
                                    <div class="profile-card">
                                        <div class="card-header">
                                            <h5 class="card-title">Activity Summary</h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="mb-3">
                                                <div class="d-flex justify-content-between mb-1">
                                                    <span class="fw-semibold">Total Activities</span>
                                                    <span><?php echo $user_stats['total_logins']; ?></span>
                                                </div>
                                                <div class="progress" style="height: 6px;">
                                                    <div class="progress-bar bg-primary" style="width: 100%"></div>
                                                </div>
                                            </div>

                                            <div class="mb-3">
                                                <div class="d-flex justify-content-between mb-1">
                                                    <span class="fw-semibold">This Week</span>
                                                    <span><?php echo $user_stats['week_activities']; ?></span>
                                                </div>
                                                <div class="progress" style="height: 6px;">
                                                    <div class="progress-bar bg-success" style="width: <?php echo min(100, ($user_stats['week_activities'] / max(1, $user_stats['total_logins'])) * 100); ?>%"></div>
                                                </div>
                                            </div>

                                            <div class="mb-3">
                                                <div class="d-flex justify-content-between mb-1">
                                                    <span class="fw-semibold">Today</span>
                                                    <span><?php echo $user_stats['today_activities']; ?></span>
                                                </div>
                                                <div class="progress" style="height: 6px;">
                                                    <div class="progress-bar bg-warning" style="width: <?php echo min(100, ($user_stats['today_activities'] / max(1, $user_stats['week_activities'])) * 100); ?>%"></div>
                                                </div>
                                            </div>

                                            <hr>

                                            <div class="text-center">
                                                <div class="mb-2">
                                                    <strong>Last Activity</strong>
                                                </div>
                                                <div class="text-muted">
                                                    <?php if ($user_stats['last_activity']): ?>
                                                        <?php echo date('M j, Y g:i A', strtotime($user_stats['last_activity'])); ?>
                                                    <?php else: ?>
                                                        No activity recorded
                                                    <?php endif; ?>
                                                </div>
                                            </div>

                                            <hr>

                                            <div class="text-center">
                                                <a href="activity_logs.php?user_id=<?php echo $user_id; ?>" class="btn btn-outline-primary btn-sm">
                                                    <i class="fas fa-external-link-alt me-1"></i>View Full Activity Log
                                                </a>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Quick Actions -->
                                    <div class="profile-card">
                                        <div class="card-header">
                                            <h5 class="card-title">Quick Actions</h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="d-grid gap-2">
                                                <a href="change_password.php" class="btn btn-outline-warning btn-sm">
                                                    <i class="fas fa-key me-2"></i>Change Password
                                                </a>
                                                <a href="download_data.php" class="btn btn-outline-info btn-sm">
                                                    <i class="fas fa-download me-2"></i>Download My Data
                                                </a>
                                                <a href="privacy_settings.php" class="btn btn-outline-secondary btn-sm">
                                                    <i class="fas fa-shield-alt me-2"></i>Privacy Settings
                                                </a>
                                                <hr>
                                                <a href="logout.php" class="btn btn-outline-danger btn-sm">
                                                    <i class="fas fa-sign-out-alt me-2"></i>Logout
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        // Password confirmation validation
        document.addEventListener('DOMContentLoaded', function() {
            const newPassword = document.getElementById('newPassword');
            const confirmPassword = document.getElementById('confirmPassword');
            const passwordMatch = document.getElementById('passwordMatch');
            const passwordForm = document.getElementById('passwordForm');

            function checkPasswordMatch() {
                if (confirmPassword.value === '') {
                    passwordMatch.textContent = '';
                    passwordMatch.className = 'form-text';
                    return;
                }

                if (newPassword.value === confirmPassword.value) {
                    passwordMatch.textContent = '✓ Passwords match';
                    passwordMatch.className = 'form-text text-success';
                } else {
                    passwordMatch.textContent = '✗ Passwords do not match';
                    passwordMatch.className = 'form-text text-danger';
                }
            }

            if (newPassword && confirmPassword) {
                newPassword.addEventListener('input', checkPasswordMatch);
                confirmPassword.addEventListener('input', checkPasswordMatch);

                passwordForm.addEventListener('submit', function(e) {
                    if (newPassword.value !== confirmPassword.value) {
                        e.preventDefault();
                        alert('Passwords do not match');
                        return false;
                    }

                    if (newPassword.value.length < 6) {
                        e.preventDefault();
                        alert('Password must be at least 6 characters long');
                        return false;
                    }

                    if (!confirm('Are you sure you want to change your password?')) {
                        e.preventDefault();
                        return false;
                    }
                });
            }

            // Avatar preview
            const avatarInput = document.getElementById('avatarInput');
            if (avatarInput) {
                avatarInput.addEventListener('change', function(e) {
                    const file = e.target.files[0];
                    if (file) {
                        // Validate file type
                        const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
                        if (!allowedTypes.includes(file.type)) {
                            alert('Only JPEG, PNG, and GIF images are allowed');
                            this.value = '';
                            return;
                        }

                        // Validate file size (2MB)
                        if (file.size > 2 * 1024 * 1024) {
                            alert('Image size must be less than 2MB');
                            this.value = '';
                            return;
                        }

                        // Preview image
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            const avatar = document.querySelector('.profile-avatar');
                            avatar.innerHTML = '<img src="' + e.target.result + '" alt="Avatar" style="width: 100%; height: 100%; object-fit: cover; border-radius: 50%;">';
                        };
                        reader.readAsDataURL(file);
                    }
                });
            }

            // Form validation
            const profileForm = document.querySelector('form[method="POST"]:not(#passwordForm):not(#avatarForm)');
            if (profileForm) {
                profileForm.addEventListener('submit', function(e) {
                    const fullName = this.querySelector('input[name="full_name"]').value.trim();
                    const email = this.querySelector('input[name="email"]').value.trim();
                    const username = this.querySelector('input[name="username"]').value.trim();

                    if (!fullName || !email || !username) {
                        e.preventDefault();
                        alert('Please fill in all required fields');
                        return false;
                    }

                    // Basic email validation
                    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailRegex.test(email)) {
                        e.preventDefault();
                        alert('Please enter a valid email address');
                        return false;
                    }

                    // Username validation (alphanumeric and underscore only)
                    const usernameRegex = /^[a-zA-Z0-9_]+$/;
                    if (!usernameRegex.test(username)) {
                        e.preventDefault();
                        alert('Username can only contain letters, numbers, and underscores');
                        return false;
                    }
                });
            }

            // Auto-hide alerts after 5 seconds
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                setTimeout(function() {
                    alert.style.transition = 'opacity 0.5s';
                    alert.style.opacity = '0';
                    setTimeout(function() {
                        alert.remove();
                    }, 500);
                }, 5000);
            });
        });

        // Tab persistence
        document.addEventListener('DOMContentLoaded', function() {
            // Get the last active tab from localStorage
            const lastActiveTab = localStorage.getItem('profileActiveTab');
            if (lastActiveTab) {
                const tabTrigger = document.querySelector(`button[data-bs-target="${lastActiveTab}"]`);
                if (tabTrigger) {
                    const tab = new bootstrap.Tab(tabTrigger);
                    tab.show();
                }
            }

            // Save active tab to localStorage
            const tabButtons = document.querySelectorAll('#profileTabs button[data-bs-toggle="tab"]');
            tabButtons.forEach(function(button) {
                button.addEventListener('shown.bs.tab', function(e) {
                    localStorage.setItem('profileActiveTab', e.target.dataset.bsTarget);
                });
            });
        });
    </script>
</body>
</html>