<?php
// config.php - Configuration sécurisée avec variables d'environnement
require_once 'EnvLoader.php';

class DatabaseConfig {
    
    private static $dbHost;
    private static $dbName;
    private static $dbUser;
    private static $dbPass;
    private static $dbPort;
    
    private static $connection = null;
    
    /**
     * Initialiser les paramètres de base de données depuis l'environnement
     */
    private static function initConfig() {
        if (self::$dbHost === null) {
            // Charger les variables d'environnement
            EnvLoader::load();
            
            // Vérifier que les variables requises sont définies
            EnvLoader::checkRequired(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS', 'DB_PORT']);
            
            self::$dbHost = EnvLoader::get('DB_HOST');
            self::$dbName = EnvLoader::get('DB_NAME');
            self::$dbUser = EnvLoader::get('DB_USER');
            self::$dbPass = EnvLoader::get('DB_PASS');
            self::$dbPort = EnvLoader::get('DB_PORT', '3306');
        }
    }
    
    public static function getConnection() {
        if (self::$connection === null) {
            try {
                self::initConfig();
                
                $dsn = "mysql:host=" . self::$dbHost . 
                       ";port=" . self::$dbPort . 
                       ";dbname=" . self::$dbName . 
                       ";charset=utf8mb4";
                
                $options = [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false,
                ];
                
                self::$connection = new PDO($dsn, self::$dbUser, self::$dbPass, $options);
                error_log("Connexion à la base de données réussie - " . date('Y-m-d H:i:s'));
                
            } catch (PDOException $e) {
                error_log("Erreur de connexion à la base de données: " . $e->getMessage());
                http_response_code(500);
                echo json_encode([
                    'error' => true,
                    'message' => 'Erreur de connexion à la base de données'
                ]);
                exit;
            }
        }
        
        return self::$connection;
    }
    
    public static function closeConnection() {
        self::$connection = null;
    }
    
    public static function testConnection() {
        try {
            $pdo = self::getConnection();
            $stmt = $pdo->query("SELECT 1");
            return true;
        } catch (Exception $e) {
            return false;
        }
    }
    
    /**
     * Obtenir la configuration de sécurité
     */
    public static function getSecurityConfig() {
        EnvLoader::load();
        
        return [
            'jwt_secret' => EnvLoader::get('JWT_SECRET'),
            'max_login_attempts' => (int) EnvLoader::get('MAX_LOGIN_ATTEMPTS', 5),
            'session_timeout' => (int) EnvLoader::get('SESSION_TIMEOUT', 3600),
            'api_timeout' => (int) EnvLoader::get('API_TIMEOUT', 30),
            'app_env' => EnvLoader::get('APP_ENV', 'production')
        ];
    }
    
    /**
     * Vérifier si l'environnement est en développement
     */
    public static function isDevelopment() {
        EnvLoader::load();
        return EnvLoader::get('APP_ENV', 'production') === 'development';
    }
}

// Classes utilitaires
class Utils {
    public static function setCorsHeaders() {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        header("Content-Type: application/json; charset=UTF-8");
        
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            http_response_code(200);
            exit;
        }
    }
    
    public static function jsonResponse($data, $success = true, $message = '', $httpCode = 200) {
        http_response_code($httpCode);
        
        $response = [
            'success' => $success,
            'data' => $data,
            'message' => $message,
            'timestamp' => date('Y-m-d H:i:s')
        ];
        
        echo json_encode($response, JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    public static function errorResponse($message, $httpCode = 400, $details = null) {
        $data = ['error_details' => $details];
        self::jsonResponse($data, false, $message, $httpCode);
    }
    
    public static function sanitizeInput($input) {
        require_once 'InputValidator.php';
        return InputValidator::sanitizeInput($input);
    }
    
    /**
     * Validation avancée des entrées avec gestion d'erreurs
     */
    public static function validateInput($data, $rules = null) {
        try {
            require_once 'InputValidator.php';
            return InputValidator::validateMultiple($data, $rules);
        } catch (ValidationException $e) {
            self::errorResponse($e->getMessage(), 400, $e->getDetails());
        }
    }
    
    public static function getJsonInput() {
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            self::errorResponse('Format JSON invalide');
        }
        
        return self::sanitizeInput($data);
    }
    
    public static function logError($message, $context = []) {
        $logMessage = date('Y-m-d H:i:s') . " - " . $message;
        if (!empty($context)) {
            $logMessage .= " - Context: " . json_encode($context);
        }
        error_log($logMessage);
    }
}

// Configuration des erreurs PHP
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/error.log');

date_default_timezone_set('Africa/Abidjan');
?>