<?php
namespace PortalPeople\DisabledPostcodes\Controller\Adminhtml\Postcode;

use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use PortalPeople\DisabledPostcodes\Api\DisabledPostcodeManagementInterface;

class Save extends AbstractPostcode
{
    private DisabledPostcodeManagementInterface $management;

    public function __construct(Context $context, DisabledPostcodeManagementInterface $management)
    {
        parent::__construct($context);
        $this->management = $management;
    }

    public function execute()
    {
        $data = (array)$this->getRequest()->getPostValue();
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);

        if (!$data) {
            return $resultRedirect->setPath('disabledpostcodes/postcode/index');
        }

        try {
            $id = isset($data['entity_id']) ? (int)$data['entity_id'] : 0;
            $postcode = (string)($data['postcode'] ?? '');
            $matchType = (string)($data['match_type'] ?? 'area');
            $storeId = isset($data['store_id']) ? (int)$data['store_id'] : 0;
            $description = isset($data['description']) ? (string)$data['description'] : null;
            $isActive = isset($data['is_active']) ? (bool)$data['is_active'] : true;
            $saved = [];

            if ($id > 0) {
                $saved = $this->management->update($id, $postcode, $matchType, $storeId, $description, $isActive);
                $this->messageManager->addSuccessMessage(__('The postcode rule has been updated.'));
            } else {
                $saved = $this->management->create($postcode, $matchType, $storeId, $description, $isActive);
                $this->messageManager->addSuccessMessage(__('The postcode rule has been created.'));
            }

            if ($this->getRequest()->getParam('back')) {
                $targetId = $id ?: (int)($saved['id'] ?? 0);
                return $resultRedirect->setPath('disabledpostcodes/postcode/edit', ['id' => $targetId]);
            }
            return $resultRedirect->setPath('disabledpostcodes/postcode/index');
        } catch (\Throwable $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
            if (!empty($data['entity_id'])) {
                return $resultRedirect->setPath('disabledpostcodes/postcode/edit', ['id' => (int)$data['entity_id']]);
            }
            return $resultRedirect->setPath('disabledpostcodes/postcode/new');
        }
    }
}
