<?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
 */
declare(strict_types=1);

namespace PrestaShop\Module\AgileMultisellerPro\Repository;

use Doctrine\ORM\EntityRepository;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoProduct;

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

class SellerInfoOrderRepository extends EntityRepository
{
    public function getTotalAmountSold(?int $idSellerinfo): array
    {
        $totals = [];

        $conn = $this->getEntityManager()->getConnection();

        $sql = 'SELECT SUM( (product_quantity  - product_quantity_refunded  ) *
				(product_price - CASE WHEN reduction_percent>0 THEN product_price * reduction_percent/100
				ELSE reduction_amount END - product_price * group_reduction/100)
				- CASE WHEN IFNULL(discount_quantity_applied,0) = 1 THEN
				IFNULL(product_quantity_discount,0) ELSE 0 END
			) AS total, o.id_currency
                FROM `' . _DB_PREFIX_ . 'order_detail` od
                    LEFT JOIN `' . _DB_PREFIX_ . 'sellerinfo_order` sio ON (od.id_order=sio.id_order)
                    LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON (od.id_order=o.id_order)
                WHERE sio.id_sellerinfo = :idSellerinfo
					AND current_state NOT IN (6,7)
				GROUP BY o.id_currency
		';

        $query = $conn->executeQuery($sql, ['idSellerinfo' => (int) $idSellerinfo]);

        foreach ($query as $total) {
            $totals[] = [
                'currency' => new \Currency($total['id_currency']),
                'amount' => \Tools::ps_round($total['total'], 2),
            ];
        }
        if (!$totals) {
            $totals[] = [
                'currency' => new \Currency((int) \Configuration::get('PS_CURRENCY_DEFAULT')),
                'amount' => 0,
            ];
        }

