<?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\Service;

use Configuration;
use PrestaShopLogger;
use RuntimeException;
use SimplyIn\Api\EncryptionService;

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

class EncryptedTrackingSender
{
    public function __construct(
        private readonly EncryptionService $encryption,
        private readonly string $backendUrl,
    ) {
    }

    /**
     * @param array<string, mixed> $trackingNumber
     */
    public function send(
        string $orderEmail,
        string $orderReference,
        string $newOrderState,
        array $trackingNumber,
    ): false|string {
        $apiKey = (string) Configuration::get('SIMPLYIN_SECRET_KEY');
        $bodyData = [
            'email' => $orderEmail,
            'shopOrderNumber' => $orderReference,
            'newOrderStatus' => $newOrderState,
            'apiKey' => $apiKey,
            'trackings' => [$trackingNumber],
        ];

        $plaintext = json_encode($bodyData, JSON_UNESCAPED_SLASHES);
        if ($plaintext === false) {
            return false;
        }

        try {
            $encrypted = $this->encryption->encrypt($plaintext, $this->encryption->getSecretKey($orderEmail));
        } catch (RuntimeException $e) {
            PrestaShopLogger::addLog('SimplyIn: tracking encryption failed for order ' . $orderReference . ' (' . $e->getMessage() . ')', 3);

            return false;
        }

        $orderData = [
            'encryptedOrderStatusChangeContent' => $encrypted,
            'hashedEmail' => $this->encryption->getEmailHash($orderEmail),
        ];
        $url = rtrim($this->backendUrl, '/') . '/encryption/saveEncryptedOrderStatusChange';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($orderData));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded',
            'Origin: ' . (defined('__PS_BASE_URI__') ? __PS_BASE_URI__ : ''),
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        $response = curl_exec($ch);
        $curlError = $response === false ? curl_error($ch) : '';
        curl_close($ch);

        if ($response === false) {
            PrestaShopLogger::addLog('SimplyIn: tracking push to Simply.IN failed for order ' . $orderReference . ' (' . $curlError . ')', 3);

            return false;
        }

        return $response;
    }
}
