<?php
/**
 * Copyright � Simplyin. All rights reserved.
 */
declare(strict_types=1);

/**
 * Copyright © Simplyin. All rights reserved.
 */
namespace Simplyin\Payment\Controller\Api;

use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Simplyin\Payment\Helper\ApiClient;
use Psr\Log\LoggerInterface;

/**
 * Update shipping method controller
 *
 * Syncs selected shipping method to SimplyIN
 */
class UpdateShippingMethod implements HttpPostActionInterface, CsrfAwareActionInterface
{
    use CsrfAwareApiTrait;

    /**
     * @var JsonFactory
     */
    private $resultJsonFactory;

    /**
     * @var ApiClient
     */
    private $apiClient;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var RequestInterface
     */
    private $request;

    /**
     * Constructor
     *
     * @param JsonFactory $resultJsonFactory
     * @param ApiClient $apiClient
     * @param LoggerInterface $logger
     * @param RequestInterface $request
     */
    public function __construct(
        JsonFactory $resultJsonFactory,
        ApiClient $apiClient,
        LoggerInterface $logger,
        RequestInterface $request
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->apiClient = $apiClient;
        $this->logger = $logger;
        $this->request = $request;
    }

    /**
     * Execute update shipping method action
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultJsonFactory->create();
        
        try {
            $data = json_decode($this->request->getContent(), true);
            $authToken = $data['authToken'] ?? '';
            $shippingMethod = $data['shippingMethod'] ?? [];

            if (empty($authToken)) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Authentication required')
                ]);
            }

            if (empty($shippingMethod)) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Shipping method data is required')
                ]);
            }

            $validationErrors = $this->validateShippingMethod($shippingMethod);
            if (!empty($validationErrors)) {
                return $result->setData([
                    'success' => false,
                    'errors' => $validationErrors,
                    'message' => __('Invalid shipping method data')
                ]);
            }

            $userDataResponse = $this->apiClient->getUserData($authToken);
            if (!$userDataResponse['success']) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Failed to get user data')
                ]);
            }

            $userData = $userDataResponse['data']['data'] ?? $userDataResponse['data'];

            $userData['selectedShippingMethod'] = [
                'carrier_code' => $shippingMethod['carrier_code'] ?? '',
                'method_code' => $shippingMethod['method_code'] ?? '',
                'carrier_title' => $shippingMethod['carrier_title'] ?? '',
                'method_title' => $shippingMethod['method_title'] ?? '',
                'amount' => $shippingMethod['amount'] ?? 0,
                'base_amount' => $shippingMethod['base_amount'] ?? 0,
                'updated_at' => date('Y-m-d H:i:s')
            ];

            $this->logger->info('Syncing shipping method to SimplyIN', [
                'carrier' => $shippingMethod['carrier_code'] ?? '',
                'method' => $shippingMethod['method_code'] ?? ''
            ]);

            $updateResponse = $this->apiClient->updateUserData(['userData' => $userData], $authToken);

            if ($updateResponse['success']) {
                return $result->setData([
                    'success' => true,
                    'message' => __('Shipping method updated successfully'),
                    'shippingMethod' => $userData['selectedShippingMethod']
                ]);
            } else {
                return $result->setData([
                    'success' => false,
                    'message' => $updateResponse['error'] ?? __('Failed to update shipping method')
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->error('Error updating shipping method: ' . $e->getMessage());
            return $result->setData([
                'success' => false,
                'message' => __('An unexpected error occurred. Please try again.')
            ]);
        }
    }

    /**
     * Validate shipping method data
     *
     * @param array $shippingMethod
     * @return array
     */
    private function validateShippingMethod($shippingMethod)
    {
        $errors = [];

        if (empty($shippingMethod['carrier_code'])) {
            $errors['carrier_code'] = __('Carrier code is required');
        }

        if (empty($shippingMethod['method_code'])) {
            $errors['method_code'] = __('Method code is required');
        }

        return $errors;
    }
}
