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

if (!isset($_SESSION['user_id'])) {
   header('Location: login.php');
   exit();
}

// Get detailed user info
$user_id = $_SESSION['user_id'];
$query = "SELECT u.*, r.role_name,
         DATE_FORMAT(u.last_password_change, '%d %b %Y') as pwd_changed,
         DATE_FORMAT(u.last_active, '%d %b %Y %H:i') as last_seen, 
         DATE_FORMAT(u.created_at, '%d %b %Y') as joined_date,
         CASE 
           WHEN u.failed_attempts >= 3 THEN 'Locked'
           WHEN u.verified = 0 THEN 'Unverified'
           WHEN u.verified = 1 THEN 'Active'
         END as account_status
         FROM users u
         LEFT JOIN user_role r ON u.role_id = r.role_id
         WHERE u.user_id = ?";

$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

   // Profile update
   if (isset($_POST['update_profile'])) {
       $full_name = $_POST['full_name'];
       $email = $_POST['email'];

       $stmt = $conn->prepare("UPDATE users SET full_name = ?, email = ? WHERE user_id = ?");
       $stmt->bind_param("ssi", $full_name, $email, $user_id);
       
       if ($stmt->execute()) {
           $_SESSION['success_msg'] = "Profile updated successfully";
       } else {
           $_SESSION['error_msg'] = "Error updating profile";
       }
   }

   // Password change
   if (isset($_POST['change_password'])) {
       $current_password = $_POST['current_password'];
       $new_password = $_POST['new_password'];
       $confirm_password = $_POST['confirm_password'];

       if (password_verify($current_password, $user['password']) && $new_password === $confirm_password) {
           $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
           
           $stmt = $conn->prepare("UPDATE users SET password = ?, last_password_change = NOW() WHERE user_id = ?");
           $stmt->bind_param("si", $hashed_password, $user_id);
           
           if ($stmt->execute()) {
               $_SESSION['success_msg'] = "Password changed successfully";
           } else {
               $_SESSION['error_msg'] = "Error changing password";
           }
       } else {
           $_SESSION['error_msg'] = "Invalid current password or passwords don't match";
       }
   }

if (isset($_FILES['avatar'])) {
   header('Content-Type: application/json');
   
   $file = $_FILES['avatar'];
   $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
   $upload_dir = __DIR__ . '/assets/images/users/';

   try {
       // Create directory if doesn't exist
       if (!is_dir($upload_dir)) {
           mkdir($upload_dir, 0777, true);
       }

       // Validate file
       if (!in_array($file['type'], $allowed_types)) {
           throw new Exception('Invalid file type. Only JPG, PNG and GIF allowed');
       }

       if ($file['size'] > 5 * 1024 * 1024) {
           throw new Exception('File too large. Maximum size is 5MB');
       }

       // Generate filename using username
       $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
       $filename = strtolower($user['username']) . '_avatar_' . time() . '.' . $extension;
       $filepath = $upload_dir . $filename;

       // Delete old avatar
       if ($user['avatar'] && file_exists($upload_dir . $user['avatar'])) {
           unlink($upload_dir . $user['avatar']);
       }

       // Upload new file
       if (!move_uploaded_file($file['tmp_name'], $filepath)) {
           throw new Exception('Failed to upload file');
       }

       // Update database
       $stmt = $conn->prepare("UPDATE users SET avatar = ? WHERE user_id = ?");
       $stmt->bind_param("si", $filename, $user_id);

       if (!$stmt->execute()) {
           unlink($filepath); // Delete uploaded file if DB update fails
           throw new Exception('Database update failed');
       }

       echo json_encode([
           'success' => true,
           'message' => 'Profile picture updated successfully',
           'image_url' => 'assets/images/users/' . $filename . '?v=' . time()
       ]);

   } catch (Exception $e) {
       http_response_code(400);
       echo json_encode([
           'success' => false,
           'error' => $e->getMessage()
       ]);
   }
   exit;
}
}
?>

<!DOCTYPE html>
<html>
<head>
   <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My Profile')); ?>
   <?php include 'layouts/head-css.php'; ?>
   <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
   <style>
       .profile-user {
           position: relative;
           width: 120px;
           height: 120px;
       }
       .profile-photo-edit {
           position: absolute;
           right: 0;
           bottom: 0;
       }
       .profile-img-file-input {
           display: none;
       }
   </style>
</head>

