<?php
/**
 * Funkcje pomocnicze
 */

/**
 * Pobierz bazowy URL
 */
function getBaseUrl(): string
{
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $path = dirname($_SERVER['SCRIPT_NAME']);
    return rtrim($protocol . '://' . $host . $path, '/');
}

/**
 * Przekieruj do URL
 */
function redirect(string $path = ''): void
{
    $url = getBaseUrl() . '/' . ltrim($path, '/');
    header('Location: ' . $url);
    exit;
}

/**
 * Pobierz wartość z POST
 */
function post(string $key, $default = null)
{
    return $_POST[$key] ?? $default;
}

/**
 * Pobierz wartość z GET
 */
function get(string $key, $default = null)
{
    return $_GET[$key] ?? $default;
}

/**
 * Escapuj HTML
 */
function e(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

/**
 * Wyświetl wiadomość flash
 */
function setFlash(string $type, string $message): void
{
    $_SESSION['flash'] = [
        'type' => $type,
        'message' => $message
    ];
}

/**
 * Pobierz i usuń wiadomość flash
 */
function getFlash(): ?array
{
    $flash = $_SESSION['flash'] ?? null;
    unset($_SESSION['flash']);
    return $flash;
}

/**
 * Sprawdź czy request jest AJAX
 */
function isAjax(): bool
{
    return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
           strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}

/**
 * Odpowiedź JSON
 */
function jsonResponse(array $data, int $code = 200): void
{
    http_response_code($code);
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

/**
 * Formatuj datę
 */
function formatDate(?string $date, string $format = 'd.m.Y H:i'): string
{
    if (!$date) {
        return '-';
    }
    return date($format, strtotime($date));
}

/**
 * Formatuj timestamp
 */
function formatTimestamp(int $timestamp, string $format = 'd.m.Y H:i'): string
{
    return date($format, $timestamp);
}

/**
 * Paginacja
 */
function paginate(int $total, int $perPage, int $currentPage): array
{
    $totalPages = max(1, ceil($total / $perPage));
    $currentPage = max(1, min($currentPage, $totalPages));
    
    $pages = [];
    $start = max(1, $currentPage - 2);
    $end = min($totalPages, $currentPage + 2);
    
    if ($start > 1) {
        $pages[] = 1;
        if ($start > 2) {
            $pages[] = '...';
        }
    }
    
    for ($i = $start; $i <= $end; $i++) {
        $pages[] = $i;
    }
    
    if ($end < $totalPages) {
        if ($end < $totalPages - 1) {
            $pages[] = '...';
        }
        $pages[] = $totalPages;
    }
    
    return [
        'total' => $total,
        'per_page' => $perPage,
        'current_page' => $currentPage,
        'total_pages' => $totalPages,
        'pages' => $pages,
        'has_prev' => $currentPage > 1,
        'has_next' => $currentPage < $totalPages,
        'offset' => ($currentPage - 1) * $perPage
    ];
}

/**
 * Generuj losowy string
 */
function randomString(int $length = 16): string
{
    return bin2hex(random_bytes($length / 2));
}

/**
 * Skróć tekst
 */
function truncate(string $text, int $length = 50, string $suffix = '...'): string
{
    if (mb_strlen($text) <= $length) {
        return $text;
    }
    return mb_substr($text, 0, $length) . $suffix;
}

/**
 * Pobierz IP klienta
 */
function getClientIp(): string
{
    $headers = ['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'];
    
    foreach ($headers as $header) {
        if (!empty($_SERVER[$header])) {
            $ip = $_SERVER[$header];
            if (strpos($ip, ',') !== false) {
                $ip = trim(explode(',', $ip)[0]);
            }
            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                return $ip;
            }
        }
    }
    
    return '0.0.0.0';
}

/**
 * Pobierz ustawienia systemu
 */
function getSettings(): array
{
    static $settings = null;
    
    if ($settings !== null) {
        return $settings;
    }
    
    $defaults = [
        'site_name' => 'IPTV Panel',
        'site_description' => 'Panel zarządzania playlistami IPTV',
        'items_per_page' => 20,
        'session_lifetime' => 3600,
        'maintenance_mode' => false,
        'maintenance_message' => 'System w trakcie konserwacji. Spróbuj ponownie później.',
        'allow_registration' => false,
        'default_device_limit' => 3,
        'default_playlist_limit' => 100,
        'password_length' => 12,
        'password_lowercase' => true,
        'password_uppercase' => true,
        'password_numbers' => true,
        'password_symbols' => false,
        'api_enabled' => true,
        'api_rate_limit' => 100,
        'log_retention_days' => 30,
        'smtp_enabled' => false,
        'smtp_host' => '',
        'smtp_port' => 587,
        'smtp_user' => '',
        'smtp_pass' => '',
        'smtp_from' => '',
        'smtp_from_name' => 'IPTV Panel',
        'login_attempts_limit' => 5,
        'login_lockout_time' => 300,
    ];
    
    $configFile = __DIR__ . '/../../config/settings.json';
    
    if (file_exists($configFile)) {
        $saved = json_decode(file_get_contents($configFile), true);
        if (is_array($saved)) {
            $settings = array_merge($defaults, $saved);
            return $settings;
        }
    }
    
    $settings = $defaults;
    return $settings;
}

/**
 * Pobierz pojedyncze ustawienie
 */
function getSetting(string $key, $default = null)
{
    $settings = getSettings();
    return $settings[$key] ?? $default;
}

/**
 * Generuj hasło według ustawień
 */
function generatePassword(?int $length = null): string
{
    $settings = getSettings();
    
    $length = $length ?? ($settings['password_length'] ?? 12);
    $useLowercase = $settings['password_lowercase'] ?? true;
    $useUppercase = $settings['password_uppercase'] ?? true;
    $useNumbers = $settings['password_numbers'] ?? true;
    $useSymbols = $settings['password_symbols'] ?? false;
    
    $chars = '';
    $required = [];
    
    if ($useLowercase) {
        $lowercase = 'abcdefghijklmnopqrstuvwxyz';
        $chars .= $lowercase;
        $required[] = $lowercase[random_int(0, strlen($lowercase) - 1)];
    }
    
    if ($useUppercase) {
        $uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $chars .= $uppercase;
        $required[] = $uppercase[random_int(0, strlen($uppercase) - 1)];
    }
    
    if ($useNumbers) {
        $numbers = '0123456789';
        $chars .= $numbers;
        $required[] = $numbers[random_int(0, strlen($numbers) - 1)];
    }
    
    if ($useSymbols) {
        $symbols = '!@#$%^&*()_+-=[]{}|;:,.<>?';
        $chars .= $symbols;
        $required[] = $symbols[random_int(0, strlen($symbols) - 1)];
    }
    
    // Fallback jeśli nic nie wybrano
    if (empty($chars)) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    }
    
    // Generuj hasło
    $password = '';
    $charsLength = strlen($chars);
    
    // Najpierw dodaj wymagane znaki z każdej kategorii
    foreach ($required as $char) {
        $password .= $char;
    }
    
    // Dopełnij do wymaganej długości
    while (strlen($password) < $length) {
        $password .= $chars[random_int(0, $charsLength - 1)];
    }
    
    // Wymieszaj znaki
    return str_shuffle($password);
}

/**
 * Pobierz ustawienia generatora haseł jako JSON dla JS
 */
function getPasswordSettingsJson(): string
{
    $settings = getSettings();
    return json_encode([
        'length' => $settings['password_length'] ?? 12,
        'lowercase' => $settings['password_lowercase'] ?? true,
        'uppercase' => $settings['password_uppercase'] ?? true,
        'numbers' => $settings['password_numbers'] ?? true,
        'symbols' => $settings['password_symbols'] ?? false,
    ]);
}
