<?php
/**
 * Fichier de configuration principal
 * Base de données : nukunu_mofiala
 */

define('DB_HOST', 'localhost');
define('DB_NAME', 'nukunu_mofiala');
define('DB_USER', 'root');
define('DB_PASS', getenv('DB_PASS') ?: '');

$rawHost = $_SERVER['HTTP_HOST'] ?? 'localhost';
if (!preg_match('/^[a-zA-Z0-9.:-]+$/', $rawHost)) { $rawHost = 'localhost'; }

// Détection automatique du dossier d'installation (racine ou sous-dossier)
$appDir   = str_replace('\\', '/', dirname(__DIR__));
$docRoot  = str_replace('\\', '/', rtrim((string)($_SERVER['DOCUMENT_ROOT'] ?? ''), '/'));
$basePath = '';
if ($docRoot !== '' && $appDir !== $docRoot && strpos($appDir . '/', $docRoot . '/') === 0) {
    $basePath = substr($appDir, strlen($docRoot));
}
define('BASE_PATH', $basePath . '/');
define('BASE_URL', (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . $rawHost . BASE_PATH);

define('APP_ENV', getenv('APP_ENV') ?: 'development');
define('BCRYPT_COST', 13);
define('CURRENCY', 'FCFA');

if (session_status() === PHP_SESSION_NONE) {
    session_set_cookie_params([
        'lifetime' => 0,
        'path'     => '/',
        'domain'   => '',
        'secure'   => !empty($_SERVER['HTTPS']),
        'httponly' => true,
        'samesite' => 'Strict',
    ]);
    session_start();
}

header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');

// Compression Gzip (sauf exports PDF/CSV/print)
if (empty($_GET['export']) && empty($_GET['template']) && empty($_GET['download']) && empty($_GET['print']) && empty($_GET['pdf'])) {
    if (extension_loaded('zlib') && !ini_get('zlib.output_compression') && ob_get_level() === 0) {
        ob_start('ob_gzhandler');
    }
}

if (APP_ENV === 'production') {
    header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
}

// Connexion à la base de données
try {
    $pdo = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false, // Vrais prepared statements
        ]
    );
} catch (PDOException $e) {
    // Ne jamais exposer les détails de connexion en production
    if (APP_ENV === 'development') {
        die("Erreur de connexion : " . htmlspecialchars($e->getMessage()));
    } else {
        error_log("DB Connection error: " . $e->getMessage());
        die("Une erreur technique est survenue. Veuillez réessayer plus tard.");
    }
}