<body>
   <div id="layout-wrapper">
       <?php include 'layouts/menu.php'; ?>
       
       <div class="main-content">
           <div class="page-content">
               <div class="container-fluid">
                   <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Account Settings', 'title' => 'My Profile')); ?>

                   <?php if (isset($_SESSION['success_msg'])): ?>
                       <div class="alert alert-success alert-dismissible fade show">
                           <?php 
                           echo $_SESSION['success_msg'];
                           unset($_SESSION['success_msg']);
                           ?>
                           <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                       </div>
                   <?php endif; ?>

                   <?php if (isset($_SESSION['error_msg'])): ?>
                       <div class="alert alert-danger alert-dismissible fade show">
                           <?php 
                           echo $_SESSION['error_msg'];
                           unset($_SESSION['error_msg']);
                           ?>
                           <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                       </div>
                   <?php endif; ?>

                   <div class="row">
                       <div class="col-xxl-3">
                           <div class="card">
                               <div class="card-body">
                                   <div class="text-center">
                                       <div class="profile-user position-relative d-inline-block mx-auto mb-4">
                                           <img src="<?php 
                                               echo $user['avatar'] && file_exists('assets/images/users/' . $user['avatar']) 
                                                   ? 'assets/images/users/' . $user['avatar'] . '?v=' . time() 
                                                   : 'assets/images/users/default-avatar.jpg'; ?>" 
                                               class="rounded-circle avatar-xl img-thumbnail user-profile-image"
                                               alt="<?php echo htmlspecialchars($user['full_name']); ?>">
                                           <div class="avatar-xs p-0 rounded-circle profile-photo-edit">
                                               <input id="profile-img-file-input" type="file" class="profile-img-file-input" 
                                                      accept="image/jpeg,image/png,image/gif">
                                               <label for="profile-img-file-input" class="profile-photo-edit avatar-xs">
                                                   <span class="avatar-title rounded-circle bg-light text-body">
                                                       <i class="ri-camera-fill"></i>
                                                   </span>
                                               </label>
                                           </div>
                                       </div>
                                       <h5 class="mb-1"><?php echo htmlspecialchars($user['full_name']); ?></h5>
                                       <p class="text-muted"><?php echo htmlspecialchars($user['role_name']); ?></p>
                                   </div>
                               </div>
                           </div>

                           <div class="card mt-4">
                               <div class="card-body">
                                   <h5 class="card-title mb-3">Account Information</h5>
                                   <div class="table-responsive">
                                       <table class="table table-sm table-borderless mb-0">
                                           <tr>
                                               <th width="150">Username:</th>
                                               <td><?php echo htmlspecialchars($user['username']); ?></td>
                                           </tr>
                                           <tr>
                                               <th>Role:</th>
                                               <td>
                                                   <span class="badge bg-primary"><?php echo htmlspecialchars($user['role_name']); ?></span>
                                               </td>
                                           </tr>
                                           <tr>
                                               <th>Status:</th>
                                               <td>
                                                   <span class="badge bg-<?php 
                                                       echo $user['account_status'] === 'Active' ? 'success' : 
                                                           ($user['account_status'] === 'Locked' ? 'danger' : 'warning'); 
                                                   ?>">
                                                       <?php echo $user['account_status']; ?>
                                                   </span>
                                               </td>
                                           </tr>
                                           <tr>
                                               <th>Member Since:</th>
                                               <td><?php echo $user['joined_date']; ?></td>
                                           </tr>
                                           <tr>
                                               <th>Last Active:</th>
                                               <td><?php echo $user['last_seen']; ?></td>
                                           </tr>
                                           <tr>
                                               <th>Password Changed:</th>
                                               <td><?php echo $user['pwd_changed']; ?></td>
                                           </tr>
                                       </table>
                                   </div>
                               </div>
                           </div>
                       </div>

                       <div class="col-xxl-9">
                           <div class="card">
                               <div class="card-header">
                                   <ul class="nav nav-tabs-custom rounded card-header-tabs border-bottom-0">
                                       <li class="nav-item">
                                           <a class="nav-link active" data-bs-toggle="tab" href="#personalDetails">
                                               <i class="fas fa-user-circle me-1"></i> Personal Details
                                           </a>
                                       </li>
                                       <li class="nav-item">
                                           <a class="nav-link" data-bs-toggle="tab" href="#changePassword">
                                               <i class="fas fa-lock me-1"></i> Change Password
                                           </a>
                                       </li>
                                   </ul>
                               </div>

                               <div class="card-body p-4">
                                   <div class="tab-content">
                                       <div class="tab-pane active" id="personalDetails">
                                           <form action="" method="POST" id="profileForm">
                                               <div class="row">
                                                   <div class="col-lg-6">
                                                       <div class="mb-3">
                                                           <label for="full_name" class="form-label">Full Name</label>
                                                           <input type="text" class="form-control" id="full_name" name="full_name"
                                                                  value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                                                       </div>
                                                   </div>
                                                   <div class="col-lg-6">
                                                       <div class="mb-3">
                                                           <label for="email" class="form-label">Email Address</label>
                                                           <input type="email" class="form-control" id="email" name="email"
                                                                  value="<?php echo htmlspecialchars($user['email']); ?>" required>
                                                       </div>
                                                   </div>
                                               </div>
                                               <div class="col-lg-12">
                                                   <div class="hstack gap-2 justify-content-end">
                                                       <button type="submit" name="update_profile" class="btn btn-primary">
                                                           <i class="fas fa-save me-1"></i> Update Profile
                                                       </button>
                                                   </div>
                                               </div>
                                           </form>
                                       </div>

                                       <div class="tab-pane" id="changePassword">
                                           <form action="" method="POST" id="passwordForm">
                                               <div class="row g-2">
                                                   <div class="col-lg-4">
                                                       <div>
                                                           <label for="current_password" class="form-label">Current Password</label>
                                                           <div class="position-relative auth-pass-inputgroup">
                                                               <input type="password" class="form-control pe-5" 
                                                                      id="current_password" name="current_password" required>
                                                               <button type="button" class="btn btn-link position-absolute end-0 top-0 h-100 text-decoration-none text-muted password-addon" tabindex="-1">
                                                                   <i class="ri-eye-fill align-middle"></i>
                                                               </button>
                                                           </div>
                                                       </div>
                                                   </div>
                                                   <div class="col-lg-4">
                                                       <div>
                                                           <label for="new_password" class="form-label">New Password</label>
                                                           <div class="position-relative auth-pass-inputgroup">
                                                               <input type="password" class="form-control pe-5" 
                                                                      id="new_password" name="new_password" required>
                                                               <button type="button" class="btn btn-link position-absolute end-0 top-0 h-100 text-decoration-none text-muted password-addon" tabindex="-1">
                                                                   <i class="ri-eye-fill align-middle"></i>
                                                               </button>
                                                           </div>
                                                       </div>
                                                   </div>
                                                   <div class="col-lg-4">
                                                       <div>
                                                           <label for="confirm_password" class="form-label">Confirm Password</label>
                                                           <div class="position-relative auth-pass-inputgroup">
                                                               <input type="password" class="form-control pe-5" 
                                                                      id="confirm_password" name="confirm_password" required>
                                                               <button type="button" class="btn btn-link position-absolute end-0 top-0 h-100 text-decoration-none text-muted password-addon" tabindex="-1">
                                                                   <i class="ri-eye-fill align-middle"></i>
                                                               </button>
                                                           </div>
                                                           </div>
                                        </div>
                                    </div>
                                    <div class="col-lg-12 mt-3">
                                        <div class="text-end">
                                            <button type="submit" name="change_password" class="btn btn-primary">
                                                <i class="ri-lock-password-line me-1"></i> Change Password
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php include 'layouts/footer.php'; ?>
</div>
</div>

