<?php
/**
 * AJAX — WooCommerce product reviews (inventory › comments).
 */

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

function zerti_ajax_product_reviews_guard(): void
{
    check_ajax_referer('zerti_product_reviews', 'nonce');

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

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

/**
 * @param array<string, mixed> $source
 * @return array{search:string,status:string,kind:string}
 */
function zerti_ajax_product_reviews_list_input_from_array(array $source): array
{
    $search = isset($source['search']) ? sanitize_text_field(wp_unslash((string) $source['search'])) : '';
    $status = isset($source['status']) ? sanitize_key(wp_unslash((string) $source['status'])) : '';
    $kind = zerti_ajax_product_reviews_kind_input_from_array($source, 'review');

    return [
        'search' => $search,
        'status' => $status,
        'kind' => $kind,
    ];
}

/**
 * @param array<string, mixed> $source
 */
function zerti_ajax_product_reviews_kind_input_from_array(array $source, string $default = 'review'): string
{
    if (!isset($source['kind'])) {
        return zerti_product_feedback_kind_is_valid($default) ? $default : 'review';
    }

    $kind = sanitize_key(wp_unslash((string) $source['kind']));

    return zerti_product_feedback_kind_is_valid($kind) ? $kind : 'review';
}

/**
 * @param array<string, mixed> $source
 * @return array{id:int,force:bool}
 */
function zerti_ajax_product_review_delete_input_from_array(array $source): array
{
    $id = isset($source['id']) ? absint(wp_unslash((string) $source['id'])) : 0;
    $force = !empty($source['force']);

    return [
        'id' => $id,
        'force' => $force,
    ];
}

/**
 * @return array{id:int,force:bool}
 */
function zerti_ajax_product_reviews_list(): void
{
    zerti_ajax_product_reviews_guard();

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_product_reviews_guard().
    $input = zerti_ajax_product_reviews_list_input_from_array($post);
    $search = $input['search'];
    $status = $input['status'];
    $kind = $input['kind'];
    $items = zerti_product_reviews_list($search, $status, $kind);

    wp_send_json_success([
        'items' => $items,
        'statuses' => zerti_product_review_status_choices(),
        'total' => count($items),
        'kind' => $kind,
    ]);
}

function zerti_ajax_product_review_save(): void
{
    zerti_ajax_product_reviews_guard();

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_product_reviews_guard().
    $payload = zerti_product_review_payload_from_array($post);
    $result = zerti_product_review_save($payload);

    if (empty($result['ok'])) {
        $code = isset($result['code']) ? (string) $result['code'] : 'save_failed';
        $msg = zerti_product_review_error_message(
            $code,
            isset($result['message']) ? (string) $result['message'] : ''
        );
        wp_send_json_error(['message' => $msg, 'code' => $code], 400);
    }

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_product_reviews_guard().
    $kind = zerti_ajax_product_reviews_kind_input_from_array($post, 'review');

    wp_send_json_success([
        'item' => $result['item'] ?? null,
        'items' => zerti_product_reviews_list('', '', $kind),
    ]);
}

function zerti_ajax_product_review_delete(): void
{
    zerti_ajax_product_reviews_guard();

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_product_reviews_guard().
    $input = zerti_ajax_product_review_delete_input_from_array($post);
    $id = $input['id'];
    $force = $input['force'];
    $result = zerti_product_review_delete($id, $force);

    if (empty($result['ok'])) {
        $code = isset($result['code']) ? (string) $result['code'] : 'delete_failed';
        $msg = zerti_product_review_error_message(
            $code,
            isset($result['message']) ? (string) $result['message'] : ''
        );
        wp_send_json_error(['message' => $msg, 'code' => $code], 400);
    }

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_product_reviews_guard().
    $kind = zerti_ajax_product_reviews_kind_input_from_array($post, 'review');

    wp_send_json_success([
        'items' => zerti_product_reviews_list('', '', $kind),
    ]);
}

