<?php
// Include database connection
include 'config/connexion.php';
include 'includes/simple_log.php';
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json');

// Log pour débogage (optionnel)
error_log("Delete request received: " . print_r($_POST, true));

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $id = intval($_POST['id']); // Utiliser intval pour s'assurer que c'est un entier
    
    // Validate ID
    if ($id <= 0) {
        echo json_encode(['success' => false, 'message' => 'ID invalide: ' . $id]);
        exit;
    }
      // Check if marque exists
    $checkQuery = "SELECT id, marque FROM marques_transport WHERE id = ?";
    $checkStmt = $conn->prepare($checkQuery);
    
    if (!$checkStmt) {
        echo json_encode(['success' => false, 'message' => 'Erreur de préparation de requête: ' . $conn->error]);
        exit;
    }
    
    $checkStmt->bind_param("i", $id);
    $checkStmt->execute();
    $result = $checkStmt->get_result();
    
    if ($result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Marque non trouvée avec ID: ' . $id]);
        $checkStmt->close();
        exit;
    }
    
    $marqueData = $result->fetch_assoc();
    $checkStmt->close();
    
    // Delete the marque
    $deleteQuery = "DELETE FROM marques_transport WHERE id = ?";
    $deleteStmt = $conn->prepare($deleteQuery);
    
    if (!$deleteStmt) {
        echo json_encode(['success' => false, 'message' => 'Erreur de préparation de suppression: ' . $conn->error]);
        exit;
    }
    
    $deleteStmt->bind_param("i", $id);
      if ($deleteStmt->execute()) {
        // Enregistrer la suppression de la marque dans le log global
        logMarqueDeletion($marqueData['marque']);
        
        echo json_encode(['success' => true, 'message' => 'Marque supprimée avec succès: ' . $marqueData['marque']]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Erreur lors de la suppression: ' . $deleteStmt->error]);
    }
    
    $deleteStmt->close();
} else {
    $method = $_SERVER['REQUEST_METHOD'] ?? 'UNKNOWN';
    $hasId = isset($_POST['id']) ? 'YES' : 'NO';
    echo json_encode(['success' => false, 'message' => 'Requête invalide - Method: ' . $method . ', ID présent: ' . $hasId]);
}

// Connection is managed globally; do not close it here.
?>