<?php include 'layouts/vendor-scripts.php'; ?>
<script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const profileImgInput = document.getElementById('profile-img-file-input');
    
    // Password visibility toggle
    document.querySelectorAll('.password-addon').forEach(button => {
        button.addEventListener('click', function() {
            const input = this.previousElementSibling;
            input.type = input.type === 'password' ? 'text' : 'password';
            this.querySelector('i').className = input.type === 'password' ? 
                'ri-eye-fill' : 'ri-eye-off-fill';
        });
    });

    // Profile image upload
    profileImgInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // Show preview
            const reader = new FileReader();
            reader.onload = function(e) {
                document.querySelector('.user-profile-image').src = e.target.result;
            }
            reader.readAsDataURL(file);

            const formData = new FormData();
            formData.append('avatar', file);

            Swal.fire({
                title: 'Uploading...',
                text: 'Please wait',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => Swal.showLoading()
            });

            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: data.message,
                        timer: 1500,
                        showConfirmButton: false
                    });
                } else {
                    throw new Error(data.error);
                }
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: error.message || 'Failed to upload image'
                });
            });
        }
    });

    // Form submissions
    document.querySelectorAll('form').forEach(form => {
        form.addEventListener('submit', function(e) {
            if (!this.checkValidity()) {
                e.preventDefault();
                e.stopPropagation();
            }
            form.classList.add('was-validated');
        });
    });
});
</script>

</body>
</html>