<?php

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

use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Form\Fields\ExportManagerFormFields;
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\ExportManagerForm;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\DAO\ExportDAO;
class ExportManagerFormProcessAction implements Conditional, Initable
{
    private Request $request;
    private ExportManagerForm $form;
    private ExportDAO $import_dao;
    public function __construct(Request $request, ExportManagerForm $form, ExportDAO $import_dao)
    {
        $this->request = $request;
        $this->form = $form;
        $this->import_dao = $import_dao;
    }
    public function isActive(): bool
    {
        $settings = $this->request->get_param('post.' . ExportManagerForm::ID);
        return $settings->isArray() && !$settings->isEmpty();
    }
    public function init()
    {
        $this->process_form_data();
    }
    private function process_form_data()
    {
        $form_data = $this->request->get_param('post.' . ExportManagerForm::ID)->get();
        $remove = \false;
        $this->form->handle_request($form_data);
        if ($this->form->is_valid() && current_user_can('manage_options')) {
            if ($this->request->get_param('post.' . ExportManagerFormFields::SUBMIT_MANAGE_APPLY)->isSet()) {
                $remove = isset($form_data[ExportManagerFormFields::SELECT_MANAGE]) && ExportManagerFormFields::SELECT_MANAGE_OPTION_REMOVE === $form_data[ExportManagerFormFields::SELECT_MANAGE];
            } elseif ($this->request->get_param('post.' . ExportManagerFormFields::SUBMIT_MANAGE_APPLY_BOTTOM)->isSet()) {
                $remove = isset($form_data[ExportManagerFormFields::SELECT_MANAGE_BOTTOM]) && ExportManagerFormFields::SELECT_MANAGE_OPTION_REMOVE === $form_data[ExportManagerFormFields::SELECT_MANAGE_BOTTOM];
            }
            if (\true === $remove) {
                if (isset($form_data['id']) && !empty($form_data['id'])) {
                    foreach ($form_data['id'] as $id) {
                        try {
                            $this->import_dao->remove_by_id($id);
                        } catch (\Exception $e) {
                        }
                        //phpcs:ignore
                    }
                }
            }
        }
    }
}
