<?php
// Debug simple pour l'action ticket
error_reporting(E_ALL);
ini_set('display_errors', 1);

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

echo "Script debug démarré\n";

// Configuration directe sans EnvLoader
$dbConfig = [
    'host' => 'serverkmaf.helioho.st',
    'port' => '3306',
    'dbname' => 'kombarferd_gestpeseedb',
    'username' => 'kombarferd_dbadmin',
    'password' => 'dbadmin@2024'
];

try {
    echo "Tentative de connexion...\n";
    
    $dsn = "mysql:host={$dbConfig['host']};port={$dbConfig['port']};dbname={$dbConfig['dbname']};charset=utf8mb4";
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    
    echo "Connexion OK\n";
    
    // Test de recherche ticket
    $numTicket = $_GET['numTicket'] ?? '20250906PBS00048';
    echo "Recherche ticket: $numTicket\n";
    
    $sql = "SELECT * FROM pesee WHERE NumTicket = :param";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':param', $numTicket, PDO::PARAM_STR);
    $stmt->execute();
    $ticket = $stmt->fetch();
    
    if ($ticket) {
        echo "Ticket trouvé!\n";
        
        // Supprimer le champ Logo qui contient des données binaires
        unset($ticket['Logo']);
        
        echo "Données ticket (sans Logo): " . print_r($ticket, true) . "\n";
        
        $jsonData = [
            'success' => true,
            'data' => $ticket,
            'message' => 'Debug: Ticket trouvé'
        ];
        
        $jsonString = json_encode($jsonData, JSON_UNESCAPED_UNICODE);
        
        if ($jsonString === false) {
            echo "Erreur JSON encode: " . json_last_error_msg() . "\n";
            echo "Code erreur: " . json_last_error() . "\n";
            
            // Nettoyer les champs problématiques
            $cleanTicket = [];
            foreach ($ticket as $key => $value) {
                if (is_string($value)) {
                    // Supprimer caractères non-UTF8 et convertir
                    $cleanValue = mb_convert_encoding($value, 'UTF-8', 'UTF-8');
                    $cleanValue = filter_var($cleanValue, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
                    $cleanTicket[$key] = $cleanValue;
                } else {
                    $cleanTicket[$key] = $value;
                }
            }
            
            $jsonString = json_encode([
                'success' => true,
                'data' => $cleanTicket,
                'message' => 'Debug: Ticket trouvé (nettoyé)'
            ], JSON_UNESCAPED_UNICODE);
        }
        
        echo "JSON: $jsonString\n";
        echo $jsonString;
    } else {
        echo "Ticket non trouvé\n";
        $jsonData = [
            'success' => false,
            'message' => 'Debug: Ticket non trouvé'
        ];
        $jsonString = json_encode($jsonData);
        echo "JSON: $jsonString\n";  
        echo $jsonString;
    }
    
} catch (Exception $e) {
    echo "Erreur: " . $e->getMessage() . "\n";
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>