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

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

// Get user ID from session
$user_id = $_SESSION['user_id'];

// Initialize variables for form submission status
$success_message = "";
$error_message = "";
$password_success = "";
$password_error = "";
$avatar_success = "";
$avatar_error = "";

// Get user details
$sql = "SELECT u.*, ur.role_name 
        FROM users u 
        LEFT JOIN user_role ur ON u.role_id = ur.role_id 
        WHERE u.user_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    header('Location: logout.php');
    exit();
}

$user = $result->fetch_assoc();

// Process profile update form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $time_zone = isset($_POST['time_zone']) ? trim($_POST['time_zone']) : 'UTC';
    $email_notifications = isset($_POST['email_notifications']) ? 1 : 0;
    $chat_notifications = isset($_POST['chat_notifications']) ? 1 : 0;

    // Validate inputs
    if (empty($full_name) || empty($email)) {
        $error_message = "Full name and email are required";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_message = "Invalid email format";
    } else {
        // Check if email already exists for another user
        $check_sql = "SELECT user_id FROM users WHERE email = ? AND user_id != ?";
        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->bind_param("si", $email, $user_id);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        if ($check_result->num_rows > 0) {
            $error_message = "Email already exists for another user";
        } else {
            // Update user profile
            $update_sql = "UPDATE users SET 
                           full_name = ?, 
                           email = ?, 
                           phone = ?, 
                           time_zone = ?, 
                           email_notifications = ?, 
                           chat_notifications = ? 
                           WHERE user_id = ?";
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param("ssssiis", $full_name, $email, $phone, $time_zone, $email_notifications, $chat_notifications, $user_id);
            
            if ($update_stmt->execute()) {
                $success_message = "Profile updated successfully";
                
                // Update session variables
                $_SESSION['full_name'] = $full_name;
                $_SESSION['email'] = $email;
                
                // Refresh user data
                $stmt->execute();
                $result = $stmt->get_result();
                $user = $result->fetch_assoc();
            } else {
                $error_message = "Error updating profile: " . $conn->error;
            }
        }
    }
}

// Process password change form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $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)) {
        $password_error = "All password fields are required";
    } elseif ($new_password !== $confirm_password) {
        $password_error = "New passwords do not match";
    } elseif (strlen($new_password) < 8) {
        $password_error = "Password must be at least 8 characters long";
    } else {
        // Verify current password
        if (password_verify($current_password, $user['password'])) {
            // Hash new password
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            
            // Update password
            $update_sql = "UPDATE users SET 
                           password = ?, 
                           last_password_change = CURRENT_TIMESTAMP 
                           WHERE user_id = ?";
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param("si", $hashed_password, $user_id);
            
            if ($update_stmt->execute()) {
                $password_success = "Password changed successfully";
            } else {
                $password_error = "Error changing password: " . $conn->error;
            }
        } else {
            $password_error = "Current password is incorrect";
        }
    }
}

// Process profile picture upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_avatar'])) {
    if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
        $max_size = 2 * 1024 * 1024; // 2MB
        
        if (!in_array($_FILES['avatar']['type'], $allowed_types)) {
            $avatar_error = "Only JPG, PNG and GIF images are allowed";
        } elseif ($_FILES['avatar']['size'] > $max_size) {
            $avatar_error = "Image size should be less than 2MB";
        } else {
            // Create uploads directory if it doesn't exist
            $upload_dir = 'assets/images/avatars/';
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            // Generate unique filename
            $file_extension = pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION);
            $filename = 'avatar_' . $user_id . '_' . time() . '.' . $file_extension;
            $target_file = $upload_dir . $filename;
            
            // Move uploaded file
            if (move_uploaded_file($_FILES['avatar']['tmp_name'], $target_file)) {
                // Delete old avatar if exists
                if (!empty($user['avatar']) && file_exists($user['avatar']) && $user['avatar'] != 'assets/images/avatars/default.png') {
                    unlink($user['avatar']);
                }
                
                // Update user avatar in database
                $update_sql = "UPDATE users SET avatar = ? WHERE user_id = ?";
                $update_stmt = $conn->prepare($update_sql);
                $update_stmt->bind_param("si", $target_file, $user_id);
                
                if ($update_stmt->execute()) {
                    $avatar_success = "Profile picture updated successfully";
                    
                    // Update user data
                    $user['avatar'] = $target_file;
                } else {
                    $avatar_error = "Error updating profile picture in database";
                }
            } else {
                $avatar_error = "Error uploading file";
            }
        }
    } else {
        $avatar_error = "No file uploaded or an error occurred";
    }
}

