<?php
/**
 * Configuration API PCC
 * Connexion aux bases de données distantes (cPanel)
 */

// Catch all PHP errors and return them as JSON
error_reporting(E_ALL);
ini_set('display_errors', 0);

register_shutdown_function(function() {
    $error = error_get_last();
    if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        if (!headers_sent()) {
            header('Content-Type: application/json; charset=utf-8');
            header('Access-Control-Allow-Origin: *');
        }
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => 'Erreur interne: ' . $error['message'] . ' (fichier: ' . basename($error['file']) . ', ligne: ' . $error['line'] . ')'
        ]);
    }
});

set_error_handler(function($severity, $message, $file, $line) {
    if (!headers_sent()) {
        header('Content-Type: application/json; charset=utf-8');
    }
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Erreur PHP: ' . $message . ' (fichier: ' . basename($file) . ', ligne: ' . $line . ')'
    ]);
    exit();
});

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Gérer les requêtes OPTIONS (preflight CORS)
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Identifiants base de données distante
define('DB_HOST', 'localhost');
define('DB_USER', 'transubd_transub_user');
define('DB_PASS', 'Tr@nsub2@24');
define('DB_NAME_PARCS', 'transubd_gestionparc');
define('DB_NAME_RH', 'transubd_GRH');

/**
 * Connexion à la base de données distante
 */
function getConnection($dbName) {
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, $dbName);
    
    if ($conn->connect_error) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => 'Erreur de connexion: ' . $conn->connect_error
        ]);
        exit();
    }
    
    $conn->set_charset("utf8mb4");
    $conn->query("SET time_zone = '+01:00'");
    
    return $conn;
}

/**
 * Envoyer une réponse JSON de succès
 */
function sendSuccess($data = [], $message = 'Succès') {
    echo json_encode([
        'success' => true,
        'message' => $message,
        'data' => $data
    ]);
    exit();
}

/**
 * Envoyer une réponse JSON d'erreur
 */
function sendError($message = 'Erreur', $httpCode = 400) {
    http_response_code($httpCode);
    echo json_encode([
        'success' => false,
        'error' => $message
    ]);
    exit();
}

/**
 * Récupérer les paramètres POST (JSON ou formulaire)
 */
function getPostData() {
    $contentType = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '';
    
    if (strpos($contentType, 'application/json') !== false) {
        $input = file_get_contents('php://input');
        return json_decode($input, true) ?? [];
    }
    
    return $_POST;
}