<?php
declare(strict_types=1);

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

function now(): string
{
    return date('Y-m-d H:i:s');
}

function digits_only(string $value): string
{
    return preg_replace('/\D+/', '', $value) ?? '';
}

function money_format_ir(int $amount): string
{
    return number_format($amount) . ' تومان';
}

function json_response(array $data, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function request_json(): array
{
    $raw = file_get_contents('php://input') ?: '';
    $data = json_decode($raw, true);
    return is_array($data) ? $data : $_POST;
}

function app_log(string $message, array $context = []): void
{
    $dir = dirname(__DIR__) . '/storage/logs';
    if (!is_dir($dir)) {
        @mkdir($dir, 0775, true);
    }
    $line = '[' . date('c') . '] ' . $message;
    if ($context) {
        $line .= ' ' . json_encode($context, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }
    @file_put_contents($dir . '/app.log', $line . PHP_EOL, FILE_APPEND | LOCK_EX);
}

function env_bool(mixed $v): bool
{
    return in_array(strtolower((string)$v), ['1','true','yes','on'], true);
}


function fa_date(?string $value): string
{
    if (!$value) return '-';
    $ts = strtotime($value);
    if (!$ts) return (string)$value;
    return date('Y/m/d H:i', $ts);
}

function user_display_name(array $user): string
{
    $name = trim((string)($user['first_name'] ?? '') . ' ' . (string)($user['last_name'] ?? ''));
    return $name !== '' ? $name : 'بدون نام';
}

function activity_notify(Repository $repo, array $config, string $text): void
{
    $chatId = trim((string)($repo->setting('activity_log_chat_id', (string)($config['activity_log_chat_id'] ?? '')) ?? ''));
    if ($chatId === '') return;
    try {
        $tg = new Telegram((string)$config['main_bot_token']);
        $tg->sendMessage($chatId, $text);
    } catch (Throwable $e) {
        app_log('activity notify failed', ['error' => $e->getMessage(), 'chat_id' => $chatId]);
    }
}

function format_user_for_log(array $user): string
{
    $name = h(user_display_name($user));
    $tid = h((string)($user['telegram_id'] ?? '-'));
    $username = !empty($user['username']) ? '@' . h((string)$user['username']) : '-';
    return "<b>{$name}</b> | <code>{$tid}</code> | {$username}";
}
