<?php
// Include database connection
include 'config/connexion.php';
include 'includes/simple_log.php';
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $typeId = intval($_POST['id']);
    
    // First, get the type name for logging
    $selectQuery = "SELECT type FROM policy_type WHERE id = ?";
    $selectStmt = $conn->prepare($selectQuery);
    $selectStmt->bind_param("i", $typeId);
    $selectStmt->execute();
    $result = $selectStmt->get_result();
    
    if ($result->num_rows > 0) {
        $typeData = $result->fetch_assoc();
        $typeName = $typeData['type'];
        
        // Check if this type is being used in any policies
        $checkQuery = "SELECT COUNT(*) as count FROM policy_table WHERE policy_type = ?";
        $checkStmt = $conn->prepare($checkQuery);
        $checkStmt->bind_param("s", $typeName);
        $checkStmt->execute();
        $checkResult = $checkStmt->get_result();
        $checkData = $checkResult->fetch_assoc();
        
        if ($checkData['count'] > 0) {
            echo "Erreur: Ce type de police est utilisé par " . $checkData['count'] . " police(s). Impossible de le supprimer.";
        } else {
            // Delete the type
            $deleteQuery = "DELETE FROM policy_type WHERE id = ?";
            $deleteStmt = $conn->prepare($deleteQuery);
            $deleteStmt->bind_param("i", $typeId);
            
            if ($deleteStmt->execute()) {
                // Enregistrer la suppression du type de police dans le log global
                logPolicyTypeDeletion($typeName);
                echo "success";
            } else {
                echo "Erreur lors de la suppression du type de police.";
            }
            $deleteStmt->close();
        }
        $checkStmt->close();
    } else {
        echo "Type de police introuvable.";
    }
    $selectStmt->close();
} else {
    echo "Requête invalide.";
}

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