<?php
/**
 * Block Direct Card-Testing POSTs to wc-ajax=checkout
 * and Log Suspicious Attempts
 */

if ( ! defined( 'ABSPATH' ) ) {
	http_response_code(403);
	exit;
}

add_action('init', function () {

    // Only target the checkout ajax endpoint
    if (isset($_GET['wc-ajax']) && $_GET['wc-ajax'] === 'checkout') {

        $has_cart_cookie =
            isset($_COOKIE['woocommerce_cart_hash']) ||
            isset($_COOKIE['woocommerce_cart']) ||
            isset($_COOKIE['woocommerce_items_in_cart']);

        // If no WooCommerce session/cart cookies => likely bot / scripted request
        if (!$has_cart_cookie) {

            // Prepare log directory + file
            $log_dir = WP_CONTENT_DIR . '/logs';
            if (!file_exists($log_dir)) {
                wp_mkdir_p($log_dir);
            }
            $log_file = $log_dir . '/wc-checkout-block.log';

            // Log details
            $entry = sprintf(
                "[%s] BLOCKED wc-ajax=checkout\nIP: %s\nUA: %s\nPOST Keys: %s\n---\n",
                date('Y-m-d H:i:s'),
                $_SERVER['REMOTE_ADDR'] ?? 'unknown',
                $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
                isset($_POST) ? implode(',', array_keys($_POST)) : 'none'
            );

            // Write log entry
            file_put_contents($log_file, $entry, FILE_APPEND);

            // Kill the request
            wp_die('Checkout request blocked. Nice try.', 'Blocked', [
                'response' => 403
            ]);
        }
    }
});
