<?php

namespace Hura8;


class Router {

    private $path_config = [];

    public function __construct() {
        //if( ! $this->path_config) {
            //$path_config_file = APP_DIR . '/config/routing.php';
            //$this->path_config = require $path_config_file;
        //}
    }

    // url: admin/abc/product.php?para1=value1
    public function getRouting() {
        $parsed = Url::parse($_SERVER['REQUEST_URI']); //abc/product?param1=12&param2=value2
        // print_r($parsed);
        
        // home
        if($parsed['path'] == '/') {
            return [
                'module' => preg_replace("/[^a-z0-9_\-]/i","", getRequest('module', 'home')),
                'view'   => preg_replace("/[^a-z0-9_\-]/i","", getRequest('view', 'home')),
                'view_id'=> 0,
                'query'  => $parsed['query'],
                'url'    => $_SERVER['REQUEST_URI'],
            ];
        }

        // check match pattern in $this->path_config
        /*foreach ($this->path_config as $_config => $_route ) {
            if(preg_match("{^".$_config."$}", $parsed['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'    => $parsed['path'],
                    'match'   => $match,
                ], $_route);
            }
        }*/

        // auto parse path base on convention: admin/module/view/view_id
        $ele = explode("/", $parsed['path']);

        $module =  $ele[2] ?? 'home';
        $view   =  isset($ele[3]) ? $ele[3] : getRequest('view', 'home');
        $view_id = isset($ele[4]) ? $ele[4] : getRequest('id', 'view_id');

        // else error
        return [
            'module'    => preg_replace("/[^a-z0-9_\-]/i","", $module ) ,
            'view'      => preg_replace("/[^a-z0-9_\-]/i","", $view ) ,
            'view_id'   => preg_replace("/[^a-z0-9_]/i","", $view_id ),
            'query'     => $parsed['query'],
            'url'       => $_SERVER['REQUEST_URI'],
        ];
    }

}
