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

try {
    $dbHost = 'serverkmaf.helioho.st';
    $dbName = 'kombarferd_gestpeseedb';
    $dbUser = 'kombarferd_dbadmin';
    $dbPass = 'dbadmin@2024';
    
    $dsn = "mysql:host=$dbHost;dbname=$dbName;charset=utf8mb4";
    $pdo = new PDO($dsn, $dbUser, $dbPass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    
    $numTicket = $_GET['numTicket'] ?? '';
    $codePesee = $_GET['codePesee'] ?? '';
    
    if (empty($numTicket) && empty($codePesee)) {
        echo json_encode(['success' => false, 'data' => null, 'message' => 'Numéro de ticket ou code pesée requis']);
        exit;
    }
    
    $searchValue = !empty($numTicket) ? $numTicket : $codePesee;
    
    // Recherche exacte par NumTicket
    $sql = "SELECT * FROM pesee WHERE NumTicket = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$searchValue]);
    $ticket = $stmt->fetch();
    
    // Si pas trouvé, recherche par CodePesee
    if (!$ticket) {
        $sql = "SELECT * FROM pesee WHERE CodePesee = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$searchValue]);
        $ticket = $stmt->fetch();
    }
    
    // Si toujours pas trouvé, recherche approximative
    if (!$ticket) {
        $sql = "SELECT * FROM pesee WHERE NumTicket LIKE ? OR CodePesee LIKE ? ORDER BY ID DESC LIMIT 1";
        $likeParam = '%' . $searchValue . '%';
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$likeParam, $likeParam]);
        $ticket = $stmt->fetch();
    }
    
    if ($ticket) {
        echo json_encode(['success' => true, 'data' => $ticket, 'message' => 'Ticket trouvé']);
    } else {
        echo json_encode(['success' => false, 'data' => null, 'message' => "Ticket non trouvé pour: $searchValue"]);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'data' => null, 'message' => 'Erreur: ' . $e->getMessage()]);
}
?>