<?php

namespace Oney\ThreeByFour\Controller\Place;

use Magento\Checkout\Model\Session;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\UrlInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;

/**
 * Place Payment Controller
 * 
 * Handles payment placement for Oney ThreeByFour module.
 * Processes payment response and redirects to appropriate URL.
 * 
 * @package Oney\ThreeByFour\Controller\Place
 * @version 1.0.0
 * @author Oney
 * @since 1.0.0
 */
class Payment extends Action
{
    /**
     * Checkout session instance
     * 
     * @var Session
     * @version 1.0.0
     */
    protected $_checkoutSession;
    
    /**
     * URL builder instance
     * 
     * @var UrlInterface
     * @version 1.0.0
     */
    protected $urlBuilder;
    
    /**
     * Order repository instance
     * 
     * @var OrderRepositoryInterface
     * @version 1.0.0
     */
    protected $orderRepository;

    /**
     * Constructor
     * 
     * @param Context $context Action context
     * @param Session $checkoutSession Checkout session
     * @param UrlInterface $url URL builder
     * @param OrderRepositoryInterface $orderRepository Order repository
     * @version 1.0.0
     */
    public function __construct(
        Context $context,
        Session $checkoutSession,
        UrlInterface $url,
        OrderRepositoryInterface $orderRepository
    ) {
        $this->urlBuilder = $url;
        $this->_checkoutSession = $checkoutSession;
        parent::__construct($context);
        $this->orderRepository = $orderRepository;
    }

    /**
     * Execute action
     * 
     * Processes payment response and redirects to appropriate URL.
     * Updates order status and handles payment flow.
     * 
     * @return void
     * @version 1.0.0
     */
    public function execute(): void
    {
        try {
            $returned_url = json_decode($this->_checkoutSession->getData('oney_response', true)[0], true);
            $order = $this->_checkoutSession->getLastRealOrder()->setStatus(Order::STATE_PENDING_PAYMENT);
            $this->orderRepository->save($order);
            $this->_checkoutSession->setOneyResponse('oney_reponse', null);
            $this->_redirect($returned_url['returned_url']);
        } catch (\Exception $e) {
            $this->_redirect($this->urlBuilder->getUrl('checkout/onepage/failure'));
        }
    }
}
