<?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;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Scheduler\ExportSchedulerService;
class ExportManagerActivateProcessAction implements Conditional, Initable
{
    private Request $request;
    private ExportDAO $import_dao;
    private PluginHelper $plugin_helper;
    private ExportSchedulerService $scheduler;
    public function __construct(Request $request, ExportDAO $import_dao, PluginHelper $plugin_helper, ExportSchedulerService $scheduler)
    {
        $this->request = $request;
        $this->import_dao = $import_dao;
        $this->plugin_helper = $plugin_helper;
        $this->scheduler = $scheduler;
    }
    public function isActive(): bool
    {
        return $this->request->get_param('get.activate')->isNumeric() && $this->plugin_helper->is_plugin_page($this->request->get_param('get.page')->getAsString());
    }
    public function init()
    {
        $this->validate_form_data();
        $this->activate_import();
    }
    private function activate_import()
    {
        $id = (int) $this->request->get_param('get.activate')->get();
        $import = $this->import_dao->find_by_id($id);
        $import->set_next_export($this->scheduler->estimate_time($import->get_uid()));
        $import->set_last_position(0);
        $import->set_skipped(0);
        $import->set_created(0);
        $import->set_products_count(0);
        $import->set_status(Export::STATUS_WAITING);
        $this->import_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');
        }
    }
}
