<?php
require_once __DIR__ . '/../config/config.php';

function sanitizeInput($input) {
    if (is_array($input)) {
        return array_map('sanitizeInput', $input);
    }
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

function formatDate($date) {
    return date('Y-m-d', strtotime($date));
}

function generateExportFilename($type) {
    return $type . '_' . date('Y-m-d') . '.json';
}

function ensureExportDirectory() {
    if (!file_exists(EXPORT_DESTINATION)) {
        mkdir(EXPORT_DESTINATION, 0755, true);
    }
}

/**
 * Base path prefix for JSON API under this app (e.g. /familyHub/api).
 */
function familyHubWebApiBase(): string {
    $sd = dirname($_SERVER['SCRIPT_NAME'] ?? '/');
    $sd = rtrim(str_replace('\\', '/', $sd), '/');
    if ($sd === '' || $sd === '/') {
        return '/api';
    }
    return $sd . '/api';
}

/**
 * Bitmask for json_encode so pasted recipe text (or any user string) with malformed UTF-8
 * does not make json_encode return false. Without substitution, failed embeds emit an empty
 * &lt;script type="application/json"&gt; and the meals UI hits JSON.parse errors.
 *
 * @return int
 */
function familyHubJsonEncodeShellFlags(): int {
    $f = JSON_UNESCAPED_UNICODE;
    if (defined('JSON_INVALID_UTF8_SUBSTITUTE')) {
        $f |= JSON_INVALID_UTF8_SUBSTITUTE;
    }
    return $f;
}

/**
 * Lowercase for comparisons and keys. Uses mbstring when available; otherwise ASCII-only strtolower
 * so grocery/chore code does not fatal on hosts without ext-mbstring.
 */
function familyHubStrLowerUtf8(string $s): string {
    if (function_exists('mb_strtolower')) {
        return mb_strtolower($s, 'UTF-8');
    }
    return strtolower($s);
}
