<?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
 */

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

class SimplyInPayments extends ObjectModel
{
    use SimplyInInstallSqlTrait;

    public $id;

    public $cart_id;

    public $type;

    public $date_add;

    public $date_upd;

    public $status;

    public $uuid;

    public $payment_provider;

    public $card_provider;

    public $provider_logo;

    public $logo;

    public static $definition = [
        'table' => 'simplyin_payments',
        'primary' => 'id_simplyin_payments',
        'multilang' => false,
        'multilang_shop' => false,
        'fields' => [
            'cart_id' => [
                'type' => self::TYPE_INT,
                'index' => true,
            ],
            'type' => [
                'type' => self::TYPE_STRING,
                'size' => 36,
            ],
            'date_add' => [
                'type' => self::TYPE_DATE,
            ],
            'date_upd' => [
                'type' => self::TYPE_DATE,
            ],
            'status' => [
                'type' => self::TYPE_STRING,
                'size' => 50,
            ],
            'uuid' => [
                'type' => self::TYPE_STRING,
                'size' => 36,
            ],
            'payment_provider' => [
                'type' => self::TYPE_STRING,
                'size' => 36,
            ],
            'card_provider' => [
                'type' => self::TYPE_STRING,
                'size' => 36,
            ],
            'provider_logo' => [
                'type' => self::TYPE_STRING,
                'size' => 255,
            ],
            'logo' => [
                'type' => self::TYPE_STRING,
                'size' => 255,
            ],
        ],
    ];

    /**
     * Random RFC-4122 v4 payment id.
     *
     * Historically this was a deterministic md5 slice of order id + reference, which is
     * guessable — and the backend's unauthenticated `payments/getPaymentStatus` endpoint
     * returns the payment status and amount for a given paymentId, so a predictable id
     * leaks order data. Nothing relies on the determinism: the id is persisted on the
     * payment row at creation (addByCart) and every later read (status polling,
     * reconcile, webhooks) takes it from the database, never recomputes it.
     *
     * The $order parameter is kept for signature compatibility.
     *
     * @param object $order unused
     *
     * @return string
     */
    public static function getUUID($order)
    {
        $bytes = random_bytes(16);
        $bytes[6] = chr((ord($bytes[6]) & 0x0F) | 0x40);
        $bytes[8] = chr((ord($bytes[8]) & 0x3F) | 0x80);

        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
    }

    public static function addByCart($cart, $type, $status, $uuid, $payment_provider, $card_provider, $provider_logo, $image)
    {

        self::ensureSchema();
        $simplyin_payment = new self();
        $simplyin_payment->cart_id = (int) $cart->id;
        $simplyin_payment->type = pSQL($type);
        $simplyin_payment->status = pSQL($status);
        $simplyin_payment->uuid = pSQL($uuid);
        $simplyin_payment->date_add = date('Y-m-d H:i:s');
        $simplyin_payment->payment_provider = pSQL($payment_provider);
        $simplyin_payment->card_provider = pSQL($card_provider);
        $simplyin_payment->provider_logo = pSQL($provider_logo);
        $simplyin_payment->logo = pSQL($image);

        return $simplyin_payment->save();
    }

    public static function getPaymentInfo($id_cart)
    {
        // ORDER BY picks the newest of several attempts for one cart. No explicit LIMIT:
        // getValue()/getRow() append " LIMIT 1" themselves ("LIMIT 1 LIMIT 1" = SQL syntax error).
        $sql = '
            SELECT      id_simplyin_payments
            FROM        ' . _DB_PREFIX_ . 'simplyin_payments
            WHERE       cart_id = ' . (int) $id_cart . '
            ORDER BY    id_simplyin_payments DESC';
        $id_simplyin_payment = Db::getInstance()->getValue($sql);
        if ($id_simplyin_payment) {
            return new self((int) $id_simplyin_payment);
        }

        return false;
    }

    public static function markAsPaid($id_cart)
    {
        $object = self::getPaymentInfo($id_cart);
        if ($object && $object->id) {

            self::ensureSchema();
            $object->status = 'PAID';
            $object->save();
        }
    }

    public static function markAsRejected($id_cart)
    {
        $object = self::getPaymentInfo($id_cart);
        if ($object && $object->id) {
            self::ensureSchema();
            $object->status = 'REJECTED';
            $object->save();
        }
    }

    public static function markAsCancelled($id_cart)
    {
        $object = self::getPaymentInfo($id_cart);
        if ($object && $object->id) {
            self::ensureSchema();
            $object->status = 'CANCELLED';
            $object->save();
        }
    }

    public static function markAsRefunded($id_cart)
    {
        $object = self::getPaymentInfo($id_cart);
        if ($object && $object->id) {
            self::ensureSchema();
            $object->status = 'REFUNDED';
            $object->save();
        }
    }

    public static function ensureSchema()
    {
        $table = _DB_PREFIX_ . self::$definition['table'];
        $columns = Db::getInstance()->executeS('SHOW COLUMNS FROM `' . bqSQL($table) . '`');
        if (!is_array($columns)) {
            return false;
        }

        $existing = [];
        foreach ($columns as $column) {
            if (isset($column['Field'])) {
                $existing[(string) $column['Field']] = true;
            }
        }

        $return = true;
        foreach (self::$definition['fields'] as $key => $field) {
            if (isset($existing[$key])) {
                continue;
            }
            switch ($field['type']) {
                case self::TYPE_STRING:
                case self::TYPE_HTML:
                    $sqlType = isset($field['size']) ? 'VARCHAR(' . (int) $field['size'] . ')' : 'LONGTEXT';

                    break;
                case self::TYPE_INT:
                case self::TYPE_BOOL:
                    $sqlType = isset($field['size']) ? 'INT(' . (int) $field['size'] . ')' : 'INT(11)';

                    break;
                case self::TYPE_DATE:
                    $sqlType = 'DATETIME';

                    break;
                case self::TYPE_FLOAT:
                    $sqlType = 'FLOAT';

                    break;
                default:
                    continue 2;
            }
            $sql = 'ALTER TABLE `' . bqSQL($table) . '` ADD COLUMN `' . bqSQL($key) . '` ' . $sqlType . ' NULL';
            $return = $return && Db::getInstance()->execute($sql);
        }

        return $return;
    }

    public static function upgrade202()
    {
        $sql = '
            ALTER TABLE `' . _DB_PREFIX_ . self::$definition['table'] . '`
            ADD COLUMN `provaider_logo` VARCHAR(255) NULL,
            ADD COLUMN `logo` VARCHAR(255) NULL
        ';

        return Db::getInstance()->execute($sql);
    }
}
