<?php

declare(strict_types=1);

namespace SHServ\Controllers;

use SHServ\Integrations\GAuth\AuthService;

class WebhookController extends \SHServ\Middleware\Controller
{
    /**
     * POST /webhooks/gnexus-auth
     */
    public function gnexus_auth()
    {
        $rawBody = file_get_contents('php://input');
        $headers = $this->getAllHeaders();

        $service = new AuthService();

        try {
            $service->verifyWebhook($rawBody, $headers);
        } catch (\Throwable $e) {
            http_response_code(401);
            return json_encode(['status' => false, 'error' => 'webhook_verification_failed']);
        }

        try {
            $event = $service->parseWebhook($rawBody);
        } catch (\Throwable $e) {
            http_response_code(400);
            return json_encode(['status' => false, 'error' => 'webhook_parse_failed']);
        }

        // Route to handler
        $handler = new \SHServ\Integrations\GAuth\Webhook\WebhookRouter();
        $handler->handle($event);

        return json_encode(['status' => true]);
    }

    /**
     * Return all request headers, with a fallback for nginx/php-fpm
     * where getallheaders() may not be available.
     */
    private function getAllHeaders(): array
    {
        if (function_exists('getallheaders')) {
            return getallheaders();
        }

        $headers = [];
        foreach ($_SERVER as $name => $value) {
            if (str_starts_with($name, 'HTTP_')) {
                $key = str_replace('_', '-', substr($name, 5));
                $headers[$key] = $value;
            } elseif ($name === 'CONTENT_TYPE') {
                $headers['Content-Type'] = $value;
            } elseif ($name === 'CONTENT_LENGTH') {
                $headers['Content-Length'] = $value;
            }
        }
        return $headers;
    }
}
