<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['GET']);

$user = hw_auth_user();
if (!$user) hw_json(['success' => false, 'message' => 'Unauthorized'], 401);

try {
    $pdo = hw_db();

    // Load user data
    $stmt = $pdo->prepare('SELECT id, first_name, last_name, email, status, created_at, updated_at FROM users WHERE id = ? LIMIT 1');
    $stmt->execute([(int)$user['sub']]);
    $u = $stmt->fetch();
    if (!$u) hw_json(['success' => false, 'message' => 'User not found'], 404);

    // Load roles
    $stmt = $pdo->prepare('SELECT r.name FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ?');
    $stmt->execute([(int)$user['sub']]);
    $roles = array_map(fn($r) => $r['name'], $stmt->fetchAll());

    // Determine if intake form exists
    $stmt = $pdo->prepare('SELECT id FROM intake_forms WHERE user_id = ? ORDER BY id DESC LIMIT 1');
    $stmt->execute([(int)$user['sub']]);
    $intake = $stmt->fetch();

    hw_json([
        'success' => true,
        'user' => [
            'id' => (int)$u['id'],
            'first_name' => $u['first_name'],
            'last_name' => $u['last_name'],
            'email' => $u['email'],
            'status' => $u['status'],
            'roles' => $roles,
            'created_at' => $u['created_at'],
            'updated_at' => $u['updated_at'],
        ],
        'intake_completed' => (bool)$intake,
    ]);
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}
