<?php
// Include database connection
include 'config/connexion.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' => 'Client cannot be deleted because they have associated policies or payments.']);
    } else {
        // 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()) {
            echo json_encode(['status' => 'success', 'message' => 'Client deleted successfully.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'An error occurred while deleting the client.']);
        }

        $stmt->close();
    }

    // Close the connection
    $conn->close();
} else {
    echo json_encode(['status' => 'invalid', 'message' => 'Invalid request.']);
}
?>

<script>
function deleteClient(clientId) {
    $.post('delete_client.php', { id: clientId }, function (response) {
        const result = JSON.parse(response);
        if (result.status === 'cannot_delete') {
            $('#errorModal .modal-body').text(result.message);
            $('#errorModal').modal('show');
        } else if (result.status === 'success') {
            location.reload();
        } else {
            alert(result.message);
        }
    });
}
</script>