<?php
$configPath = __DIR__ . '/db_config.php';
$config = [];

if (is_file($configPath)) {
    $loaded = require $configPath;
    if (is_array($loaded)) {
        $config = $loaded;
    }
}

$host = $config['host'] ?? getenv('DB_HOST') ?: '';
$dbname = $config['dbname'] ?? getenv('DB_NAME') ?: '';
$user = $config['user'] ?? getenv('DB_USER') ?: '';
$password = $config['password'] ?? getenv('DB_PASSWORD') ?: '';

if (!$host || !$dbname || !$user) {
    http_response_code(500);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['message' => 'Configuration base de donnees manquante.']);
    exit;
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    http_response_code(500);
    header('Content-Type: application/json; charset=utf-8');
    error_log('Database connection failed: ' . $e->getMessage());
    echo json_encode(['message' => 'Connexion base de donnees impossible.']);
    exit;
}
