<?php
namespace admin;

class Site
{
  public static function special_actions()
  {
    $sa = \S::get( 's-action' );
    $domain       = preg_replace( '#^(http(s)?://)?w{3}\.#', '$1', $_SERVER['SERVER_NAME'] );
    $cookie_name  = str_replace( '.', '-', $domain );
    switch ( $sa )
    {
      case 'user-logon':
        
        $result = \admin\factory\Users::logon( \S::get( 'login' ), \S::get( 'password' ) );
        
        if ( $result == 1 )
        {
          if(\S::get('remember'))
          {
            $password = md5( \S::get( 'password' ) );
            $login    = \S::get( 'login' );
            $value = [ login => $login , hash => $password ];
            $value = json_encode( $value );
              
            setcookie( $cookie_name, $value, time() +(86400 * 14), "/", $domain );
          }
          \S::set_session( 'user', \admin\factory\Users::details( \S::get( 'login' ) ) );
        }
        else
        {
          if ( $result == -1 )
            \S::alert( 'Z powodu nieudanych 5 prób logowania Twoje konto zostało zablokowane.' );
          else
            \S::alert( 'Podane hasło jest nieprawidłowe, lub brak użytkownika o podanym loginie.' );
        }
        header( 'Location: /admin/articles/view_list/' );
        exit;
      break;
      
      case 'user-logout':

        setcookie( $cookie_name, "", time() -(86400), "/", $domain );
        session_destroy();
        header( 'Location: /admin/' );
        exit;
      break;
    }
  }
  
  public static function route()
  {    
    $_SESSION['admin'] = true;
    
    $class = '\admin\controls\\';
      
    $results = explode( '_', \S::get( 'module' ) );
    if ( is_array( $results ) ) foreach ( $results as $row )
      $class .= ucfirst( $row );
    
    $action = \S::get( 'action' );
    
    if ( class_exists( $class ) and method_exists( new $class, $action ) )
      return call_user_func_array( array( $class, $action ), array() );
    else
    {
      \S::alert( 'Nieprawidłowy adres url.' );
      return false;
    }
  }
}
