<?php
require_once __DIR__ . '/../config.php';
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/i18n.php';
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/currency.php';

require_once __DIR__ . '/auth.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['lang'])) {
    $new_lang = $_GET['lang'];
    set_lang($new_lang);

    if (is_logged_in()) {
        $user_id = $_SESSION['user_id'];
        $stmt = db()->prepare("SELECT client_id FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $client_id = $stmt->fetchColumn();

        if ($client_id) {
            $stmt = db()->prepare("UPDATE clients SET language = ? WHERE id = ?");
            $stmt->execute([$new_lang, $client_id]);
        }
    }

    $uri = $_SERVER['REQUEST_URI'];
    $url_parts = parse_url($uri);
    $path = $url_parts['path'];
    $query = [];
    if (isset($url_parts['query'])) {
        parse_str($url_parts['query'], $query);
        unset($query['lang']);
    }
    $new_url = $path;
    if (!empty($query)) {
        $new_url .= '?' . http_build_query($query);
    }
    header("Location: " . $new_url);
    exit;
}

// Redirect handlowiec from client area to admin dashboard
if (is_logged_in() && get_user_role() === 'handlowiec' && strpos($_SERVER['PHP_SELF'], '/admin/') === false) {
    header('Location: /admin/orders.php');
    exit();
}