<?
error_reporting( E_ALL ^ E_NOTICE ^ E_STRICT ^ E_WARNING ^ E_DEPRECATED );
if ( file_exists( 'ip.conf' ) )
{
  $ips = file_get_contents( 'ip.conf' );
  $ips = preg_split( "/\\r\\n|\\r|\\n/", $ips );
  $ips = array_filter( $ips );
  if ( is_array( $ips ) and!empty( $ips ) )
  {
    if ( !in_array( $_SERVER['REMOTE_ADDR'], $ips ) )
      die( 'Brak dostępu.' );
  }
}

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 );
  else
  {
    $f = '../autoload/' . implode( '/', $q ) . '/' . $c . '.php';
    if ( file_exists( $f ) )
      require_once( $f );
  }
}

spl_autoload_register( '__autoload_my_classes' );
require_once '../config.php';
require_once '../libraries/medoo/medoo.php';
require_once '../libraries/rb.php';
require_once '../libraries/phpmailer/class.phpmailer.php';
require_once '../libraries/phpmailer/class.smtp.php';

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

date_default_timezone_set( 'Europe/Warsaw' );

$settings = ( new \Domain\Settings\SettingsRepository( $mdb ) )->allSettings();

if ( file_exists( 'config.php' ) )
  include 'config.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: /admin/' );
  exit;
}

$langRepo = new \Domain\Languages\LanguagesRepository( $mdb );

if ( !$lang_id = \Shared\Helpers\Helpers::get_session( 'current-lang' ) )
{
  $lang_id = $langRepo->defaultLanguage();
  \Shared\Helpers\Helpers::set_session( 'current-lang', $lang_id );
}

if ( !$lang = \Shared\Helpers\Helpers::get_session( 'lang-' . $lang_id ) )
{
  $lang = $langRepo->translations( $lang_id );
  \Shared\Helpers\Helpers::set_session( 'lang-' . $lang_id, $lang );
}

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

$user = \Shared\Helpers\Helpers::get_session( 'user', true );

\admin\App::update();
\admin\App::special_actions();

$domain       = preg_replace( '/^www\./', '', $_SERVER['SERVER_NAME'] );
$cookie_name  = 'admin_remember_' . str_replace( '.', '-', $domain );

if ( isset( $_COOKIE[$cookie_name] ) && !isset( $_SESSION['user'] ) )
{
  $users = new \Domain\User\UserRepository($mdb);
  $payload = base64_decode($_COOKIE[$cookie_name]);
  if ($payload !== false && strpos($payload, '.') !== false)
  {
    list($json, $sig) = explode('.', $payload, 2);
    $expected_sig = hash_hmac('sha256', $json, \admin\App::APP_SECRET_KEY);

    if (hash_equals($expected_sig, $sig))
    {
      $data = json_decode($json, true);
      if ($data && isset($data['login']) && isset($data['ts']))
      {
        // Sprawdź czy cookie nie wygasło (14 dni)
        if ((time() - $data['ts']) < (86400 * 14))
        {
          $user_data = $mdb->get('pp_users', '*', ['AND' => ['login' => $data['login'], 'status' => 1]]);
          if ($user_data)
          {
            \Shared\Helpers\Helpers::set_session('user', $users->details($data['login']));
            $redirect = $_SERVER['REQUEST_URI'] ?: '/admin/articles/view_list/';
            header('Location: ' . $redirect);
            exit;
          }
        }
      }
    }
  }
  // Jeśli coś poszło nie tak, usuń nieprawidłowe cookie
  setcookie($cookie_name, '', [
    'expires'  => time() - 86400,
    'path'     => '/',
    'domain'   => $domain,
    'secure'   => true,
    'httponly' => true,
    'samesite' => 'Lax',
  ]);
}

echo \admin\App::render();
?>
