<?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\DAO\ExportDAO;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Entity\Export;
/**
 * Class StopExportAjaxAction, class that handles export to stop.
 */
class StopExportAjaxAction implements Conditional, Hookable
{
    const AJAX_ACTION = 'stop_export_products';
    const AJAX_NONCE = 'nonce_stop_export_products';
    /**
     * @var Request
     */
    private $request;
    /**
     * @var AjaxActionValidatorService
     */
    private $validator_service;
    /**
     * @var ExportDAO
     */
    private $export_dao;
    public function __construct(Request $request, AjaxActionValidatorService $validator_service, ExportDAO $export_dao)
    {
        $this->request = $request;
        $this->validator_service = $validator_service;
        $this->export_dao = $export_dao;
    }
    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 {
            $this->validate_form_data();
            $post_data = $this->prepare_form_data();
            $export = $this->export_dao->find_by_uid($post_data['uid']);
            $export->set_status(Export::STATUS_STOPPED);
            $this->export_dao->update($export);
            wp_send_json(['success' => \true, 'message' => __('Export stopped.', 'dropshipping-export-free')]);
        } 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('post.security')->getAsString(), self::AJAX_NONCE);
    }
    private function prepare_form_data(): array
    {
        return ['uid' => $this->request->get_param('post.uid')->getAsString()];
    }
}