// Get last login time
$last_login_query = "SELECT login_date FROM login_activity_log WHERE user_id = ? ORDER BY login_date DESC LIMIT 1";
$last_login_stmt = $conn->prepare($last_login_query);
$last_login_stmt->bind_param("i", $user_id);
$last_login_stmt->execute();
$last_login_result = $last_login_stmt->get_result();
$last_login = $last_login_result->num_rows > 0 ? $last_login_result->fetch_assoc()['login_date'] : 'N/A';

// Get recent activity
$activity_query = "SELECT a.*, n.message FROM admin_logs a
                  LEFT JOIN notif_messages n ON a.action = n.type
                  WHERE a.user_id = ? 
                  ORDER BY a.created_at DESC LIMIT 5";
$activity_stmt = $conn->prepare($activity_query);
$activity_stmt->bind_param("i", $user_id);
$activity_stmt->execute();
$activity_result = $activity_stmt->get_result();
$recent_activities = [];
while ($row = $activity_result->fetch_assoc()) {
    $recent_activities[] = $row;
}

// Default avatar if none is set
if (empty($user['avatar'])) {
    $user['avatar'] = 'assets/images/avatars/default.png';
}

// Time zone options
$timezones = [
    'UTC' => 'UTC',
    'Africa/Dar_es_Salaam' => 'East Africa Time (EAT)',
    'Africa/Nairobi' => 'Nairobi',
    'Africa/Johannesburg' => 'South Africa Standard Time',
    'Africa/Cairo' => 'Eastern European Time (Cairo)',
    'Africa/Lagos' => 'West Africa Time',
    'Africa/Casablanca' => 'Western European Time (Casablanca)',
    'Europe/London' => 'Greenwich Mean Time (GMT)',
    'America/New_York' => 'Eastern Time (US & Canada)',
    'America/Chicago' => 'Central Time (US & Canada)',
    'America/Denver' => 'Mountain Time (US & Canada)',
    'America/Los_Angeles' => 'Pacific Time (US & Canada)',
    'Asia/Dubai' => 'Gulf Standard Time (Dubai)',
    'Asia/Kolkata' => 'India Standard Time',
    'Asia/Tokyo' => 'Japan Standard Time',
    'Australia/Sydney' => 'Australian Eastern Time'
];
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My Profile')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <!-- Custom CSS for profile page -->
    <style>
        /* Profile header styles */
        .profile-header {
            position: relative;
            background: linear-gradient(to right, #4a6cf7, #2651f3);
            border-radius: 0.5rem;
            padding: 2rem;
            margin-bottom: 2rem;
            color: #fff;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
            overflow: hidden;
        }
        
        .profile-image-container {
            position: relative;
            margin-right: 1.5rem;
            z-index: 1;
        }
        
        .profile-image {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border: 4px solid #fff;
            border-radius: 50%;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
            transition: all 0.3s ease;
        }
        
        .profile-image-edit {
            position: absolute;
            bottom: 0;
            right: 0;
            background: #fff;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            color: #555;
            transition: all 0.3s;
            z-index: 2;
        }
        
        .profile-info {
            z-index: 1;
            position: relative;
        }
        
        .profile-name {
            margin-bottom: 0.25rem;
            font-weight: 600;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }
        
        .profile-role {
            margin-bottom: 0.5rem;
            opacity: 0.9;
        }
        
        .profile-username {
            color: #4a6cf7;
            border: 1px solid #4a6cf7;
            background-color: transparent;
            padding: 0.25em 0.4em;
            font-size: 75%;
            font-weight: 700;
            line-height: 1;
            text-align: center;
            white-space: nowrap;
            vertical-align: baseline;
            border-radius: 0.25rem;
            margin-right: 0.5rem;
        }
        
        .profile-decoration-circle-1 {
            position: absolute;
            top: -50px;
            right: -50px;
            width: 150px;
            height: 150px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.1);
            z-index: 0;
        }
        
        .profile-decoration-circle-2 {
            position: absolute;
            bottom: -70px;
            left: -70px;
            width: 200px;
            height: 200px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.1);
            z-index: 0;
        }
        
        /* Tab navigation styles */
        .profile-tabs-container {
            background: #fff;
            border-radius: 0.5rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            margin-bottom: 1.5rem;
            overflow: hidden;
        }
        
        .profile-tabs {
            border-bottom: none;
            padding: 0 1rem;
        }
        
        .profile-tabs .nav-link {
            padding: 1rem;
            color: #6c757d;
            border: none;
            border-bottom: 2px solid transparent;
            border-radius: 0;
            font-weight: 500;
        }
        
        .profile-tabs .nav-link.active {
            border-bottom: 2px solid #4a6cf7;
            color: #4a6cf7;
        }
        
        /* Card styles */
        .profile-card {
            border: none;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            margin-bottom: 1.5rem;
        }
        
        .profile-card-header {
            background-color: transparent;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            padding: 1.25rem 1.5rem;
        }
        
        .profile-card-body {
            padding: 1.5rem;
        }
        
        /* Activity card */
        .activity-item {
            padding: 1rem;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }
        
        .activity-item:last-child {
            border-bottom: none;
        }
        
        .activity-icon {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            margin-right: 1rem;
        }
        
        /* Stats chart container */
        .stats-chart-container {
            position: relative;
            height: 300px;
            margin-bottom: 1.5rem;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'User', 'title' => 'My Profile')); ?>
                    
                    <!-- Profile Header -->
                    <div class="profile-header">
                        <div class="d-flex align-items-center flex-wrap">
                            <div class="profile-image-container">
                                <img src="<?php echo htmlspecialchars($user['avatar']); ?>" alt="Profile Picture" class="profile-image">
                                <div class="profile-image-edit" data-bs-toggle="modal" data-bs-target="#uploadAvatarModal">
                                    <i class="ri-camera-line"></i>
                                </div>
                            </div>
                            <div class="profile-info">
                                <h4 class="profile-name"><?php echo htmlspecialchars($user['full_name']); ?></h4>
                                <p class="profile-role"><?php echo htmlspecialchars($user['role_name']); ?></p>
                                <div class="d-flex align-items-center">
                                    <span class="profile-username"><?php echo htmlspecialchars($user['username']); ?></span>
                                    <?php if ($user['verified'] == 1): ?>
                                        <span class="badge bg-success">Verified</span>
                                    <?php else: ?>
                                        <span class="badge bg-warning">Unverified</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <!-- Decorative elements -->
                        <div class="profile-decoration-circle-1"></div>
                        <div class="profile-decoration-circle-2"></div>
                    </div>
                    
                    <!-- Profile Navigation Tabs -->
                    <div class="profile-tabs-container">
                        <ul class="nav nav-tabs profile-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" aria-controls="profile" aria-selected="true">
                                    <i class="ri-user-3-line me-1"></i> Personal Info
                                </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" aria-controls="security" aria-selected="false">
                                    <i class="ri-lock-line me-1"></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" aria-controls="activity" aria-selected="false">
                                    <i class="ri-history-line me-1"></i> Activity
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="stats-tab" data-bs-toggle="tab" data-bs-target="#stats" type="button" role="tab" aria-controls="stats" aria-selected="false">
                                    <i class="ri-bar-chart-2-line me-1"></i> Statistics
                                </button>
                            </li>
                        </ul>
                    </div>
                    
                    <!-- Profile Content -->
                    <div class="tab-content" id="profileTabsContent">
                        <!-- Personal Info Tab -->
                        <div class="tab-pane fade show active" id="profile" role="tabpanel" aria-labelledby="profile-tab">
                            <div class="row">
                                <div class="col-lg-8">
                                    <!-- Profile Information Form -->
                                    <div class="card profile-card">
                                        <div class="card-header profile-card-header d-flex justify-content-between align-items-center">
                                            <h5 class="card-title mb-0">Profile Information</h5>
                                            <span class="text-muted small">Last updated: 
                                                <?php echo date('M d, Y', strtotime($user['last_password_change'])); ?>
                                            </span>
                                        </div>
                                        <div class="card-body profile-card-body">
                                            <?php if (!empty($success_message)): ?>
                                                <div class="alert alert-success alert-dismissible fade show" role="alert">
                                                    <?php echo $success_message; ?>
                                                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($error_message)): ?>
                                                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                                    <?php echo $error_message; ?>
                                                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <form method="POST" action="">
                                                <div class="mb-3">
                                                    <label for="username" class="form-label">Username</label>
                                                    <input type="text" class="form-control" id="username" value="<?php echo htmlspecialchars($user['username']); ?>" readonly>
                                                    <small class="text-muted">Username cannot be changed</small>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="full_name" class="form-label">Full Name <span class="text-danger">*</span></label>
                                                    <input type="text" class="form-control" id="full_name" name="full_name" value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="email" class="form-label">Email Address <span class="text-danger">*</span></label>
                                                    <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="phone" class="form-label">Phone Number</label>
                                                    <input type="text" class="form-control" id="phone" name="phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>">
                                                </div>
                                                <div class="mb-3">
                                                    <label for="time_zone" class="form-label">Time Zone</label>
                                                    <select class="form-select" id="time_zone" name="time_zone">
                                                        <?php foreach ($timezones as $tz_value => $tz_label): ?>
                                                            <option value="<?php echo $tz_value; ?>" <?php echo (($user['time_zone'] ?? 'UTC') == $tz_value) ? 'selected' : ''; ?>>
                                                                <?php echo $tz_label; ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="mb-3">
                                                    <label class="form-label">Notification Preferences</label>
                                                    <div class="form-check mb-2">
                                                        <input class="form-check-input" type="checkbox" id="email_notifications" name="email_notifications" <?php echo (($user['email_notifications'] ?? 1) == 1) ? 'checked' : ''; ?>>
                                                        <label class="form-check-label" for="email_notifications">
                                                            Email Notifications
                                                        </label>
                                                        <small class="d-block text-muted">Receive notifications and updates via email</small>
                                                    </div>
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" id="chat_notifications" name="chat_notifications" <?php echo (($user['chat_notifications'] ?? 1) == 1) ? 'checked' : ''; ?>>
                                                        <label class="form-check-label" for="chat_notifications">
                                                            In-App Chat Notifications
                                                        </label>
                                                        <small class="d-block text-muted">Receive chat notifications while using the application</small>
                                                    </div>
                                                </div>
                                                <button type="submit" name="update_profile" class="btn btn-primary">Save Changes</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-lg-4">
                                    <!-- Account Details -->
                                    <div class="card profile-card">
                                        <div class="card-header profile-card-header">
                                            <h5 class="card-title mb-0">Account Details</h5>
                                        </div>
                                        <div class="card-body profile-card-body">
                                            <div class="mb-3">
                                                <h6 class="text-muted mb-1">User ID</h6>
                                                <p class="mb-0"><?php echo $user['user_id']; ?></p>
                                            </div>
                                            <div class="mb-3">
                                                <h6 class="text-muted mb-1">Account Type</h6>
                                                <p class="mb-0"><?php echo htmlspecialchars($user['role_name']); ?></p>
                                            </div>
                                            <div class="mb-3">
                                                <h6 class="text-muted mb-1">Account Status</h6>
                                                <?php if ($user['verified'] == 1): ?>
                                                    <span class="badge bg-success">Active</span>
                                                <?php else: ?>
                                                    <span class="badge bg-warning">Pending Verification</span>
                                                <?php endif; ?>
                                            </div>
                                            <div class="mb-3">
                                                <h6 class="text-muted mb-1">Created At</h6>
                                                <p class="mb-0"><?php echo date('F d, Y', strtotime($user['created_at'])); ?></p>
                                            </div>
                                            <div class="mb-0">
                                                <h6 class="text-muted mb-1">Last Login</h6>
                                                <p class="mb-0">
                                                    <?php echo ($last_login != 'N/A') ? date('F d, Y h:i A', strtotime($last_login)) : 'N/A'; ?>
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Security Tab -->
                        <div class="tab-pane fade" id="security" role="tabpanel" aria-labelledby="security-tab">
                            <div class="row">
                                <div class="col-lg-8">
                                    <!-- Change Password Form -->
                                    <div class="card profile-card">
                                        <div class="card-header profile-card-header">
                                            <h5 class="card-title mb-0">Change Password</h5>
                                        </div>
                                        <div class="card-body profile-card-body">
                                            <?php if (!empty($password_success)): ?>
                                                <div class="alert alert-success alert-dismissible fade show" role="alert">
                                                    <?php echo $password_success; ?>
                                                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($password_error)): ?>
                                                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                                    <?php echo $password_error; ?>
                                                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <form method="POST" action="">
                                                <div class="mb-3">
                                                    <label for="current_password" class="form-label">Current Password <span class="text-danger">*</span></label>
                                                    <input type="password" class="form-control" id="current_password" name="current_password" required>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="new_password" class="form-label">New Password <span class="text-danger">*</span></label>
                                                    <input type="password" class="form-control" id="new_password" name="new_password" required>
                                                    <small class="text-muted">Password must be at least 8 characters long</small>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="confirm_password" class="form-label">Confirm New Password <span class="text-danger">*</span></label>
                                                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                                                </div>
                                                <button type="submit" name="change_password" class="btn btn-primary">Change Password</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-lg-4">
                                    <!-- Password Policy -->
                                    <div class="card profile-card">
                                        <div class="card-header profile-card-header">
                                            <h5 class="card-title mb-0">Password Policy</h5>
                                        </div>
                                        <div class="card-body profile-card-body">
                                            <ul class="list-unstyled mb-0">
                                                <li class="mb-2">
                                                    <i class="ri-checkbox-circle-fill text-success me-2"></i>
                                                    Minimum 8 characters
                                                </li>
                                                <li class="mb-2">
                                                    <i class="ri-checkbox-circle-fill text-success me-2"></i>
                                                    At least one uppercase letter
                                                </li>
                                                <li class="mb-2">
                                                    <i class="ri-checkbox-circle-fill text-success me-2"></i>
                                                    At least one lowercase letter
                                                </li>
                                                <li class="mb-2">
                                                    <i class="ri-checkbox-circle-fill text-success me-2"></i>
                                                    At least one number
                                                </li>
                                                <li class="mb-0">
                                                    <i class="ri-checkbox-circle-fill text-success me-2"></i>
                                                    At least one special character
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                    
                                    <!-- Account Security -->
                                    <div class="card profile-card">
                                        <div class="card-header profile-card-header">
                                            <h5 class="card-title mb-0">Login Activity</h5>
                                        </div>
                                        <div class="card-body profile-card-body">
                                            <div class="mb-3">
                                                <h6 class="text-muted mb-1">Last Password Change</h6>
                                                <p class="mb-0">
                                                    <?php echo date('F d, Y', strtotime($user['last_password_change'])); ?>
                                                </p>
                                            </div>
                                            <div class="mb-3">
                                                <h6 class="text-muted mb-1">Failed Login Attempts</h6>
                                                <p class="mb-0">
                                                    <?php echo $user['failed_attempts']; ?> attempt(s)
                                                </p>
                                            </div>
                                            <div class="mb-0">
                                                <h6 class="text-muted mb-1">Last Active</h6>
                                                <p class="mb-0">
                                                    <?php echo (!empty($user['last_active'])) ? date('F d, Y h:i A', strtotime($user['last_active'])) : 'N/A'; ?>
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Activity Tab -->
                        <div class="tab-pane fade" id="activity" role="tabpanel" aria-labelledby="activity-tab">
                            <div class="row">
                                <div class="col-lg-12">
                                    <div class="card profile-card">
                                        <div class="card-header profile-card-header">
                                            <h5 class="card-title mb-0">Recent Activity</h5>
                                        </div>
                                        <div class="card-body profile-card-body p-0">
                                            <?php if (empty($recent_activities)): ?>
                                                <div class="p-4 text-center">
                                                    <div class="text-muted mb-3">
                                                        <i class="ri-information-line" style="font-size: 3rem;"></i>
                                                    </div>
                                                    <h5 class="mb-2">No recent activity</h5>
                                                    <p class="mb-0">Your recent activity will be displayed here</p>
                                                </div>
                                            <?php else: ?>
                                                <div class="activity-list">
                                                    <?php foreach ($recent_activities as $activity): ?>
                                                        <div class="activity-item d-flex align-items-start">
                                                            <div class="activity-icon bg-primary bg-opacity-10 text-primary">
                                                                <i class="ri-file-list-line"></i>
                                                            </div>
                                                            <div class="flex-grow-1">
                                                                <h6 class="mb-1"><?php echo htmlspecialchars($activity['action']); ?></h6>
                                                                <p class="text-muted mb-1"><?php echo htmlspecialchars($activity['details'] ?? 'No details available'); ?></p>
                                                                <small class="text-muted">
                                                                    <i class="ri-time-line"></i> 
                                                                    <?php echo date('F d, Y h:i A', strtotime($activity['created_at'])); ?>
                                                                </small>
                                                                <?php if (!empty($activity['ip_address'])): ?>
                                                                    <small class="text-muted ms-2">
                                                                        <i class="ri-global-line"></i> 
                                                                        <?php echo htmlspecialchars($activity['ip_address']); ?>
                                                                    </small>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        <?php if (count($recent_activities) > 0): ?>
                                            <div class="card-footer text-center">
                                                <a href="activity_log.php" class="btn btn-sm btn-outline-secondary">View All Activity</a>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Statistics Tab -->
                        <div class="tab-pane fade" id="stats" role="tabpanel" aria-labelledby="stats-tab">
                            <div class="row">
                                <div class="col-lg-8">
                                    <div class="card profile-card">
                                        <div class="card-header profile-card-header">
                                            <h5 class="card-title mb-0">Activity Overview</h5>
                                        </div>
                                        <div class="card-body profile-card-body">
                                            <div class="stats-chart-container">
                                                <canvas id="activityChart"></canvas>
                                            </div>
                                            <div class="row text-center">
                                                <div class="col-4">
                                                    <div class="p-3">
                                                        <h5 class="mb-1">5</h5>
                                                        <p class="text-muted mb-0">Files Created</p>
                                                    </div>
                                                </div>
                                                <div class="col-4">
                                                    <div class="p-3">
                                                        <h5 class="mb-1">12</h5>
                                                        <p class="text-muted mb-0">Files Updated</p>
                                                    </div>
                                                </div>
                                                <div class="col-4">
                                                    <div class="p-3">
                                                        <h5 class="mb-1">3</h5>
                                                        <p class="text-muted mb-0">Logins</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-lg-4">
                                    <div class="card profile-card">
                                        <div class="card-header profile-card-header">
                                            <h5 class="card-title mb-0">System Usage</h5>
                                        </div>
                                        <div class="card-body profile-card-body">
                                            <div class="mb-4">
                                                <label class="form-label d-flex justify-content-between mb-2">
                                                    <span>Files Created</span>
                                                    <span>5/100</span>
                                                </label>
                                                <div class="progress" style="height: 10px;">
                                                    <div class="progress-bar bg-success" role="progressbar" style="width: 5%;" aria-valuenow="5" aria-valuemin="0" aria-valuemax="100"></div>
                                                </div>
                                            </div>
                                            <div class="mb-4">
                                                <label class="form-label d-flex justify-content-between mb-2">
                                                    <span>Storage Used</span>
                                                    <span>10.5 MB / 100 MB</span>
                                                </label>
                                                <div class="progress" style="height: 10px;">
                                                    <div class="progress-bar bg-info" role="progressbar" style="width: 10.5%;" aria-valuenow="10.5" aria-valuemin="0" aria-valuemax="100"></div>
                                                </div>
                                            </div>
                                            <div>
                                                <label class="form-label d-flex justify-content-between mb-2">
                                                    <span>API Requests</span>
                                                    <span>150/1000</span>
                                                </label>
                                                <div class="progress" style="height: 10px;">
                                                    <div class="progress-bar bg-warning" role="progressbar" style="width: 15%;" aria-valuenow="15" aria-valuemin="0" aria-valuemax="100"></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <!-- Upload Avatar Modal -->
            <div class="modal fade" id="uploadAvatarModal" tabindex="-1" aria-labelledby="uploadAvatarModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="uploadAvatarModalLabel">Upload Profile Picture</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <?php if (!empty($avatar_success)): ?>
                                <div class="alert alert-success alert-dismissible fade show" role="alert">
                                    <?php echo $avatar_success; ?>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($avatar_error)): ?>
                                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                    <?php echo $avatar_error; ?>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                </div>
                            <?php endif; ?>
                            
                            <form method="POST" action="" enctype="multipart/form-data">
                                <div class="text-center mb-4">
                                    <img src="<?php echo htmlspecialchars($user['avatar']); ?>" alt="Current Profile Picture" class="img-fluid rounded-circle" style="width: 150px; height: 150px; object-fit: cover; border: 5px solid #f8f9fa;">
                                </div>
                                <div class="mb-3">
                                    <label for="avatar" class="form-label">Choose Image</label>
                                    <input type="file" class="form-control" id="avatar" name="avatar" accept="image/jpeg, image/png, image/gif" required>
                                    <div class="form-text text-muted">
                                        Allowed file types: JPG, PNG, GIF. Maximum size: 2MB.
                                    </div>
                                </div>
                                <div class="d-flex justify-content-end">
                                    <button type="button" class="btn btn-secondary me-2" data-bs-dismiss="modal">Cancel</button>
                                    <button type="submit" name="upload_avatar" class="btn btn-primary">Upload</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- Activity Chart -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Fix for tab switching issue
            var triggerTabList = [].slice.call(document.querySelectorAll('#profileTabs button'))
            triggerTabList.forEach(function(triggerEl) {
                triggerEl.addEventListener('click', function(event) {
                    event.preventDefault();
                    var tabTrigger = new bootstrap.Tab(triggerEl);
                    tabTrigger.show();
                });
            });
            
            // Initialize activity chart
            var ctx = document.getElementById('activityChart');
            if (ctx) {
                var myChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                        datasets: [{
                            label: 'Activity',
                            data: [5, 10, 8, 15, 12, 8],
                            backgroundColor: 'rgba(74, 108, 247, 0.2)',
                            borderColor: 'rgba(74, 108, 247, 1)',
                            borderWidth: 2,
                            tension: 0.4,
                            fill: true,
                            pointBackgroundColor: 'rgba(74, 108, 247, 1)',
                            pointBorderColor: '#fff',
                            pointBorderWidth: 2,
                            pointRadius: 4
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                grid: {
                                    color: 'rgba(0, 0, 0, 0.05)'
                                }
                            },
                            x: {
                                grid: {
                                    display: false
                                }
                            }
                        },
                        plugins: {
                            legend: {
                                display: false
                            }
                        }
                    }
                });
            }
        });
    </script>
</body>
</html>