        return $totals;
    }

    public function getSellerSalesFromOrder($id_order, $include_shppingcost = true, $after_discounts = false, $include_tax = true)
    {
        $order = new \Order($id_order);

        if (!\Validate::isLoadedObject($order)) {
            return;
        }

        $seller_sales_amount = [];

        $order_total_product = 0;

        foreach ($order->getProducts() as $product) {
            $idSellerinfo = 0;

            $sellerinfoProduct = $this->getEntityManager()->getRepository(SellerinfoProduct::class)
                ->findOneBy(['idProduct' => (int) $product['product_id']]);

            if ($sellerinfoProduct) {
                $idSellerinfo = (int) $sellerinfoProduct->getSellerinfo()->getIdSellerinfo();
            }

            if (!isset($seller_sales_amount[$idSellerinfo])) {
                $seller_sales_amount[$idSellerinfo] = 0;
            }

            if ($include_tax) {
                $lineamount = $product['unit_price_tax_incl'] * $product['product_quantity'];
            } else {
                $lineamount = $product['unit_price_tax_excl'] * $product['product_quantity'];
            }

            $seller_sales_amount[$idSellerinfo] += $lineamount;

            $order_total_product += $lineamount;
        }

        if ($order_total_product == 0) {
            return $seller_sales_amount;
        }

        $total_discounts = 0 - $order->total_discounts;

        if ($after_discounts && $total_discounts < 0) {
            foreach ($seller_sales_amount as $key => $amount) {
                $seller_discount = $amount * $total_discounts / $order_total_product;
                $seller_sales_amount[$key] = \Tools::ps_round($amount + $seller_discount, 2);
            }
        }

        $total_shipping = $order->total_shipping;

        if ($include_shppingcost && $total_shipping > 0) {
            foreach ($seller_sales_amount as $key => $amount) {
                $seller_shipping = ($include_tax ? $order->total_shipping_tax_incl : $order->total_shipping_tax_excl);
                $seller_sales_amount[$key] = \Tools::ps_round($amount + $seller_shipping, 2);
            }
        }

        return $seller_sales_amount;
    }

    public function getOrders($idSellerinfo, $showHiddenStatus = false, ?\Context $context = null, $nb_only = false, $p = 1, $n = 10, $orderby = '', $orderway = '', $extraConditions = '', $isDisplayPice = true)
    {
        if (!(int) $idSellerinfo) {
            return;
        }

        if (!$context) {
            $context = \Context::getContext();
        }

        $conn = $this->getEntityManager()->getConnection();

        $use_tax = (int) \Configuration::get('PS_TAX') == 1;

        $defaultCurrency = \Currency::getDefaultCurrency();

        $select = '
            SELECT o.id_order
                    , CONCAT(LEFT(c.`firstname`, 1), \'. \', c.`lastname`) AS `customer`
                    , IF((SELECT COUNT(so.id_order) FROM `' . _DB_PREFIX_ .
                'orders` so WHERE so.id_customer = o.id_customer) > 1, 0, 1) as new
                    , (SELECT SUM(od.`product_quantity`) FROM `' . _DB_PREFIX_ .
                'order_detail` od WHERE od.`id_order` = o.`id_order`) nb_products
                    , CONCAT(LEFT(c.`firstname`, 1), \'. \', c.`lastname`) AS `customer`
                    ,o.date_add
                    ,o.payment,
                    (
                        (SELECT SUM(' . ($use_tax ? 'od.`total_price_tax_incl`' : 'od.`total_price_tax_excl`') . ') FROM `' . _DB_PREFIX_ . 'order_detail` od
                        LEFT JOIN ' . _DB_PREFIX_ . 'sellerinfo_order_detail AS sp ON (sp.id_order_detail = od.id_order_detail)
                        WHERE IFNULL(sp.id_sellerinfo, 0) = ' . (int) $idSellerinfo . ' AND od.`id_order` = o.`id_order`) +
                        IFNULL(
                            (SELECT SUM(scc.shipping_cost * IF(cy.id_currency = ' . (int) $defaultCurrency->id . ', cy.conversion_rate, (cy.conversion_rate / ' . (float) ($defaultCurrency->conversion_rate == 0 ? 1 : $defaultCurrency->conversion_rate) . '))) FROM ' . _DB_PREFIX_ . 'sellerinfo_cart_carrier AS scc WHERE scc.id_sellerinfo = ' . (int) $idSellerinfo . ' AND scc.id_cart = o.id_cart)
                        , 0)
                    ) AS `total_paid`
                    ,sio.id_sellerinfo
                    ,o.id_customer
                    ,o.id_currency as id_currency
                    ,o.reference
                    ,cy.name AS currency
                    ,CONCAT(c.`firstname`, \' \', c.`lastname`) AS `customer`
                    ,osl.`name` AS `osname`
                    ,os.`color`
            ';

        $from = '
            FROM `' . _DB_PREFIX_ . 'orders` o
                LEFT JOIN `' . _DB_PREFIX_ . 'customer` c ON (o.id_customer=c.id_customer)
                LEFT JOIN `' . _DB_PREFIX_ . 'sellerinfo_order` sio ON (o.id_order=sio.id_order)
                LEFT JOIN `' . _DB_PREFIX_ . 'currency` cy ON (o.`id_currency`=cy.id_currency)
                LEFT JOIN `' . _DB_PREFIX_ . 'sellerinfo` s ON (sio.`id_sellerinfo`=s.`id_sellerinfo`)
                LEFT JOIN `' . _DB_PREFIX_ .
                    'sellerinfo_lang` sl ON (sl.`id_sellerinfo`=s.`id_sellerinfo` AND sl.id_lang=' .
                    (int) $context->language->id . ')
                LEFT JOIN `' . _DB_PREFIX_ .
                'order_history` oh ON (oh.`id_order` = o.`id_order` and o.current_state = oh.id_order_state)
                LEFT JOIN `' . _DB_PREFIX_ . 'order_state` os ON (os.`id_order_state` = oh.`id_order_state`)
                LEFT JOIN `' . _DB_PREFIX_ .
                'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = ' .
                (int) $context->language->id . ')
                LEFT JOIN `' . _DB_PREFIX_ . 'order_invoice` oi ON o.id_order = oi.id_order
            ';

        $where = '
    		WHERE sio.`id_sellerinfo` = ' . (int) $idSellerinfo . '
    	';

        if (!empty($extraConditions)) {
            $where .= $extraConditions;
        }

        if ($nb_only) {
            return $conn->fetchColumn('SELECT COUNT(DISTINCT o.id_order)' . $from . $where);
        }

        if ($p < 1) {
            $p = 1;
        }

        if ($n < 1) {
            $n = 10;
        }

        if (empty($orderby)) {
            $orderby = 'o.date_add';
        }

        if (empty($orderway)) {
            $orderway = 'DESC';
        }

        $sort = ' ORDER BY ' . $orderby . ' ' . $orderway . ' ';

        $limit = ' LIMIT ' . (((int) $p - 1) * (int) $n) . ',' . (int) $n . ' ';

        $sql = $select . $from . $where . $sort . $limit;

        $res = [];

        foreach ($conn->executeQuery($sql) as $key => $val) {
            $res[$key] = $val;

            $sql = '
				SELECT os.`id_order_state`, osl.`name` AS order_state, os.`invoice`
				FROM `' . _DB_PREFIX_ . 'order_history` oh
				LEFT JOIN `' . _DB_PREFIX_ . 'order_state` os ON (os.`id_order_state` = oh.`id_order_state`)
				INNER JOIN `' . _DB_PREFIX_ .
                'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = ' .
                (int) $context->language->id . ')
			WHERE oh.`id_order` = ' . (int) $val['id_order'] .
                (!$showHiddenStatus ? ' AND os.`hidden` != 1' : '') . '
				ORDER BY oh.`date_add` DESC, oh.`id_order_history` DESC
			LIMIT 1';

            $res2 = $conn->fetchAssociative($sql);

            if ($res2) {
                if (true === $isDisplayPice) {
                    $res[$key]['total_paid'] = \Tools::displayPrice($res[$key]['total_paid'], (int) $res[$key]['id_currency']);
                }

                $res[$key] = array_merge($res[$key], $res2);
            }
        }

        return $res;
    }
}
