<?php
declare(strict_types=1);

// PHP 8.0 polyfills — compatibilité PHP 7.x
if (!function_exists('str_starts_with')) {
    function str_starts_with(string $haystack, string $needle): bool {
        return strlen($needle) === 0 || strpos($haystack, $needle) === 0;
    }
}
if (!function_exists('str_ends_with')) {
    function str_ends_with(string $haystack, string $needle): bool {
        return strlen($needle) === 0 || substr($haystack, -strlen($needle)) === $needle;
    }
}
if (!function_exists('str_contains')) {
    function str_contains(string $haystack, string $needle): bool {
        return strlen($needle) === 0 || strpos($haystack, $needle) !== false;
    }
}

/**
 * Centralized configuration
 */
define('APP_ROOT', dirname(__DIR__));
define('UPLOADS_DIR', APP_ROOT . '/uploads');
define('EXPORTS_DIR', APP_ROOT . '/exports');
define('LOGS_DIR', APP_ROOT . '/logs');
define('DB_PATH', APP_ROOT . '/database.sqlite');
define('APP_VERSION', '1.0.0');

// Upload limits
define('MAX_UPLOAD_SIZE_MB', 50);
define('MAX_UPLOAD_BYTES', MAX_UPLOAD_SIZE_MB * 1024 * 1024);
define('ALLOWED_EXTENSIONS', ['xlsx', 'xls', 'csv']);
define('ALLOWED_MIMES', [
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-excel',
    'text/csv',
    'text/plain',
    'application/csv',
    'application/octet-stream',
]);

// Scraping defaults
define('DEFAULT_TIMEOUT', 20);
define('DEFAULT_USER_AGENT', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
define('DEFAULT_DELAY_MS', 500);
define('DEFAULT_MAX_RETRIES', 3);
define('DEFAULT_BATCH_SIZE', 20);
define('MAX_REDIRECTS', 10);

// Session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Error reporting (suppress in production, show in dev)
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', LOGS_DIR . '/php_errors.log');

// Memory & time limits
ini_set('memory_limit', '512M');
set_time_limit(0);

// Timezone
date_default_timezone_set('UTC');

// Ensure directories exist
foreach ([UPLOADS_DIR, EXPORTS_DIR, LOGS_DIR] as $dir) {
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
}
