<?php
declare(strict_types=1);

require_once __DIR__ . '/../system/bootstrap.php';
require_once __DIR__ . '/../system/auth.php';
require_once __DIR__ . '/../system/response.php';

try {
    $actor = require_auth($pdo);

    if (!in_array($actor['role_key'], [
        'super_admin',
        'platform_admin',
        'rsp_admin',
        'company_admin'
    ], true)) {
        error_forbidden('Forbidden');
    }

    $input = json_decode(file_get_contents('php://input'), true);

    $userId    = (int)($input['user_id'] ?? 0);
    $firstName = trim($input['first_name'] ?? '');
    $lastName  = trim($input['last_name'] ?? '');

    if ($userId <= 0 || $firstName === '' || $lastName === '') {
        error_bad_request('Invalid input');
    }

    // Company admin → own company only
    if ($actor['role_key'] === 'company_admin') {
        $stmt = $pdo->prepare("
            SELECT id FROM users
            WHERE id = ? AND company_id = ?
        ");
        $stmt->execute([$userId, $actor['company_id']]);
        if (!$stmt->fetch()) {
            error_forbidden('Forbidden');
        }
    }

    $pdo->prepare("
        UPDATE users
        SET first_name = ?, last_name = ?
        WHERE id = ? AND deleted_at IS NULL
    ")->execute([$firstName, $lastName, $userId]);

    auditLog(
        (int)$actor['id'],
        (int)$actor['company_id'],
        'users',
        'profile_updated',
        ['user_id' => $userId]
    );

    success('Profile updated');
    invalidate_user_sessions($pdo, (int)$userId);

} catch (Throwable $e) {
    error_log('PROFILE UPDATE ERROR: ' . $e->getMessage());
    error_server('Profile update failed');
}
