<?php

/**
 * Copyright 2024-2025 Simply.IN Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the EUPL-1.2 or later.
 * You may not use this work except in compliance with the Licence.
 *
 * Copy of the Licence is available at:
 * https://joinup.ec.europa.eu/software/page/eupl
 * It is bundled with this package in the file LICENSE.txt
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Licence is distributed on an as is basis,
 * without warranties or conditions of any kind, either express or implied.
 * Check the Licence for the specific language governing permissions
 * and limitations under the License.
 *
 * @author   Simply.IN Sp. z o.o.
 * @copyright 2024-2025 Simply.IN Sp. z o.o.
 * @license   https://joinup.ec.europa.eu/software/page/eupl
 */

declare(strict_types=1);

namespace SimplyIn\Payment;

use Configuration;
use Module;
use Order;
use SimplyIn\Api\SimplyInApiClient;
use SimplyIn\Security\TokenService;
use SimplyInPayments;
use Tools;
use Validate;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class PaymentStatusChecker
{
    private const TERMINAL_STATUSES = ['PAID', 'REJECTED', 'FAILED', 'FAILD', 'CANCELLED', 'REFUNDED'];

    public function __construct(
        private readonly TokenService $tokenService,
        private readonly SimplyInApiClient $apiClient,
    ) {
    }

    /**
     * @return null|array<string, mixed>
     */
    public function check(Module $module): ?array
    {
        $ajaxToken = (string) Tools::getValue('ajax_token');
        $cartToken = (string) Tools::getValue('cart_token');
        $paymentCheckToken = (string) Tools::getValue('payment_check_token');
        $idCart = (int) Tools::getValue('id_cart');

        $tokensOk = $this->tokensValid($module, $ajaxToken, $cartToken, $paymentCheckToken, $idCart);
        $status = SimplyInPayments::getPaymentInfo($idCart);

        if (!$tokensOk) {
            return [
                'status' => 'error',
                'message' => 'Token error',
            ];
        }

        if (!$status) {
            return null;
        }

        if (in_array($status->status, self::TERMINAL_STATUSES, true)) {
            return [
                'status' => $status->status,
                'date' => $status->date_upd,
            ];
        }

        if (!empty($status->uuid)) {
            $reconciled = $this->reconcileWithBackend($module, $status->uuid, $idCart);
            if ($reconciled !== null) {
                return $reconciled;
            }
        }

        return [
            'status' => $status->status,
            'date' => $status->date_upd,
        ];
    }

    private function tokensValid(Module $module, string $ajaxToken, string $cartToken, string $paymentCheckToken, int $idCart): bool
    {

        return $ajaxToken === (string) $module->getAjaxToken()
            && $cartToken === (string) $module->getCartToken($idCart)
            && $paymentCheckToken === (string) $module->getPaymentCheckToken($ajaxToken, $cartToken);
    }

    /**
     * @return null|array<string, mixed>
     */
    private function reconcileWithBackend(Module $module, string $uuid, int $idCart): ?array
    {
        $response = $this->apiClient->apiCall(
            false,
            'GET',
            'payments/getPaymentStatus?paymentId=' . urlencode($uuid),
        );

        $apiStatus = is_array($response) ? ($response['status'] ?? null) : null;
        if (!$apiStatus || !in_array($apiStatus, ['PAID', 'REJECTED'], true)) {
            return null;
        }

        $order = Order::getByCartId($idCart);

        if ($apiStatus === 'PAID') {
            SimplyInPayments::markAsPaid($idCart);
            if (Validate::isLoadedObject($order)) {
                $module->updateOrderState(
                    $order,
                    Configuration::get('PS_OS_PAYMENT'),
                    'markAsPaid',
                );
            }
        } else {
            SimplyInPayments::markAsRejected($idCart);
            if (Validate::isLoadedObject($order)) {
                $module->updateOrderState(
                    $order,
                    (int) Configuration::get('SIMPLYIN_PAYMENT_STATUS_CANCELED'),
                    'markAsRejected',
                );
            }
        }

        return [
            'status' => $apiStatus,
            'date' => date('Y-m-d H:i:s'),
        ];
    }
}
