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

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
hw_require_method(['GET', 'PUT']);

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

try {
    $pdo = hw_db();

    if ($method === 'GET') {
        // Return basic profile 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)$auth['sub']]);
        $u = $stmt->fetch();
        if (!$u) hw_json(['message' => 'User not found'], 404);

        // 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)$auth['sub']]);
        $roles = array_map(fn($r) => $r['name'], $stmt->fetchAll());

        hw_json(['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'],
        ]]);
    }

    // PUT: update profile fields (first_name, last_name, optional email)
    $input = hw_input_json();
    $first = hw_sanitize_string($input['first_name'] ?? '');
    $last = hw_sanitize_string($input['last_name'] ?? '');
    $email = isset($input['email']) ? hw_sanitize_string($input['email']) : null; // optional

    if ($first === '' || $last === '') {
        hw_json(['message' => 'First and last name are required'], 422);
    }
    if ($email !== null && !hw_validate_email($email)) {
        hw_json(['message' => 'Email is invalid'], 422);
    }

    // Ensure email uniqueness if changing
    if ($email !== null) {
        $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ? AND id <> ? LIMIT 1');
        $stmt->execute([$email, (int)$auth['sub']]);
        if ($stmt->fetch()) hw_json(['message' => 'Email already in use'], 409);
    }

    // Build dynamic update
    $fields = ['first_name' => $first, 'last_name' => $last];
    if ($email !== null) $fields['email'] = $email;

    $set = [];$vals = [];
    foreach ($fields as $k => $v) { $set[] = "$k = ?"; $vals[] = $v; }
    $vals[] = (int)$auth['sub'];

    $sql = 'UPDATE users SET ' . implode(', ', $set) . ', updated_at = NOW() WHERE id = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($vals);

    // Audit
    $pdo->prepare('INSERT INTO audit_logs (user_id, action, meta) VALUES (?, ?, JSON_OBJECT("fields", JSON_ARRAY(' . ($email !== null ? '"first_name","last_name","email"' : '"first_name","last_name"') . ')))')
        ->execute([(int)$auth['sub'], 'profile_updated']);

    hw_json(['message' => 'Profile updated']);
} catch (Throwable $e) {
    hw_json(['message' => 'Server error', 'error' => $e->getMessage()], 500);
}
