<?php
// helpers.php - Utility functions for validation and sanitization

/**
 * Sanitize string input
 */
function sanitizeString($input) {
    if (is_null($input)) return '';
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

/**
 * Sanitize numeric input
 */
function sanitizeNumber($input, $default = 0) {
    $num = filter_var($input, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
    return is_numeric($num) ? floatval($num) : $default;
}

/**
 * Sanitize integer input
 */
function sanitizeInt($input, $default = 0) {
    $num = filter_var($input, FILTER_SANITIZE_NUMBER_INT);
    return is_numeric($num) ? intval($num) : $default;
}

/**
 * Validate email
 */
function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

/**
 * Validate phone number (Malaysian format)
 */
function validatePhone($phone) {
    $phone = preg_replace('/[^0-9]/', '', $phone);
    return preg_match('/^01[0-9]{8,9}$/', $phone);
}

/**
 * Sanitize phone number
 */
function sanitizePhone($phone) {
    return preg_replace('/[^0-9-]/', '', $phone);
}

/**
 * Validate job ID format
 */
function validateJobId($jobId) {
    return preg_match('/^(JS|IV)-(SG|SR)\d{5}$/', $jobId);
}

/**
 * Escape for HTML output
 */
function escapeHtml($text) {
    if (is_null($text)) return '';
    return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

/**
 * Validate date format
 */
function validateDate($date, $format = 'Y-m-d') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) === $date;
}

/**
 * Get config value with env > config.php > default precedence.
 *
 * The env-var name is derived by upper-casing the dotted key and replacing
 * '.' with '_', prefixed with FONFIX_. Example:
 *   getConfig('database.password')  reads FONFIX_DATABASE_PASSWORD first.
 *
 * Common short aliases also checked (e.g. FONFIX_DB_PASS) to match the
 * names documented in config.sample.php.
 */
function getConfig($key, $default = null) {
    static $config = null;
    if ($config === null) {
        $configFile = __DIR__ . '/config.php';
        $config = file_exists($configFile) ? require $configFile : [];
    }

    $envCandidates = ['FONFIX_' . strtoupper(str_replace('.', '_', $key))];
    static $aliasMap = [
        'database.host'              => 'FONFIX_DB_HOST',
        'database.dbname'            => 'FONFIX_DB_NAME',
        'database.username'          => 'FONFIX_DB_USER',
        'database.password'          => 'FONFIX_DB_PASS',
        'database.charset'           => 'FONFIX_DB_CHARSET',
        'backup_sync.secret_key'     => 'FONFIX_BACKUP_SECRET',
        'backup_sync.target_url'     => 'FONFIX_BACKUP_URL',
        'backup_sync.cron_key'       => 'FONFIX_CRON_KEY',
        'backup_sync.monitor_token'  => 'FONFIX_MONITOR_TOKEN',
        'telegram.bot_token'         => 'FONFIX_TELEGRAM_BOT_TOKEN',
        'telegram.chat_id'           => 'FONFIX_TELEGRAM_CHAT_ID',
        'security.session_lifetime'  => 'FONFIX_SESSION_LIFETIME',
    ];
    if (isset($aliasMap[$key])) {
        $envCandidates[] = $aliasMap[$key];
    }
    foreach ($envCandidates as $envName) {
        $v = getenv($envName);
        if ($v !== false && $v !== '') {
            return $v;
        }
    }

    $value = $config;
    foreach (explode('.', $key) as $k) {
        if (is_array($value) && array_key_exists($k, $value)) {
            $value = $value[$k];
        } else {
            return $default;
        }
    }
    return $value;
}
?>
