<?php
/**
 * Router Class
 * Handles URL routing with slugs (SEO-friendly URLs)
 */

class Router {
    private $routes = [];
    private $currentPath;

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

    /**
     * Get current path from request
     */
    private function getCurrentPath() {
        $path = $_SERVER['REQUEST_URI'] ?? '/';
        
        // Remove query string
        $path = strtok($path, '?');
        
        // Remove base path if in subdirectory (for development)
        $basePath = str_replace($_SERVER['DOCUMENT_ROOT'], '', dirname($_SERVER['SCRIPT_NAME']));
        if ($basePath !== '/' && strpos($path, $basePath) === 0) {
            $path = substr($path, strlen($basePath));
        }
        
        // Ensure path starts with /
        if (empty($path) || $path[0] !== '/') {
            $path = '/' . $path;
        }
        
        // Remove trailing slash except for root
        if ($path !== '/' && substr($path, -1) === '/') {
            $path = rtrim($path, '/');
        }
        
        return $path;
    }

    /**
     * Get current path
     */
    public function getPath() {
        return $this->currentPath;
    }

    /**
     * Route a path to a file
     */
    public function route($pattern, $file) {
        $this->routes[$pattern] = $file;
    }

    /**
     * Match route and return file to include
     */
    public function match() {
        $path = $this->currentPath;
        
        // Exact match
        if (isset($this->routes[$path])) {
            return $this->routes[$path];
        }
        
        // Pattern matching
        foreach ($this->routes as $pattern => $file) {
            // Convert pattern to regex
            $regex = '#^' . preg_replace('#\{[^}]+\}#', '([^/]+)', $pattern) . '$#';
            
            if (preg_match($regex, $path, $matches)) {
                // Extract parameters
                preg_match_all('#\{([^}]+)\}#', $pattern, $paramNames);
                $params = [];
                for ($i = 0; $i < count($paramNames[1]); $i++) {
                    $params[$paramNames[1][$i]] = $matches[$i + 1] ?? null;
                }
                
                // Store params in $_GET for backward compatibility
                foreach ($params as $key => $value) {
                    $_GET[$key] = $value;
                }
                
                return $file;
            }
        }
        
        return null;
    }

    /**
     * Generate URL from route
     */
    public function url($path, $params = []) {
        $url = $path;
        
        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }
        
        return $url;
    }

    /**
     * Redirect to URL
     */
    public function redirect($url, $statusCode = 302) {
        header("Location: $url", true, $statusCode);
        exit;
    }

    /**
     * Get slug from path segment
     */
    public function getSlug($segment = 0) {
        $segments = explode('/', trim($this->currentPath, '/'));
        return $segments[$segment] ?? null;
    }

    /**
     * Get all path segments
     */
    public function getSegments() {
        return array_filter(explode('/', trim($this->currentPath, '/')));
    }
}

// Initialize router
$router = new Router();

// Define routes
$router->route('/', 'index.php');
$router->route('/catalog', 'shop-catalog-electronics.php');
$router->route('/catalog/{category_slug}', 'shop-catalog-electronics.php');
$router->route('/categorii', 'shop-categories-electronics.php');
$router->route('/produs/{product_slug}', 'shop-product-details-electronics.php');
$router->route('/cos', 'checkout-v1-cart.php');
$router->route('/checkout', 'checkout-v1-delivery-1.php');
$router->route('/checkout/livrare', 'checkout-v1-delivery-1.php');
$router->route('/checkout/transport', 'checkout-v1-shipping.php');
$router->route('/checkout/plata', 'checkout-v1-payment.php');
$router->route('/checkout/multumim', 'checkout-v1-thankyou.php');
$router->route('/cont/comenzi/{order_id}', 'account-order-details.php');
$router->route('/cont/login', 'account-signin.php');
$router->route('/cont/inregistrare', 'account-signup.php');
$router->route('/cont/info', 'account-info.php');
$router->route('/cont/comenzi', 'account-orders.php');
$router->route('/cont/wishlist', 'account-wishlist.php');
$router->route('/cont/adrese', 'account-addresses.php');
$router->route('/cont/plata', 'account-payment.php');
$router->route('/cont/recenzii', 'account-reviews.php');
$router->route('/cont/notificari', 'account-notifications.php');
$router->route('/cont/recuperare-parola', 'account-password-recovery.php');
$router->route('/cont/plata', 'account-payment.php');
$router->route('/despre', 'about-v1.php');
$router->route('/contact', 'contact-v3.php');
$router->route('/blog', 'blog-list.php');
$router->route('/blog/{post_slug}', 'blog-single-v1.php');

// Admin routes
$router->route('/admin', 'admin/dashboard.php');
$router->route('/admin/login', 'admin/login.php');
$router->route('/admin/produse', 'admin/products.php');
$router->route('/admin/produse/adauga', 'admin/product-add.php');
$router->route('/admin/produse/editeaza/{product_slug}', 'admin/product-edit.php');
$router->route('/admin/comenzi', 'admin/orders.php');
$router->route('/admin/comenzi/{order_id}', 'admin/order-details.php');
$router->route('/admin/clienti', 'admin/customers.php');
$router->route('/admin/clienti/{user_id}', 'admin/customer-details.php');
$router->route('/admin/cosuri-abandonate', 'admin/abandoned-carts.php');
$router->route('/admin/import-export', 'admin/import-export.php');
$router->route('/admin/puncte-fidelitate', 'admin/loyalty-points.php');
$router->route('/admin/grupuri-b2b', 'admin/b2b-groups.php');
$router->route('/admin/furnizori', 'admin/suppliers.php');
$router->route('/admin/produse-cadou', 'admin/gift-products.php');
?>

