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

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

function zerti_ajax_product_tags_guard(): void
{
    check_ajax_referer('zerti_product_tags', 'nonce');

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

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

/**
 * @param array<string, mixed> $source
 * @return array{term:string}
 */
function zerti_ajax_product_tags_search_input_from_array(array $source): array
{
    $term = isset($source['term']) ? sanitize_text_field(wp_unslash((string) $source['term'])) : '';

    return [
        'term' => $term,
    ];
}

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

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

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

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

function zerti_ajax_product_tags_search(): void
{
    check_ajax_referer('zerti_product_tags', 'nonce');

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

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

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified via check_ajax_referer() above.
    $input = zerti_ajax_product_tags_search_input_from_array($post);
    $term = $input['term'];

    wp_send_json_success([
        'tags' => zerti_product_tags_search_for_picker($term),
    ]);
}

function zerti_ajax_product_tags_list(): void
{
    zerti_ajax_product_tags_guard();

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_product_tags_guard().
    $input = zerti_ajax_product_tags_list_input_from_array($post);
    $search = $input['search'];
    $flat = zerti_product_tags_flat_list();

    if ($search !== '') {
        $needle = mb_strtolower($search, 'UTF-8');
        $flat = array_values(array_filter(
            $flat,
            static function (array $row) use ($needle): bool {
                $name = mb_strtolower((string) ($row['name'] ?? ''), 'UTF-8');
                $slug = mb_strtolower((string) ($row['slug'] ?? ''), 'UTF-8');

                return zerti_str_contains($name, $needle) || zerti_str_contains($slug, $needle);
            }
        ));
    }

    wp_send_json_success([
        'flat' => $flat,
        'tree' => zerti_product_tags_build_tree($flat),
        'parent_options' => zerti_product_tag_parent_options(),
        'total' => count($flat),
    ]);
}

function zerti_ajax_product_tag_save(): void
{
    zerti_ajax_product_tags_guard();

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_product_tags_guard().
    $payload = zerti_product_tag_payload_from_array($post);
    $result = zerti_product_tag_save($payload);

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

    wp_send_json_success([
        'item' => $result['item'] ?? null,
        'flat' => zerti_product_tags_flat_list(),
        'tree' => zerti_product_tags_build_tree(zerti_product_tags_flat_list()),
        'parent_options' => zerti_product_tag_parent_options((int) ($result['item']['id'] ?? 0)),
    ]);
}

function zerti_ajax_product_tag_delete(): void
{
    zerti_ajax_product_tags_guard();

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_product_tags_guard().
    $input = zerti_ajax_product_tag_delete_input_from_array($post);
    $id = $input['id'];
    $result = zerti_product_tag_delete($id);

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

    wp_send_json_success([
        'flat' => zerti_product_tags_flat_list(),
        'tree' => zerti_product_tags_build_tree(zerti_product_tags_flat_list()),
        'parent_options' => zerti_product_tag_parent_options(),
    ]);
}

