<?php

namespace App\Router;

use Slim\Factory\AppFactory;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class SlimRouter
{
    private $app;
    private $pdo;

    public function __construct($pdo)
    {
        $this->app = AppFactory::create();
        $this->pdo = $pdo;

        // Add error middleware
        $this->app->addErrorMiddleware(true, true, true);

        $this->registerRoutes();
    }

    private function registerRoutes()
    {
        // Auth routes
        $this->app->get('/login', function (Request $request, Response $response) {
            $authController = new \AuthController($this->pdo);
            $html = $authController->showLogin();
            $response->getBody()->write($html);
            return $response;
        });

        $this->app->post('/login', function (Request $request, Response $response) {
            $authController = new \AuthController($this->pdo);
            $result = $authController->login($this->createRequestAdapter($request));

            if (is_array($result) && isset($result['redirect'])) {
                return $response->withHeader('Location', $result['redirect'])->withStatus(302);
            }

            $response->getBody()->write(json_encode($result));
            return $response->withHeader('Content-Type', 'application/json');
        });

        // API routes with Slim's nice parameter handling
        $this->app->get('/api/leads/{id}', function (Request $request, Response $response, $args) {
            $leadsController = new \LeadsController($this->pdo);
            $result = $leadsController->show($this->createRequestAdapter($request), $args['id']);

            $response->getBody()->write(json_encode($result));
            return $response->withHeader('Content-Type', 'application/json');
        });

        $this->app->get('/api/forms/{id}/embed', function (Request $request, Response $response, $args) {
            $formsController = new \FormsController($this->pdo);
            $result = $formsController->getEmbedCode($this->createRequestAdapter($request), $args['id']);

            $response->getBody()->write(json_encode($result));
            return $response->withHeader('Content-Type', 'application/json');
        });

        // Grouped routes for app area
        $this->app->group('/app', function (\Slim\Routing\RouteCollectorProxy $group) {
            $group->get('/dashboard', function (Request $request, Response $response) {
                $dashboardController = new \DashboardController($this->pdo);
                $html = $dashboardController->index($this->createRequestAdapter($request));
                $response->getBody()->write($html);
                return $response;
            });

            $group->get('/forms', function (Request $request, Response $response) {
                $formsController = new \FormsController($this->pdo);
                $html = $formsController->index($this->createRequestAdapter($request));
                $response->getBody()->write($html);
                return $response;
            });
        });
    }

    private function createRequestAdapter($slimRequest)
    {
        // Adapt Slim Request to our custom Request interface
        return new class($slimRequest) {
            private $request;

            public function __construct($request)
            {
                $this->request = $request;
            }

            public function get($key, $default = null)
            {
                $params = $this->request->getQueryParams();
                return $params[$key] ?? $default;
            }

            public function post($key, $default = null)
            {
                $params = (array)$this->request->getParsedBody();
                return $params[$key] ?? $default;
            }

            public function isPost()
            {
                return $this->request->getMethod() === 'POST';
            }

            public function isAjax()
            {
                return $this->request->getHeaderLine('X-Requested-With') === 'XMLHttpRequest';
            }
        };
    }

    public function run()
    {
        $this->app->run();
    }
}
