<?php

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

use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Factory\DataProviderFactory;
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\Form\ExportFileTypeForm;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Action\View\ExportLogicViewAction;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\DataProvider\ExportFileTypeDataProvider;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Form\Fields\ExportFileTypeFormFields;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Helper\PluginHelper;
class ExportTypeFormProcessAction implements Conditional, Initable
{
    private Request $request;
    private ExportFileTypeForm $form;
    private PluginHelper $plugin_helper;
    private DataProviderFactory $data_provider_factory;
    public function __construct(Request $request, ExportFileTypeForm $form, DataProviderFactory $data_provider_factory, 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.' . ExportFileTypeForm::get_id());
        return $settings->isArray() && !$settings->isEmpty();
    }
    public function init()
    {
        $this->save_form_data();
    }
    private function save_form_data()
    {
        $args = [];
        $view = ExportLogicViewAction::class;
        $file_form_id = ExportFileTypeForm::get_id();
        $uid = $this->request->get_param('post.' . $file_form_id . '.' . ExportFileTypeFormFields::UID)->getAsString();
        $this->form->handle_request($this->request->get_param('post.' . $file_form_id)->get());
        if ($this->form->is_valid() && current_user_can('manage_options')) {
            $data_provider = $this->data_provider_factory->create_by_class_name(ExportFileTypeDataProvider::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];
            }
        }
        $this->redirect($this->plugin_helper->generate_url_by_view($view, $args));
    }
    private function redirect(string $url)
    {
        wp_safe_redirect($url);
        exit;
    }
}
