<?php
// ticket.php - Endpoint autonome pour récupérer les tickets
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

function jsonResponse($data, $success = true, $message = '') {
    $response = [
        'success' => $success,
        'data' => $data,
        'message' => $message,
        'timestamp' => date('Y-m-d H:i:s')
    ];
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    // Configuration de base de données
    $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,
    ]);
    
    // Récupérer les paramètres
    $numTicket = $_GET['numTicket'] ?? '';
    $codePesee = $_GET['codePesee'] ?? '';
    
    if (empty($numTicket) && empty($codePesee)) {
        jsonResponse(null, false, 'Numéro de ticket ou code pesée requis');
    }
    
    $searchValue = !empty($numTicket) ? $numTicket : $codePesee;
    $ticket = null;
    
    // Essayer d'abord avec NumTicket
    $sql = "SELECT * FROM pesee WHERE NumTicket = :param";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':param', $searchValue, PDO::PARAM_STR);
    $stmt->execute();
    $ticket = $stmt->fetch();
    
    // Si pas trouvé avec NumTicket, essayer avec CodePesee
    if (!$ticket) {
        $sql = "SELECT * FROM pesee WHERE CodePesee = :param";
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':param', $searchValue, PDO::PARAM_STR);
        $stmt->execute();
        $ticket = $stmt->fetch();
    }
    
    // Si toujours pas trouvé, essayer une recherche approximative (LIKE)
    if (!$ticket) {
        $sql = "SELECT * FROM pesee WHERE NumTicket LIKE :param OR CodePesee LIKE :param ORDER BY ID DESC LIMIT 1";
        $likeParam = '%' . $searchValue . '%';
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':param', $likeParam, PDO::PARAM_STR);
        $stmt->execute();
        $ticket = $stmt->fetch();
    }
    
    if ($ticket) {
        jsonResponse($ticket, true, 'Ticket trouvé');
    } else {
        jsonResponse(null, false, "Ticket non trouvé pour: $searchValue");
    }
    
} catch (Exception $e) {
    jsonResponse(null, false, 'Erreur: ' . $e->getMessage());
}
?>