<?php
/**
 * AJAX — product attribute groups (inventory › attribute groups).
 */

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

function zerti_ajax_product_attribute_groups_guard(): void
{
    check_ajax_referer('zerti_product_attribute_groups', 'nonce');

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

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

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

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

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

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

/**
 * @return array{id:int}
 */
function zerti_ajax_product_attribute_groups_list(): void
{
    zerti_ajax_product_attribute_groups_guard();

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_product_attribute_groups_guard().
    $input = zerti_ajax_product_attribute_groups_list_input_from_array($post);
    $search = $input['search'];
    $items = zerti_product_attribute_groups_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);
            }
        ));
    }

    $group_id = $input['group_id'];
    $active = $group_id > 0 ? zerti_product_attribute_group_get($group_id) : null;

    wp_send_json_success([
        'groups' => $items,
        'active' => $active,
        'available_attributes' => zerti_product_attribute_groups_available_attributes(),
        'total' => count($items),
    ]);
}

function zerti_ajax_product_attribute_group_save(): void
{
    zerti_ajax_product_attribute_groups_guard();

    $post = zerti_unslash_post_array();
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in zerti_ajax_product_attribute_groups_guard().
    $payload = zerti_product_attribute_group_payload_from_array($post);
    $result = zerti_product_attribute_group_save($payload);

    if (empty($result['ok'])) {
        $code = isset($result['code']) ? (string) $result['code'] : 'save_failed';
        $msg = zerti_product_attribute_group_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,
        'groups' => zerti_product_attribute_groups_list(),
        'active' => $saved_id > 0 ? zerti_product_attribute_group_get($saved_id) : null,
        'available_attributes' => zerti_product_attribute_groups_available_attributes(),
    ]);
}

function zerti_ajax_product_attribute_group_delete(): void
{
    zerti_ajax_product_attribute_groups_guard();

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

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

    wp_send_json_success([
        'groups' => zerti_product_attribute_groups_list(),
        'active' => null,
        'available_attributes' => zerti_product_attribute_groups_available_attributes(),
    ]);
}

