<?php
require_once 'config/database.php';
require_once 'utils/helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    Helpers::sendResponse(false, 'Method not allowed', null, 405);
}

// Get and verify token
$token = Helpers::getBearerToken();
$userData = Helpers::verifyJWT($token);

if (!$userData) {
    Helpers::sendResponse(false, 'Unauthorized', null, 401);
}

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

// Get user profile
$query = "SELECT u.`id`, u.`email`, u.`first_name`, u.`last_name`, u.`phone_number`, u.`gender`, 
            u.`department_id` AS department, d.`name` AS department_name, u.`role_id` AS role, ur.`role_name`, u.`created_at`
          FROM `users` AS u 
          JOIN `user_roles` AS ur ON ur.`id` = u.`role_id`
          JOIN `departments` AS d ON d.`id` = u.`department_id`
          WHERE u.`id` = :id";

$stmt = $db->prepare($query);
$stmt->bindParam(':id', $userData['user_id']);
$stmt->execute();

if ($stmt->rowCount() === 0) {
    Helpers::sendResponse(false, 'User not found', null, 404);
}

$user = $stmt->fetch();

Helpers::sendResponse(true, 'Profile retrieved successfully', [
    'user' => $user
]);
