<?php
/**
 * AJAX — WooCommerce coupons (Financial › Coupons).
 */

if (!defined('ABSPATH')) {
    exit;
}

function zerti_ajax_wc_coupons_guard(): void
{
    check_ajax_referer('zerti_wc_coupons', 'nonce');

    if (!zerti_user_can_access_admin() || !zerti_user_can_manage_wc_coupons()) {
        wp_send_json_error(['message' => 'forbidden'], 403);
    }

    if (!zerti_wc_coupons_available()) {
        wp_send_json_error(['message' => 'woocommerce_required'], 400);
    }
}

function zerti_ajax_wc_coupons_grid(): void
{
    zerti_ajax_wc_coupons_guard();

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_wc_coupons_guard().
    $input = zerti_wc_coupons_grid_input_from_array($post);

    $result = zerti_fetch_wc_coupons_grid($input);
    if (is_wp_error($result)) {
        $status = (int) ($result->get_error_data()['status'] ?? 400);
        wp_send_json_error(['message' => $result->get_error_code()], $status > 0 ? $status : 400);
    }

    wp_send_json_success($result);
}

function zerti_ajax_wc_coupon_editor(): void
{
    zerti_ajax_wc_coupons_guard();

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_wc_coupons_guard().
    $coupon_id = isset($post['coupon_id']) ? absint((string) $post['coupon_id']) : 0;

    ob_start();
    zerti_render_wc_coupon_editor($coupon_id);
    $html = ob_get_clean();

    wp_send_json_success([
        'html' => $html,
        'coupon_id' => $coupon_id,
        'is_new' => $coupon_id <= 0,
    ]);
}

function zerti_ajax_wc_coupon_save(): void
{
    zerti_ajax_wc_coupons_guard();

    $allowed_keys = [
        'coupon_id',
        'post_title',
        'excerpt',
        'discount_type',
        'coupon_amount',
        'expiry_date',
        'individual_use',
        'product_ids',
        'exclude_product_ids',
        'usage_limit',
        'usage_limit_per_user',
        'limit_usage_to_x_items',
        'free_shipping',
        'product_categories',
        'exclude_product_categories',
        'exclude_sale_items',
        'minimum_amount',
        'maximum_amount',
        'customer_email',
    ];

    $payload = [];
    $post = zerti_unslash_post_array();
    foreach ($allowed_keys as $key) {
        if (!isset($post[$key])) {
            continue;
        }
        $value = $post[$key];
        if (is_array($value)) {
            $payload[$key] = map_deep($value, static function ($item) {
                return is_scalar($item) ? sanitize_text_field((string) $item) : '';
            });
        } else {
            $payload[$key] = sanitize_text_field((string) $value);
        }
    }

    $result = zerti_wc_coupon_save_from_payload($payload);
    if (is_wp_error($result)) {
        $status = (int) ($result->get_error_data()['status'] ?? 400);
        wp_send_json_error(
            [
                'message' => $result->get_error_message(),
                'code' => $result->get_error_code(),
            ],
            $status > 0 ? $status : 400
        );
    }

    wp_send_json_success($result);
}

function zerti_ajax_wc_coupon_delete(): void
{
    zerti_ajax_wc_coupons_guard();

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_wc_coupons_guard().
    $coupon_id = isset($post['coupon_id']) ? absint((string) $post['coupon_id']) : 0;
    $result = zerti_wc_coupon_delete($coupon_id);
    if (is_wp_error($result)) {
        $status = (int) ($result->get_error_data()['status'] ?? 400);
        wp_send_json_error(['message' => $result->get_error_message()], $status > 0 ? $status : 400);
    }

    wp_send_json_success(['deleted' => true]);
}

