<?php
/**
 * Created by PhpStorm.
 * User: Игорь
 * Date: 23.01.2017
 * Time: 01:58
 */

namespace PFRM;


class App {

  protected $user_agent;

  protected $user_IP;

  protected $route_table;

  function __construct() {
    date_default_timezone_set('Europe/Moscow');
    error_reporting(E_ALL);
    $this->user_agent = $_SERVER['HTTP_USER_AGENT'];
    $this->user_IP    = $_SERVER['REMOTE_ADDR'];
    $this->setRoute( '|^/$|', 'Index', 'index' );
  }

  /**
   * Получение useragent пользователя
   *
   * @return string
   */
  public function getUserAgent() {
    return $this->user_agent;
  }

  /**
   * Получение IP пользователя
   *
   * @return string
   */
  public function getUserIP() {
    return $this->user_IP;
  }

  /**
   * Установка маршрута
   *
   * @param string $regexp регулярное выражение описывающее путь
   * @param string $controller котроллер.
   * @param string $action действие. по умолчанию 'index'
   */
  public function setRoute( $regexp, $controller, $action = 'index') {
    $this->route_table[] = array($regexp,$controller,$action);
  }

  /**
   * Редирект
   *
   * @param string $url адрес переброса
   */
  public function Redirect( $url ) {
    header( 'Location: ' . $url );
    exit(0);
  }

  /**
   * Запуск маршрутов
   */
  public function run(){
    foreach ( $this->route_table as $route_array ) {
      if ( preg_match( $route_array[0], $_SERVER['REQUEST_URI'], $matches ) ) {
        $a = $this->config->controller_namespace . $route_array[1] . 'Controller';
        $obj = new $a;
        $param_arr = [];
        foreach ( $matches as $key => $value ) {
          if ( ! is_int( $key ) ) {
            $param_arr[] = $value;
          }
        }
        call_user_func_array( [ $obj, $route_array[2] . 'Action' ], $param_arr );
        break;
      }
    }
  }
}