<?php
error_reporting(E_ALL ^ E_NOTICE ^ E_STRICT ^ E_WARNING ^ E_DEPRECATED);
function __autoload_my_classes($classname)
{
    $q = explode('\\', $classname);
    $c = array_pop($q);
    $f = 'autoload/' . implode('/', $q) . '/class.' . $c . '.php';

    if (file_exists($f)) {
        require_once($f);
    }
}
spl_autoload_register('__autoload_my_classes');
date_default_timezone_set('Europe/Warsaw');

require_once 'config.php';
require_once 'libraries/medoo/medoo.php';
require_once 'libraries/grid/config.php';
require_once 'libraries/phpmailer/class.phpmailer.php';
require_once 'libraries/phpmailer/class.smtp.php';

session_start();

$mdb = new medoo([
                    'database_type' => 'mysql',
                    'database_name' => $database['name'],
                    'server'        => $database['host'],
                    'username'      => $database['user'],
                    'password'      => $database['password'],
                    'charset'       => 'utf8'
                ]);

$domain = preg_replace( '#^(http(s)?://)?w{3}\.#', '$1', $_SERVER['SERVER_NAME'] );
$cookie_name = str_replace( '.', '-', $domain );

if ( isset( $_COOKIE[$cookie_name] ) && !isset( $_SESSION['user'] ) )
{
  $obj = json_decode( $_COOKIE[$cookie_name] );
  $email = $obj -> {'email'};
  $password = $obj -> {'hash'};

  if ( $user_tmp = $mdb -> get( 'users', '*', [ 'AND' => [ 'email' => $email, 'password' => $password ] ] ) )
  {
    \S::set_session( 'user', $user_tmp );
  }
}

$user = \S::get_session('user');
if (
  !$user
and
  !(
      in_array( $_SERVER['REQUEST_URI'], [ '/logowanie', '/users/login/' ] )
    or
      strpos( $_SERVER['REQUEST_URI'], '/api/campaigns_data_save/' ) !== false
    or
      strpos( $_SERVER['REQUEST_URI'], '/api/phrases_data_save/' ) !== false
    or
      strpos( $_SERVER['REQUEST_URI'], '/api/products_data_save/' ) !== false
    or
      strpos( $_SERVER['REQUEST_URI'], '/cron/cron_products/' ) !== false
    or
      strpos( $_SERVER['REQUEST_URI'], '/cron/cron_products_history_30/' ) !== false
    or
      strpos( $_SERVER['REQUEST_URI'], '/cron/cron_xml/' ) !== false
    or
      strpos( $_SERVER['REQUEST_URI'], '/cron/cron_phrases/' ) !== false
    or
      strpos( $_SERVER['REQUEST_URI'], '/cron/cron_phrases_history_30/' ) !== false
  )
)
{
  header( 'Location: /logowanie' );
  exit;
}

echo \view\Site::show();