<?php


namespace Hura8\System;


use Hura8\System\Controller\UrlManagerController;

class Router {

    private $path_config = [];

    /* @var UrlManagerController $objUrlManagerController */
    private  $objUrlManagerController;

    public function __construct() {
        $this->path_config = Config::getRoutes();
        $this->objUrlManagerController = new UrlManagerController();
    }

    // url: domain/abc/product.php?para1=value1
    public function getSiteRouting(string $request_uri = '') {

        if(!$request_uri) $request_uri = $_SERVER['REQUEST_URI'];

        $parsed = Url::parse($request_uri); //abc/product.php?param1=12&param2=value2

        $request_path = $parsed['path'];

        // remove possible language prefix: i.e. /en/about-us
        $language_enabled = Config::getLanguageConfig();
        if(sizeof($language_enabled) > 1) {
            $test_language_prefix = substr($request_path, 0, 4); //  /vi/ or /en/ ''
            foreach ($language_enabled as $_lang => $_v) {
                if($test_language_prefix == "/".$_lang."/") {
                    $request_path = substr($request_path, 3);
                    break;
                }
            }
        }


        // home
        if($request_path == '/') {
            return array_merge($this->path_config['home'], ['query' => $parsed['query']]);
        }

        // check match pattern in $this->path_config
        foreach ($this->path_config as $_config => $_route ) {
            if(preg_match("{^".$_config."$}", $request_path, $match )) {

                if(isset($_route['query']) && is_array($_route['query'])) {
                    $_route['query'] = array_merge($_route['query'], $parsed['query']);
                }else{
                    $_route['query'] = $parsed['query'];
                }

                return array_merge([
                    'path'    => $request_path,
                    'match'   => $match,
                ], $_route);
            }
        }

        // check in database's url table as the last resort
        $check_db = $this->objUrlManagerController->getUrlInfoByRequestPath($request_path);
        if($check_db) {

            if($check_db['redirect_code']) {
                return [
                    "redirect_code" =>  $check_db['redirect_code'],
                    "redirect_url" => $check_db['redirect_url'],
                ];
            }

            if(sizeof($parsed['query'])) {
                if(isset($check_db['query']) && is_array($check_db['query'])) {
                    $check_db['query'] = array_merge($check_db['query'], $parsed['query']);
                }else{
                    $check_db['query'] = $parsed['query'];
                }
            }

            return $check_db;
        }

        // else error
        return [
            'module' => 'error',
            'view' => '404_not_found',
        ];
    }

}
