<?php
/**
 * Router - SEO-Friendly URL Routing
 * Aegean Dominance - İzmir Tenteci V2
 */

declare(strict_types=1);

class Router
{
    private array $routes = [];
    private array $params = [];
    private ?string $matchedRoute = null;

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

    /**
     * Register all routes
     */
    private function registerRoutes(): void
    {
        // Home
        $this->addRoute('GET', '/', 'home');
        $this->addRoute('GET', '/index.php', 'home');

        // Services
        $this->addRoute('GET', '/hizmetlerimiz', 'services');
        $this->addRoute('GET', '/hizmetler', 'services');
        $this->addRoute('GET', '/hizmetlerimiz/{slug}', 'service-detail');

        // City Landing Pages
        $this->addRoute('GET', '/{city}-tente', 'city-landing');
        $this->addRoute('GET', '/{city}-pergola', 'city-landing');
        $this->addRoute('GET', '/{city}-cam-balkon', 'city-landing');

        // Static Pages
        $this->addRoute('GET', '/hakkimizda', 'about');
        $this->addRoute('GET', '/iletisim', 'contact');
        $this->addRoute('GET', '/galeri', 'gallery');
        $this->addRoute('GET', '/referanslar', 'references');
        $this->addRoute('GET', '/sss', 'faq');

        // Blog
        $this->addRoute('GET', '/blog', 'blog');
        $this->addRoute('GET', '/blog/{slug}', 'blog-detail');

        // Quote Form
        $this->addRoute('GET', '/teklif-al', 'quote');
        $this->addRoute('POST', '/teklif-al', 'quote-submit');

        // API Endpoints
        $this->addRoute('POST', '/api/contact', 'api-contact');
        $this->addRoute('GET', '/api/services', 'api-services');
    }

    /**
     * Add a route
     */
    public function addRoute(string $method, string $pattern, string $handler): void
    {
        $this->routes[] = [
            'method' => $method,
            'pattern' => $pattern,
            'handler' => $handler,
            'regex' => $this->patternToRegex($pattern)
        ];
    }

    /**
     * Convert route pattern to regex
     */
    private function patternToRegex(string $pattern): string
    {
        $regex = preg_replace('/\{([a-z_]+)\}/', '(?P<$1>[a-z0-9\-]+)', $pattern);
        return '#^' . $regex . '$#i';
    }

    /**
     * Match current request to a route
     */
    public function match(): ?string
    {
        $method = $_SERVER['REQUEST_METHOD'];
        $uri = $this->getUri();

        foreach ($this->routes as $route) {
            if ($route['method'] !== $method) continue;

            if (preg_match($route['regex'], $uri, $matches)) {
                // Extract named parameters
                foreach ($matches as $key => $value) {
                    if (is_string($key)) {
                        $this->params[$key] = $value;
                    }
                }
                $this->matchedRoute = $route['handler'];
                return $route['handler'];
            }
        }

        return null;
    }

    /**
     * Get clean URI from request
     */
    private function getUri(): string
    {
        $uri = $_SERVER['REQUEST_URI'] ?? '/';
        
        // Remove base path
        $basePath = BASE_URL ?? '/jules/v2';
        if (strpos($uri, $basePath) === 0) {
            $uri = substr($uri, strlen($basePath));
        }

        // Remove query string
        if (($pos = strpos($uri, '?')) !== false) {
            $uri = substr($uri, 0, $pos);
        }

        // Ensure leading slash
        if (empty($uri) || $uri[0] !== '/') {
            $uri = '/' . $uri;
        }

        // Remove trailing slash (except for root)
        if ($uri !== '/' && substr($uri, -1) === '/') {
            $uri = rtrim($uri, '/');
        }

        return $uri;
    }

    /**
     * Get route parameters
     */
    public function getParams(): array
    {
        return $this->params;
    }

    /**
     * Get single parameter
     */
    public function getParam(string $key, $default = null): mixed
    {
        return $this->params[$key] ?? $default;
    }

    /**
     * Dispatch to handler
     */
    public function dispatch(): void
    {
        $handler = $this->match();

        if (!$handler) {
            $this->render404();
            return;
        }
        
        // Handle API routes
        if (str_starts_with($handler, 'api-')) {
            $this->dispatchApi($handler);
            return;
        }

        $viewFile = VIEWS_PATH . '/' . $handler . '.php';

        if (file_exists($viewFile)) {
            $this->render($handler);
        } else {
            $this->render404();
        }
    }
    
    /**
     * Dispatch API requests
     */
    private function dispatchApi(string $handler): void
    {
        $apiFile = PUBLIC_PATH . '/api/' . str_replace('api-', '', $handler) . '.php';
        
        if (file_exists($apiFile)) {
            require_once $apiFile;
        } else {
            http_response_code(404);
            header('Content-Type: application/json');
            echo json_encode(['error' => 'API endpoint not found']);
        }
    }

    /**
     * Render a view
     */
    public function render(string $view, array $data = []): void
    {
        extract($data);
        extract($this->params);
        
        $router = $this;
        $db = Database::getInstance();

        $viewFile = VIEWS_PATH . '/' . $view . '.php';
        
        if (file_exists($viewFile)) {
            include $viewFile;
        } else {
            throw new Exception("View not found: {$view}");
        }
    }

    /**
     * Render 404 page
     */
    public function render404(): void
    {
        http_response_code(404);
        
        if (file_exists(VIEWS_PATH . '/404.php')) {
            include VIEWS_PATH . '/404.php';
        } else {
            echo '<h1>404 - Sayfa Bulunamadı</h1>';
            echo '<p><a href="' . BASE_URL . '">Ana Sayfaya Dön</a></p>';
        }
    }

    /**
     * Generate URL for a route
     */
    public static function url(string $path = ''): string
    {
        return (BASE_URL ?? '') . $path;
    }

    /**
     * Generate service URL
     */
    public static function serviceUrl(string $slug): string
    {
        return self::url('/hizmetlerimiz/' . $slug);
    }

    /**
     * Generate city landing URL
     */
    public static function cityUrl(string $city, string $service = 'tente'): string
    {
        return self::url('/' . $city . '-' . $service);
    }

    /**
     * Redirect to URL
     */
    public static function redirect(string $url, int $code = 302): void
    {
        http_response_code($code);
        header('Location: ' . $url);
        exit;
    }

    /**
     * JSON Response
     */
    public static function json(array $data, int $code = 200): void
    {
        http_response_code($code);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        exit;
    }
}
