<?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'
                ]);

// --- Nowy router ---
$request_uri = $_SERVER['REQUEST_URI'];
$uri = parse_url($request_uri, PHP_URL_PATH);
$uri = trim($uri, '/');
$segments = $uri ? explode('/', $uri, 3) : [];

// Aliasy czystych URL na moduł/akcję
$route_aliases = [
  'login'             => ['users', 'login_form'],
  'logowanie'         => ['users', 'login_form'],
  'logout'            => ['users', 'logout'],
  'settings'          => ['users', 'settings'],
  'settings/save'     => ['users', 'settings_save'],
  'settings/cron_status'    => ['users', 'settings_cron_status'],
  'settings/save_google_ads' => ['users', 'settings_save_google_ads'],
  'settings/save_openai'     => ['users', 'settings_save_openai'],
  'settings/save_claude'     => ['users', 'settings_save_claude'],
  'settings/save_gemini'     => ['users', 'settings_save_gemini'],
  'settings/save_ai_prompts' => ['users', 'settings_save_ai_prompts'],
  'products/ai_suggest'      => ['products', 'ai_suggest'],
  'clients/save'             => ['clients', 'save'],
  'feeds'                    => ['feeds', 'main_view'],
  'logs'                     => ['logs', 'main_view'],
  'logs/get_data_table'      => ['logs', 'get_logs_data_table'],
  'logs/get_detail'          => ['logs', 'get_detail'],
];

$path = implode('/', $segments);
$path_first = $segments[0] ?? '';

if (isset($route_aliases[$path])) {
  $_GET['module'] = $route_aliases[$path][0];
  $_GET['action'] = $route_aliases[$path][1];
} elseif (isset($route_aliases[$path_first])) {
  $_GET['module'] = $route_aliases[$path_first][0];
  $_GET['action'] = $route_aliases[$path_first][1];
} elseif (count($segments) >= 2) {
  $_GET['module'] = $segments[0];
  $_GET['action'] = $segments[1];
  if (isset($segments[2])) {
    parse_str($segments[2], $extra);
    $_GET = array_merge($_GET, $extra);
  }
} elseif (count($segments) === 1 && $segments[0] !== '') {
  $_GET['module'] = $segments[0];
  $_GET['action'] = 'main_view';
} else {
  $_GET['module'] = 'campaigns';
  $_GET['action'] = 'main_view';
}

// Aktualny moduł do podświetlenia w sidebar
$current_module = $_GET['module'] ?? '';

// --- Autoryzacja ---
$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');

// Whitelist - strony dostępne bez logowania
$public_paths = ['login', 'logowanie', 'users/login', 'users/login_form'];
$public_prefixes = ['api/', 'cron/'];

$is_public = in_array($path, $public_paths)
  || in_array($path_first . '/' . ($segments[1] ?? ''), $public_paths);

foreach ($public_prefixes as $prefix) {
  if (strpos($path, $prefix) === 0) {
    $is_public = true;
    break;
  }
}

// Strony tylko dla niezalogowanych (np. formularz logowania)
$guest_only_paths = ['login', 'logowanie', 'users/login', 'users/login_form'];
$is_guest_only = in_array($path, $guest_only_paths)
  || in_array($path_first . '/' . ($segments[1] ?? ''), $guest_only_paths);

if ($user && $is_guest_only)
{
  header('Location: /campaigns');
  exit;
}

if (!$user && !$is_public)
{
  header( 'Location: /login' );
  exit;
}

echo \view\Site::show();
