<?php
/**
 * 2007-2023 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 *  @author    PrestaShop SA <contact@prestashop.com>
 *  @copyright 2007-2023 PrestaShop SA
 *  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 *  International Registered Trademark & Property of PrestaShop SA
 */

namespace PrestaShop\Module\AgileMultisellerPro\Adapter;

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

class SellerOrderInvoice extends \OrderInvoice
{
    private $seller;
    private $sellerProducts;

    public function getshippingTaxRate()
    {
        $shippingTaxRate = 1;

        if ($this->total_shipping_tax_incl != 0) {
            $shippingTaxRate = $this->total_shipping_tax_excl / $this->total_shipping_tax_incl;
        }

        return $shippingTaxRate;
    }

    public function setSeller($seller)
    {
        $this->seller = $seller;

        return $this;
    }

    public function getSellerProducts($refresh = false)
    {
        if ($refresh == false && !is_null($this->sellerProducts)) {
            return $this->sellerProducts;
        }

        $products = $this->getProducts();

        foreach ($products as $k => $product) {
            // check that the product assigned to seller
            $sellerProduct = \Db::getInstance()->getRow('
                    SELECT * FROM ' . _DB_PREFIX_ . 'sellerinfo_product
                    WHERE id_product = ' . (int) $product['id_product'] . '
                        AND id_sellerinfo = ' . (int) $this->seller->getIdSellerinfo() . '
                ');

            if (!$sellerProduct) {
                // delete product from list if not assigned to seller
                unset($products[$k]);
            }
        }

        $this->sellerProducts = $products;

        return $this->sellerProducts;
    }

    public function getTotalProducts($useTax = true)
    {
        $products = $this->getSellerProducts();
        $amount = 0.0;
        foreach ($products as $product) {
            $amount += ($useTax ? $product['total_price_tax_incl'] : $product['total_price_tax_excl']);
        }

        return $amount;
    }

    public function getTotalShipping($useTax = true)
    {
        $order = new \Order($this->id_order);

        $shippingCostTaxIncl = (float) \Db::getInstance()->getValue('
                SELECT SUM(shipping_cost) AS `total_shipping_cost` FROM ' . _DB_PREFIX_ . 'sellerinfo_cart_carrier
                WHERE id_sellerinfo = ' . (int) $this->seller->getIdSellerinfo() . '
                    AND id_cart = ' . (int) $order->id_cart . '
            ');

        $orderCurrency = new \Currency($order->id_currency);
        $shippingCostTaxIncl = \Tools::convertPriceFull(
            $shippingCostTaxIncl,
            \Currency::getDefaultCurrency(),
            $orderCurrency
        );

        if ($useTax) {
            return $shippingCostTaxIncl;
        }

        return $this->getshippingTaxRate() * $shippingCostTaxIncl;
    }

    public function getOrderPaymentCollection()
    {
        $payments = parent::getOrderPaymentCollection();
        foreach ($payments as $payment) {
            $payment->amount = $this->getTotalShipping() + $this->getTotalProducts();

            return [$payment];
        }

        return $payments;
    }

    /**
     * Get the formatted number of invoice.
     *
     * @since 1.5.0.2
     *
     * @param int $id_lang for invoice_prefix
     *
     * @return string
     */
    public function getInvoiceNumberFormatted($id_lang, $id_shop = null)
    {
        $invoice_formatted_number = \Hook::exec('actionInvoiceNumberFormatted', [
            get_class($this) => $this,
            'id_lang' => (int) $id_lang,
            'id_shop' => (int) $id_shop,
            'number' => (int) $this->number,
        ]);

        if (!empty($invoice_formatted_number)) {
            return $invoice_formatted_number;
        }

        $format = '%1$s%2$06d';

        if (\Configuration::get('PS_INVOICE_USE_YEAR')) {
            $format = \Configuration::get('PS_INVOICE_YEAR_POS') ? '%1$s%3$s/%2$06d' : '%1$s%2$06d/%3$s';
        }

        return sprintf($format, \Configuration::get('PS_INVOICE_PREFIX', (int) $id_lang, null, (int) $id_shop) . 'S' . $this->seller->getIdSellerinfo() . 'N', $this->number, date('Y', strtotime($this->date_add)));
    }
}
