<?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);
    $base_path = 'autoload/' . implode('/', $q) . '/';
    $f = $base_path . $c . '.php';
    if ( !file_exists( $f ) )
      $f = $base_path . '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';
require_once 'libraries/rb.php';

session_start();

if (!isset($_SESSION['check'])) {
    session_regenerate_id();
    $_SESSION['check']  = true;
    $_SESSION['ip']     = $_SERVER['REMOTE_ADDR'];
}

if ($_SESSION['ip'] !== $_SERVER['REMOTE_ADDR']) {
    session_destroy();
    header('Location: /');
    exit;
}

\R::setup('mysql:host=' . $database['host'] . ';dbname=' . $database['name'], $database['user'], $database['password']);
\R::ext('xdispense', function ($type) {
    return R::getRedBean() -> dispense($type);
});

$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 );
$settings = array_merge( $settings, \factory\Crm::settings());
$clear_remember_cookie = function() use ( $cookie_name, $domain )
{
  setcookie( $cookie_name, '', [
    'expires'  => strtotime( '-1 year' ),
    'path'     => '/',
    'domain'   => $domain,
    'secure'   => true,
    'httponly'  => true,
    'samesite'  => 'Lax'
  ] );
};
$cleanup_remember_tokens = function() use ( $mdb )
{
  $mdb -> query( 'DELETE FROM `users_remember_tokens` WHERE COALESCE(`last_used_at`, `created_at`) < DATE_SUB(NOW(), INTERVAL 6 MONTH)' );
};

if ( empty( $_SESSION['_db_migrated_v5'] ) )
{
  $col = $mdb -> query( "SHOW COLUMNS FROM `users` LIKE 'remember_token'" ) -> fetch();
  if ( !$col )
    $mdb -> pdo -> exec( "ALTER TABLE `users` ADD COLUMN `remember_token` VARCHAR(64) DEFAULT NULL" );

  $tbl = $mdb -> query( "SHOW TABLES LIKE 'users_permissions'" ) -> fetch();
  if ( !$tbl )
  {
    $mdb -> pdo -> exec( "
      CREATE TABLE `users_permissions` (
        `user_id` INT UNSIGNED NOT NULL PRIMARY KEY,
        `tasks` TINYINT(1) NOT NULL DEFAULT 1,
        `projects` TINYINT(1) NOT NULL DEFAULT 1,
        `projects_view` TINYINT(1) NOT NULL DEFAULT 1,
        `projects_add` TINYINT(1) NOT NULL DEFAULT 1,
        `projects_edit` TINYINT(1) NOT NULL DEFAULT 1,
        `projects_delete` TINYINT(1) NOT NULL DEFAULT 1,
        `finances` TINYINT(1) NOT NULL DEFAULT 0,
        `wiki` TINYINT(1) NOT NULL DEFAULT 1,
        `crm` TINYINT(1) NOT NULL DEFAULT 0,
        `work_time` TINYINT(1) NOT NULL DEFAULT 1
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    " );
  }
  else
  {
    $col_z = $mdb -> query( "SHOW COLUMNS FROM `users_permissions` LIKE 'zaplecze'" ) -> fetch();
    if ( $col_z )
      $mdb -> pdo -> exec( "ALTER TABLE `users_permissions` DROP COLUMN `zaplecze`" );

    $project_permission_columns = [ 'projects_view', 'projects_add', 'projects_edit', 'projects_delete' ];
    foreach ( $project_permission_columns as $permission_column )
    {
      $col_perm = $mdb -> query( "SHOW COLUMNS FROM `users_permissions` LIKE '" . $permission_column . "'" ) -> fetch();
      if ( !$col_perm )
      {
        $mdb -> pdo -> exec( "ALTER TABLE `users_permissions` ADD COLUMN `" . $permission_column . "` TINYINT(1) NOT NULL DEFAULT 1" );
        $mdb -> pdo -> exec( "UPDATE `users_permissions` SET `" . $permission_column . "` = `projects`" );
      }
    }
  }

  $tbl_tokens = $mdb -> query( "SHOW TABLES LIKE 'users_remember_tokens'" ) -> fetch();
  if ( !$tbl_tokens )
  {
    $mdb -> pdo -> exec( "
      CREATE TABLE `users_remember_tokens` (
        `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        `user_id` INT UNSIGNED NOT NULL,
        `token_hash` CHAR(64) NOT NULL,
        `created_at` DATETIME NOT NULL,
        `last_used_at` DATETIME NULL,
        `user_agent` VARCHAR(255) NULL,
        `ip` VARCHAR(45) NULL,
        UNIQUE KEY `uniq_token_hash` (`token_hash`),
        KEY `idx_user_id` (`user_id`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    " );
  }

  $_SESSION['_db_migrated_v5'] = true;
}

if ( isset( $_COOKIE[$cookie_name] ) && !isset( $_SESSION['user'] ) )
{
  $cleanup_remember_tokens();
  $remember_token = $_COOKIE[$cookie_name];

  if ( is_string( $remember_token ) && strlen( $remember_token ) === 64 && ctype_xdigit( $remember_token ) )
  {
    $token_hash = hash( 'sha256', $remember_token );
    $token_row = $mdb -> get( 'users_remember_tokens', '*', [ 'token_hash' => $token_hash ] );

    if ( $token_row )
    {
      $user_tmp = $mdb -> get( 'users', '*', [ 'id' => $token_row['user_id'] ] );
      if ( $user_tmp )
      {
        \S::set_session( 'user', $user_tmp );
        $mdb -> update( 'users_remember_tokens', [
          'last_used_at' => date( 'Y-m-d H:i:s' ),
          'user_agent'   => substr( (string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255 ),
          'ip'           => (string)($_SERVER['REMOTE_ADDR'] ?? '')
        ], [ 'id' => (int)$token_row['id'] ] );
      }
      else
      {
        $mdb -> delete( 'users_remember_tokens', [ 'id' => (int)$token_row['id'] ] );
        $clear_remember_cookie();
      }
    }
    else
    {
      $clear_remember_cookie();
    }
  }
  else
  {
    // stale cookie w nieaktualnym formacie - usuniecie
    $clear_remember_cookie();
  }
}

$user = \S::get_session('user');
$request_path = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
$request_path = is_string( $request_path ) ? rtrim( $request_path, '/' ) : '';
if ( $request_path === '' )
  $request_path = '/';

if ( !$user and !in_array( $request_path, [ '/logowanie', '/rejestracja', '/users/login', '/cron/main_view' ], true ) )
{
  header( 'Location: /logowanie' );
  exit;
}

if ( $user and $request_path === '/logowanie' )
{
  header( 'Location: /tasks/main_view/' );
  exit;
}

echo \view\Site::show();
