<?php

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

use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Helper\PluginHelper;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Infrastructure\Service\Listener\Items\Conditional\Conditional;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Infrastructure\Service\Listener\Items\Initable\Initable;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Infrastructure\Request\Request;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\DAO\ExportDAO;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Action\View\ExportManagerViewAction;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Entity\Export;
class ExportManagerStopProcessAction implements Conditional, Initable
{
    private Request $request;
    private ExportDAO $export_dao;
    private PluginHelper $plugin_helper;
    public function __construct(Request $request, ExportDAO $import_dao, PluginHelper $plugin_helper)
    {
        $this->request = $request;
        $this->export_dao = $import_dao;
        $this->plugin_helper = $plugin_helper;
    }
    public function isActive(): bool
    {
        return $this->request->get_param('get.stop')->isNumeric() && $this->plugin_helper->is_plugin_page($this->request->get_param('get.page')->getAsString());
    }
    public function init()
    {
        $this->validate_form_data();
        $this->stop_import();
    }
    private function stop_import()
    {
        $id = (int) $this->request->get_param('get.stop')->get();
        $import = $this->export_dao->find_by_id($id);
        $import->set_status(Export::STATUS_STOPPED);
        $this->export_dao->update($import);
        $url = $this->plugin_helper->generate_url_by_view(ExportManagerViewAction::class);
        wp_safe_redirect($url);
        exit;
    }
    private function validate_form_data()
    {
        if (!wp_verify_nonce($this->request->get_param('get.nonce')->getAsString(), ExportManagerViewAction::MANAGER_NONCE)) {
            wp_die('Error, security code is not valid');
        }
        if (!current_user_can('manage_options')) {
            wp_die('Error, you are not allowed to do this action');
        }
    }
}
