<?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;
class ExportManagerDeleteProcessAction implements Conditional, Initable
{
    private Request $request;
    private ExportDAO $import_dao;
    private PluginHelper $plugin_helper;
    public function __construct(Request $request, ExportDAO $import_dao, PluginHelper $plugin_helper)
    {
        $this->request = $request;
        $this->import_dao = $import_dao;
        $this->plugin_helper = $plugin_helper;
    }
    public function isActive(): bool
    {
        return $this->request->get_param('get.delete')->isNumeric() && $this->plugin_helper->is_plugin_page($this->request->get_param('get.page')->getAsString());
    }
    public function init()
    {
        $this->validate_form_data();
        $this->delete_import();
    }
    private function delete_import()
    {
        $id = (int) $this->request->get_param('get.delete')->get();
        $this->import_dao->remove_by_id($id);
        $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');
        }
    }
}
