<?php
declare(strict_types=1);

/** Escape for HTML output. Every dynamic value in a view goes through this. */
function e(mixed $value): string
{
    return htmlspecialchars((string) ($value ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

/** Build an internal URL: url('companies', 'view', ['id' => 5]) */
function url(string $module = 'dashboard', string $action = 'index', array $params = []): string
{
    $query = array_merge(['m' => $module, 'a' => $action], $params);
    return BASE_URL . '/index.php?' . http_build_query($query);
}

function redirect(string $module = 'dashboard', string $action = 'index', array $params = []): never
{
    header('Location: ' . url($module, $action, $params));
    exit;
}

function redirect_to(string $absoluteUrl): never
{
    header('Location: ' . $absoluteUrl);
    exit;
}

/** Current query string with some parameters replaced - used by sort links and pagers. */
function url_with(array $overrides): string
{
    $params = $_GET;
    foreach ($overrides as $k => $v) {
        if ($v === null) {
            unset($params[$k]);
        } else {
            $params[$k] = $v;
        }
    }
    $params['m'] = $params['m'] ?? 'dashboard';
    $params['a'] = $params['a'] ?? 'index';
    return BASE_URL . '/index.php?' . http_build_query($params);
}

function client_ip(): string
{
    return (string) ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0');
}

function client_ip_binary(): ?string
{
    $packed = @inet_pton(client_ip());
    return $packed === false ? null : $packed;
}

function post(string $key, mixed $default = null): mixed
{
    $v = $_POST[$key] ?? $default;
    return is_string($v) ? trim($v) : $v;
}

function get_param(string $key, mixed $default = null): mixed
{
    $v = $_GET[$key] ?? null;
    if ($v === null || $v === '') {
        return $default;
    }
    return is_string($v) ? trim($v) : $v;
}

function get_int(string $key, ?int $default = null): ?int
{
    $v = get_param($key);
    return $v === null ? $default : (int) $v;
}

/** Comma-separated query parameter as a clean array. */
function get_list(string $key): array
{
    $v = get_param($key);
    if ($v === null) {
        return [];
    }
    if (is_array($v)) {
        return array_values(array_filter(array_map('trim', $v), 'strlen'));
    }
    return array_values(array_filter(array_map('trim', explode(',', (string) $v)), 'strlen'));
}

function slugify(string $text): string
{
    $text = mb_strtolower(trim($text));
    $text = preg_replace('/[^\p{L}\p{N}]+/u', '-', $text) ?? '';
    return trim($text, '-') ?: 'item';
}

/** Make a slug unique within a table, optionally scoped to one company. */
function unique_slug(string $base, string $table, ?int $ignoreId = null, ?int $companyId = null): string
{
    $safe = preg_replace('/[^a-z_]/', '', $table);
    $slug = $base;
    $n = 2;

    while (true) {
        $sql = "SELECT 1 FROM `{$safe}` WHERE slug = :s";
        $bind = ['s' => $slug];
        if ($companyId !== null) {
            $sql .= ' AND company_id = :cid';
            $bind['cid'] = $companyId;
        }
        if ($ignoreId !== null) {
            $sql .= ' AND id <> :ign';
            $bind['ign'] = $ignoreId;
        }
        if (Database::scalar($sql . ' LIMIT 1', $bind) === null) {
            return $slug;
        }
        $slug = $base . '-' . $n++;
    }
}

/** "12 Mar 2025" or an em dash when empty. */
function fmt_date(?string $date): string
{
    if ($date === null || $date === '' || $date === '0000-00-00') {
        return '—';
    }
    $d = date_create($date);
    return $d === false ? '—' : $d->format('j M Y');
}

function fmt_datetime(?string $dt): string
{
    if ($dt === null || $dt === '') {
        return '—';
    }
    $d = date_create($dt);
    return $d === false ? '—' : $d->format('j M Y, H:i');
}

/** "3 months ago" / "in 12 days" - relative phrasing for staleness. */
function fmt_ago(?string $date): string
{
    if ($date === null || $date === '') {
        return t('never');
    }
    $then = date_create($date);
    if ($then === false) {
        return '—';
    }
    $days = (int) $then->diff(new DateTimeImmutable('today'))->format('%r%a');

    if ($days === 0)          return t('today');
    if ($days === 1)          return t('yesterday');
    if ($days < 0)            return t('in_days', ['n' => abs($days)]);
    if ($days < 45)           return t('days_ago', ['n' => $days]);
    if ($days < 365)          return t('months_ago', ['n' => (int) round($days / 30)]);
    return t('years_ago', ['n' => round($days / 365, 1)]);
}

/** Whole days between a date and today. Positive = in the past. */
function days_since(?string $date): ?int
{
    if ($date === null || $date === '') {
        return null;
    }
    $then = date_create($date);
    return $then === false ? null : (int) $then->diff(new DateTimeImmutable('today'))->format('%r%a');
}

/**
 * Staleness on a 0-1 scale, which drives the thermal indicator.
 * 0 = checked today, 1 = never checked or well past a year.
 */
function staleness(?string $lastVisit): float
{
    $days = days_since($lastVisit);
    if ($days === null) {
        return 1.0;
    }
    return max(0.0, min(1.0, $days / STALE_AFTER_DAYS));
}

/** Thermal ramp: cold violet through to hot amber. */
function thermal_color(float $t): string
{
    $stops = [
        [0.00, [43, 26, 77]],
        [0.25, [95, 32, 110]],
        [0.50, [166, 45, 90]],
        [0.72, [216, 92, 42]],
        [0.88, [237, 145, 33]],
        [1.00, [250, 204, 121]],
    ];

    $t = max(0.0, min(1.0, $t));
    for ($i = 0; $i < count($stops) - 1; $i++) {
        [$p0, $c0] = $stops[$i];
        [$p1, $c1] = $stops[$i + 1];
        if ($t <= $p1) {
            $f = ($p1 - $p0) > 0 ? ($t - $p0) / ($p1 - $p0) : 0;
            $r = (int) round($c0[0] + ($c1[0] - $c0[0]) * $f);
            $g = (int) round($c0[1] + ($c1[1] - $c0[1]) * $f);
            $b = (int) round($c0[2] + ($c1[2] - $c0[2]) * $f);
            return sprintf('#%02x%02x%02x', $r, $g, $b);
        }
    }
    return '#facc79';
}

/** Threat level 1-5 to a readable label. */
function threat_label(?int $level): string
{
    return match ($level) {
        1 => t('threat_1'),
        2 => t('threat_2'),
        3 => t('threat_3'),
        4 => t('threat_4'),
        5 => t('threat_5'),
        default => t('threat_none'),
    };
}

/** Truncate for table cells, on a word boundary. */
function excerpt(?string $text, int $max = 120): string
{
    $text = trim((string) $text);
    if ($text === '') {
        return '';
    }
    if (mb_strlen($text) <= $max) {
        return $text;
    }
    $cut = mb_substr($text, 0, $max);
    $sp = mb_strrpos($cut, ' ');
    return rtrim($sp !== false ? mb_substr($cut, 0, $sp) : $cut, ' ,.;') . '…';
}

/** Render page numbers for a result set. */
function pager(int $total, int $page, int $perPage): string
{
    $pages = (int) ceil($total / max(1, $perPage));
    if ($pages < 2) {
        return '';
    }

    $out = '<nav class="pager" aria-label="' . e(t('pagination')) . '">';
    $out .= '<span class="pager-count">' . e(t('showing_n_of_m', [
        'from' => number_format(($page - 1) * $perPage + 1),
        'to'   => number_format(min($total, $page * $perPage)),
        'n'    => number_format($total),
    ])) . '</span>';

    $window = 2;
    $shown = [];
    for ($i = 1; $i <= $pages; $i++) {
        if ($i === 1 || $i === $pages || abs($i - $page) <= $window) {
            $shown[] = $i;
        }
    }

    $last = 0;
    foreach ($shown as $i) {
        if ($last && $i - $last > 1) {
            $out .= '<span class="pager-gap">…</span>';
        }
        $out .= $i === $page
            ? '<span class="pager-page is-current">' . $i . '</span>'
            : '<a class="pager-page" href="' . e(url_with(['page' => $i])) . '">' . $i . '</a>';
        $last = $i;
    }

    return $out . '</nav>';
}

/** Column header that toggles sort direction. */
function sort_link(string $key, string $label): string
{
    $current = (string) get_param('sort', 'name');
    $dir     = strtolower((string) get_param('dir', 'asc'));
    $isOn    = $current === $key;
    $next    = ($isOn && $dir === 'asc') ? 'desc' : 'asc';
    $arrow   = $isOn ? ($dir === 'asc' ? '▲' : '▼') : '';

    return '<a class="sort' . ($isOn ? ' is-active' : '') . '" href="'
        . e(url_with(['sort' => $key, 'dir' => $next, 'page' => null])) . '">'
        . e($label) . '<span class="sort-arrow">' . $arrow . '</span></a>';
}

/** Threat rendered as a five-step block meter rather than a coloured word. */
function threat_meter(?int $level): string
{
    if ($level === null || $level < 1) {
        return '<span class="threat-none">' . e(t('threat_none')) . '</span>';
    }

    $out = '<span class="threat" title="' . e(threat_label($level)) . '" role="img" aria-label="'
         . e(threat_label($level)) . '">';
    for ($i = 1; $i <= 5; $i++) {
        $classes = 'threat-step';
        if ($i <= $level) {
            $classes .= ' is-on';
            if ($level >= 4) {
                $classes .= ' is-high';
            }
        }
        $out .= '<span class="' . $classes . '"></span>';
    }
    return $out . '</span>';
}

/** The thermal staleness indicator used in every list of companies. */
function thermal_cell(?string $lastVisit): string
{
    $heat  = staleness($lastVisit);
    $color = thermal_color($heat);
    $pct   = (int) round($heat * 100);

    return '<span class="trail' . ($heat > .72 ? ' is-cold-trail' : '') . '">'
        . '<span class="thermal" title="' . e(fmt_date($lastVisit)) . '">'
        . '<span class="thermal-fill" style="width:' . $pct . '%;background:' . e($color) . '"></span>'
        . '</span>'
        . '<span class="trail-text">' . e(fmt_ago($lastVisit)) . '</span>'
        . '</span>';
}


/** Upsert the monitoring schedule. $withLastVisit=false leaves the recorded date alone. */
function save_watch(int $companyId, ?int $assignedUser, ?int $frequencyDays,
                    ?string $lastVisit, int $isPaused, bool $withLastVisit): void
{
    if ($withLastVisit) {
        Database::run(
            'INSERT INTO watches (company_id, assigned_user_id, frequency_days, last_visit_date, is_paused)
             VALUES (:c, :u, :f, :l, :p)
             ON DUPLICATE KEY UPDATE assigned_user_id = VALUES(assigned_user_id),
                                     frequency_days   = VALUES(frequency_days),
                                     last_visit_date  = VALUES(last_visit_date),
                                     is_paused        = VALUES(is_paused)',
            ['c' => $companyId, 'u' => $assignedUser, 'f' => $frequencyDays, 'l' => $lastVisit, 'p' => $isPaused]
        );
        return;
    }

    Database::run(
        'INSERT INTO watches (company_id, assigned_user_id, frequency_days, is_paused)
         VALUES (:c, :u, :f, :p)
         ON DUPLICATE KEY UPDATE assigned_user_id = VALUES(assigned_user_id),
                                 frequency_days   = VALUES(frequency_days),
                                 is_paused        = VALUES(is_paused)',
        ['c' => $companyId, 'u' => $assignedUser, 'f' => $frequencyDays, 'p' => $isPaused]
    );
}
