<?php

namespace DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Action\Ajax;

use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Infrastructure\Service\Listener\Items\Conditional\Conditional;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Infrastructure\Service\Listener\Items\Hookable\Hookable;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Infrastructure\Request\Request;
use Exception;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Validator\AjaxActionValidatorService;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Factory\PriceCompareFactory;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\PriceCompare\PriceCompareCategoryConfig;
class FindCategoryAjaxAction implements Conditional, Hookable
{
    const AJAX_ACTION = 'dropshipping_find_category_id';
    const AJAX_NONCE = 'nonce_dropshipping_find_category_id';
    private Request $request;
    private AjaxActionValidatorService $validator_service;
    private PriceCompareFactory $price_compare_factory;
    public function __construct(Request $request, AjaxActionValidatorService $validator_service, PriceCompareFactory $price_compare_factory)
    {
        $this->request = $request;
        $this->validator_service = $validator_service;
        $this->price_compare_factory = $price_compare_factory;
    }
    public function isActive(): bool
    {
        return wp_doing_ajax();
    }
    public function hooks()
    {
        add_action('wp_ajax_' . self::AJAX_ACTION, [$this, 'ajax_process']);
    }
    public function ajax_process()
    {
        try {
            $result = [];
            $this->validate_form_data();
            $post_data = $this->prepare_form_data();
            $item = isset($post_data['item']) ? sanitize_text_field($post_data['item']) : '';
            $term = isset($post_data['term']) ? sanitize_text_field($post_data['term']) : '';
            $config = $this->price_compare_factory->get_config_by_id($item);
            if ($config instanceof PriceCompareCategoryConfig) {
                $result = $config->get_category()->find_category_by_name($term);
            }
            wp_send_json($result);
        } catch (Exception $e) {
            wp_send_json(['success' => \false, 'message' => $e->getMessage()]);
        }
    }
    private function validate_form_data()
    {
        $this->validator_service->is_valid($this->request->get_param('get.security')->getAsString(), self::AJAX_NONCE);
    }
    private function prepare_form_data(): array
    {
        return ['item' => $this->request->get_param('get.item')->getAsString(), 'term' => $this->request->get_param('get.term')->getAsString()];
    }
}
