<?php

declare(strict_types=1);

function h(?string $value): string
{
    return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8');
}

function sanitizeText(string $value): string
{
    return trim(strip_tags($value));
}

function sanitizeEmail(?string $value): ?string
{
    if ($value === null || $value === '') {
        return null;
    }

    $email = filter_var($value, FILTER_SANITIZE_EMAIL);

    return filter_var($email, FILTER_VALIDATE_EMAIL) ? $email : null;
}

function redirect(string $path, array $params = []): void
{
    if ($params) {
        $query = http_build_query($params);
        $path .= (str_contains($path, '?') ? '&' : '?') . $query;
    }

    header('Location: ' . $path);
    exit;
}

function navItems(): array
{
    return [
        ['path' => '/index.php', 'label' => 'Dashboard'],
        ['path' => '/clients.php', 'label' => 'Clients'],
        ['path' => '#', 'label' => 'Proposals', 'dropdown' => [
            ['path' => '/templates.php', 'label' => 'Templates'],
            ['path' => '/modules.php', 'label' => 'Modules'],
            ['path' => '/generate.php', 'label' => 'Generate'],
            ['path' => '/proposals.php', 'label' => 'All Proposals'],
        ]],
        ['path' => '#', 'label' => 'New +', 'dropdown' => [
            ['path' => '/generate.php', 'label' => 'Proposal'],
            ['path' => '/clients.php', 'label' => 'Client'],
            ['path' => '/templates.php', 'label' => 'Template'],
            ['path' => '/modules.php', 'label' => 'Module'],
            ['path' => '/labels.php', 'label' => 'Manage Labels'],
        ]],
    ];
}

function isActiveNav(string $path): bool
{
    $current = $_SERVER['SCRIPT_NAME'] ?? '';
    
    // Check if current page matches the path
    if (str_ends_with($current, $path)) {
        return true;
    }
    
    // Check if current page is in a dropdown
    $navItems = navItems();
    foreach ($navItems as $item) {
        if (isset($item['dropdown'])) {
            foreach ($item['dropdown'] as $dropdownItem) {
                if (str_ends_with($current, $dropdownItem['path'])) {
                    return $path === '#'; // Parent dropdown is active
                }
                if ($path === $dropdownItem['path']) {
                    return true;
                }
            }
        }
    }
    
    return false;
}

function getTimeAgo(string $datetime): string
{
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) {
        return 'just now';
    } elseif ($diff < 3600) {
        $minutes = floor($diff / 60);
        return $minutes . ' minute' . ($minutes > 1 ? 's' : '') . ' ago';
    } elseif ($diff < 86400) {
        $hours = floor($diff / 3600);
        return $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';
    } elseif ($diff < 604800) {
        $days = floor($diff / 86400);
        return $days . ' day' . ($days > 1 ? 's' : '') . ' ago';
    } else {
        return date('M j, Y', $time);
    }
}

function getClientInitials(string $name): string
{
    $words = explode(' ', trim($name));
    if (count($words) >= 2) {
        return strtoupper(substr($words[0], 0, 1) . substr($words[1], 0, 1));
    }
    return strtoupper(substr($name, 0, 2));
}

function extractPlaceholders(array $blocks): array
{
    $placeholders = [];
    $pattern = '/{{\s*([a-zA-Z0-9_]+)\s*}}/';

    foreach ($blocks as $html) {
        if (!is_string($html) || $html === '') {
            continue;
        }

        if (preg_match_all($pattern, $html, $matches)) {
            foreach ($matches[1] as $token) {
                $placeholders[] = $token;
            }
        }
    }

    return array_values(array_unique($placeholders));
}

function renderWithVariables(?string $html, array $variables): string
{
    if (!$html) {
        return '';
    }

    $rendered = $html;
    foreach ($variables as $key => $value) {
        // For variable replacement, escape the values but keep HTML formatting intact
        $safeValue = h($value ?? '');
        $rendered = preg_replace('/{{\s*' . preg_quote($key, '/') . '\s*}}/', $safeValue, $rendered);
    }

    return $rendered;
}

function allowedCurrencies(): array
{
    return [
        'USD' => 'USD $',
        'EUR' => 'EUR €',
        'INR' => 'INR ₹',
        'GBP' => 'GBP £',
    ];
}

function sanitizeCurrency(?string $currency): string
{
    $currency = strtoupper((string) $currency);
    $options = allowedCurrencies();

    return array_key_exists($currency, $options) ? $currency : 'USD';
}

function formatCurrency(float $amount, string $currency): string
{
    $symbols = [
        'USD' => '$',
        'EUR' => '€',
        'INR' => '₹',
        'GBP' => '£',
    ];

    $symbol = $symbols[$currency] ?? '';

    return sprintf('%s%s', $symbol, number_format($amount, 2));
}

function clientVariableSuggestions(?array $client): array
{
    if (!$client) {
        return [];
    }

    return array_filter([
        'client_name' => $client['name'] ?? null,
        'client_company' => $client['company'] ?? null,
        'client_email' => $client['email'] ?? null,
        'client_phone' => $client['phone'] ?? null,
        'client_address' => $client['address'] ?? null,
    ], static fn ($value) => $value !== null && $value !== '');
}

function getTemplateModules(int $templateId): array
{
    $pdo = getPDO();
    $stmt = $pdo->prepare(
        "SELECT m.* FROM modules m 
         INNER JOIN template_modules tm ON m.id = tm.module_id 
         WHERE tm.template_id = ? AND tm.company_id = ?
         ORDER BY tm.sort_order"
    );
    $companyId = TenantDB::getTenant();
    $stmt->execute([$templateId, $companyId]);
    return $stmt->fetchAll();
}
