<?php

namespace PortalPeople\OrderWebhook\Controller\Adminhtml\Order;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Sales\Api\OrderRepositoryInterface;
use PortalPeople\OrderWebhook\Model\WebhookSender;

class ResendWebhook extends Action
{
    const ADMIN_RESOURCE = 'PortalPeople_OrderWebhook::config';

    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;

    /**
     * @var WebhookSender
     */
    private $webhookSender;

    /**
     * @param Context $context
     * @param OrderRepositoryInterface $orderRepository
     * @param WebhookSender $webhookSender
     */
    public function __construct(
        Context $context,
        OrderRepositoryInterface $orderRepository,
        WebhookSender $webhookSender
    ) {
        parent::__construct($context);
        $this->orderRepository = $orderRepository;
        $this->webhookSender = $webhookSender;
    }

    /**
     * Resend order via webhook
     *
     * @return \Magento\Framework\Controller\Result\Redirect
     */
    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        $orderId = (int)$this->getRequest()->getParam('order_id');

        if (!$orderId) {
            $this->messageManager->addErrorMessage(__('Invalid order ID.'));
            return $resultRedirect->setPath('sales/order/index');
        }

        try {
            $order = $this->orderRepository->get($orderId);
            $success = $this->webhookSender->sendOrderData($order, 'manual_resend');

            if ($success) {
                $this->messageManager->addSuccessMessage(
                    __('Order #%1 has been sent to NGauge successfully.', $order->getIncrementId())
                );
            } else {
                $this->messageManager->addErrorMessage(
                    __('Failed to send order #%1 to NGauge. Check webhook configuration and logs.', $order->getIncrementId())
                );
            }
        } catch (\Exception $e) {
            $this->messageManager->addErrorMessage(__('Error: %1', $e->getMessage()));
        }

        return $resultRedirect->setPath('sales/order/view', ['order_id' => $orderId]);
    }
}
