<?php

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

use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\DataProvider\ExportLogicDataProvider;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Factory\DataProviderFactory;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Form\ExportLogicForm;
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\Action\View\ExportMapperViewAction;
class ExportLogicFormProcessAction implements Conditional, Initable
{
    private Request $request;
    private ExportLogicForm $form;
    private PluginHelper $plugin_helper;
    private DataProviderFactory $data_provider_factory;
    public function __construct(Request $request, DataProviderFactory $data_provider_factory, ExportLogicForm $form, PluginHelper $helper)
    {
        $this->request = $request;
        $this->form = $form;
        $this->plugin_helper = $helper;
        $this->data_provider_factory = $data_provider_factory;
    }
    public function isActive(): bool
    {
        $settings = $this->request->get_param('post.' . $this->form->get_form_id());
        return $settings->isArray() && !$settings->isEmpty();
    }
    public function init()
    {
        $this->save_form_data();
    }
    private function save_form_data()
    {
        $args = [];
        $uid = $this->request->get_param('get.uid')->getAsString();
        $this->form->handle_request($this->request->get_param('post.' . $this->form->get_form_id())->get());
        if ($this->form->is_valid() && current_user_can('manage_options')) {
            $data_provider = $this->data_provider_factory->create_by_class_name(ExportLogicDataProvider::class, ['postfix' => $uid]);
            $data_provider->update($this->form);
            $mode = $this->request->get_param('get.mode')->getAsString();
            if (!empty($mode)) {
                $args = ['uid' => $uid, 'mode' => $mode];
            } else {
                $args = ['uid' => $uid];
            }
        }
        $url = $this->plugin_helper->generate_url_by_view(ExportMapperViewAction::class, $args);
        $this->redirect($url);
    }
    private function redirect(string $url)
    {
        wp_safe_redirect($url);
        exit;
    }
}
