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

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

function zerti_ajax_product_attributes_guard(): void
{
    check_ajax_referer('zerti_product_attributes', 'nonce');

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

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

function zerti_ajax_product_attributes_list(): void
{
    zerti_ajax_product_attributes_guard();

    // phpcs:disable WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_product_attributes_guard().
    $search = isset($_POST['search']) ? sanitize_text_field(wp_unslash((string) $_POST['search'])) : '';
    $items = zerti_product_attributes_list();

    if ($search !== '') {
        $needle = mb_strtolower($search, 'UTF-8');
        $items = array_values(array_filter(
            $items,
            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);
            }
        ));
    }

    $attribute_id = isset($_POST['attribute_id']) ? absint(wp_unslash((string) $_POST['attribute_id'])) : 0;
    $terms = [];
    $active = null;
    if ($attribute_id > 0) {
        $active = zerti_product_attribute_get($attribute_id);
        if ($active !== null) {
            $term_search = isset($_POST['term_search']) ? sanitize_text_field(wp_unslash((string) $_POST['term_search'])) : '';
            $terms = zerti_product_attribute_terms_list($attribute_id, $term_search);
        }
    }
    // phpcs:enable WordPress.Security.NonceVerification.Missing

    wp_send_json_success([
        'attributes' => $items,
        'active' => $active,
        'terms' => $terms,
        'types' => zerti_product_attribute_type_choices(),
        'order_by_options' => zerti_product_attribute_orderby_choices(),
        'total' => count($items),
    ]);
}

function zerti_ajax_product_attribute_save(): void
{
    zerti_ajax_product_attributes_guard();

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_product_attributes_guard().
    $payload = zerti_product_attribute_payload_from_array($post);
    $result = zerti_product_attribute_save($payload);

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

    $saved_id = (int) ($result['item']['id'] ?? 0);

    wp_send_json_success([
        'item' => $result['item'] ?? null,
        'attributes' => zerti_product_attributes_list(),
        'active' => $saved_id > 0 ? zerti_product_attribute_get($saved_id) : null,
        'terms' => $saved_id > 0 ? zerti_product_attribute_terms_list($saved_id) : [],
    ]);
}

function zerti_ajax_product_attribute_delete(): void
{
    zerti_ajax_product_attributes_guard();

    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_product_attributes_guard().
    $id = isset($_POST['id']) ? absint(wp_unslash((string) $_POST['id'])) : 0;
    $result = zerti_product_attribute_delete($id);

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

    wp_send_json_success([
        'attributes' => zerti_product_attributes_list(),
        'active' => null,
        'terms' => [],
    ]);
}

function zerti_ajax_product_attribute_term_save(): void
{
    zerti_ajax_product_attributes_guard();

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_product_attributes_guard().
    $payload = zerti_product_attribute_term_payload_from_array($post);
    $result = zerti_product_attribute_term_save($payload);

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

    $attribute_id = (int) ($payload['attribute_id'] ?? 0);

    wp_send_json_success([
        'item' => $result['item'] ?? null,
        'terms' => zerti_product_attribute_terms_list($attribute_id),
        'active' => zerti_product_attribute_get($attribute_id),
        'attributes' => zerti_product_attributes_list(),
    ]);
}

function zerti_ajax_product_attribute_term_delete(): void
{
    zerti_ajax_product_attributes_guard();

    // phpcs:disable WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_product_attributes_guard().
    $attribute_id = isset($_POST['attribute_id']) ? absint(wp_unslash((string) $_POST['attribute_id'])) : 0;
    $term_id = isset($_POST['term_id']) ? absint(wp_unslash((string) $_POST['term_id'])) : 0;
    // phpcs:enable WordPress.Security.NonceVerification.Missing
    $result = zerti_product_attribute_term_delete($attribute_id, $term_id);

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

    wp_send_json_success([
        'terms' => zerti_product_attribute_terms_list($attribute_id),
        'active' => zerti_product_attribute_get($attribute_id),
        'attributes' => zerti_product_attributes_list(),
    ]);
}

