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

// Check if the request method is POST and the ID is provided
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $clientId = intval($_POST['id']);

    // Check if the client has any policies or payments
    $queryCheck = "
        SELECT 
            (SELECT COUNT(*) FROM policy_table WHERE client_cin = (SELECT client_cin FROM clients_table WHERE id = ?)) AS policies_count,
            (SELECT COUNT(*) FROM receipts_table WHERE client_cin = (SELECT client_cin FROM clients_table WHERE id = ?)) AS payments_count
    ";
    $stmtCheck = $conn->prepare($queryCheck);
    $stmtCheck->bind_param("ii", $clientId, $clientId);
    $stmtCheck->execute();
    $resultCheck = $stmtCheck->get_result();
    $rowCheck = $resultCheck->fetch_assoc();
    $stmtCheck->close();    if ($rowCheck['policies_count'] > 0 || $rowCheck['payments_count'] > 0) {
        echo json_encode(['status' => 'cannot_delete', 'message' => 'Impossible de supprimer ce client.']);
    } else {
        // Récupérer les informations du client avant suppression pour le log
        $queryClient = "SELECT client_name, client_cin, n_dossier FROM clients_table WHERE id = ?";
        $stmtClient = $conn->prepare($queryClient);
        $stmtClient->bind_param("i", $clientId);
        $stmtClient->execute();
        $resultClient = $stmtClient->get_result();
        $clientInfo = $resultClient->fetch_assoc();
        $stmtClient->close();
        
        // Prepare and execute the delete query
        $query = "DELETE FROM clients_table WHERE id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $clientId);

        if ($stmt->execute()) {
            // Enregistrer la suppression dans le log si les informations client sont disponibles
            if ($clientInfo) {
                logClientDeletion($clientInfo['client_name'], $clientInfo['client_cin'], $clientInfo['n_dossier']);
            }
            
            echo json_encode(['status' => 'success', 'message' => 'Client supprimé avec succès.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Erreur lors de la suppression du client.']);
        }

        $stmt->close();
    }

    // Close the connection
    // Connection is managed globally; do not close it here.
} else {
    echo 'invalid';
}
?>
