<?php

namespace app\controllers;
if(!defined('ACCESS_CONTROL')) {header($_SERVER['SERVER_PROTOCOL']. ' 404'); exit('404 not found');}

class Factory {
    protected $_controller;
    protected $_action;

    public function __construct($controller, $action){
        $namespace = 'app\controllers\\';
        $default_controller = $namespace.'Notfound';
        $default_action = 'get_index';

        if(class_exists("{$namespace}{$controller}", true))
        {
            $this->_controller = $namespace.$controller;
            $this->_action = method_exists($this->_controller, $action) ? $action : $default_action;
        }
        else{
            $this->_controller = $default_controller;
            $this->_action = $default_action;
        }
    }

    public static function factory()
    {
        $params = $_REQUEST;

        $do = isset($params['do']) && is_string($params['do']) ? $params['do'] : 'stats';
        $action = isset($params['action']) && is_string($params['action']) ? $params['action'] : 'index';
        $action_prefix = strtolower($_SERVER['REQUEST_METHOD'])."_";

        $controller_name = ucfirst(strtolower($do));
        $action_name = $action_prefix.$action;

        return new Factory($controller_name, $action_name);
    }

    public function execute()
    {
        $controller = new $this->_controller();
        $action = $this->_action;
        return $controller->$action();
    }
}