<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace ArtabanMarketplace\Loop;

use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\PropelSearchLoopInterface;
use Thelia\Core\Template\Element\SearchLoopInterface;
use ArtabanMarketplace\Model\Map\AmpSellerOrderTableMap;
use ArtabanMarketplace\Model\AmpSellerOrderQuery;
use ArtabanMarketplace\Model\AmpSellerQuery;
use ArtabanMarketplace\Model\AmpSellerAdminQuery;
use ArtabanMarketplace\Model\AmpSellerOrderAddressQuery;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Join;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Order;
use Thelia\Model\OrderQuery;
use Thelia\Model\AdminQuery;
use Thelia\Model\Map\OrderTableMap;
use Propel\Runtime\Propel;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Type;
use Thelia\Type\TypeCollection;
use ArtabanMarketplace\Model\AmpSellerOrderDeliveryReferenceQuery;

/**
 * Description of AmpSellerOrderLoop
 *
 * @author LENGY Gilles
 */
class AmpSellerOrderLoop extends BaseLoop implements SearchLoopInterface, PropelSearchLoopInterface {

    protected $countable = true;
    protected $timestampable = true;
    protected $versionable = false;

    /**
     * @inheritDoc
     */
    protected function getArgDefinitions() {
        return new ArgumentCollection(
                Argument::createIntListTypeArgument('id'), Argument::createIntListTypeArgument('amp_seller_id'), Argument::createIntListTypeArgument('customer_id'), Argument::createIntListTypeArgument('order_id'), Argument::createAlphaNumStringTypeArgument('interval_creation_order'), new Argument(
                'customer', new TypeCollection(
                new Type\IntType(), new Type\EnumType(array('current', '*'))
                ), NULL
                )
        );
    }

    public function parseResults(LoopResult $loopResult) {
        /**  @var ArtabanMarketplace\Model\AmpSellerOrder $sellerOrder */
        foreach ($loopResult->getResultDataCollection() as $sellerOrder) {

            $sellerOrderQuery = new AmpSellerOrderQuery();
            $sellerOrderObject = $sellerOrderQuery->findOneById($sellerOrder->getId());

            if ($sellerOrderObject !== NULL) {

                // Seller Name
                $sellerQuery = new AmpSellerQuery();
                $seller = $sellerQuery->findOneById($sellerOrderObject->getAmpSellerId());

                $sellerAdminQuery = new AmpSellerAdminQuery();
                $sellerAdmin = $sellerAdminQuery->findOneByAmpSellerId($seller->getId());

                $adminQuery = new AdminQuery();
                $admin = $adminQuery->findOneById($sellerAdmin->getAdminId());

                $sellerName = $admin->getFirstname() . " " . $admin->getLastname();

                // Order            
                $orderQuery = new orderQuery();
                $order = $orderQuery->findOneById($sellerOrderObject->getOrderId());

                // Amount, Tax
                $amountTaxArray = $sellerOrderObject->getAmountTax($sellerOrderObject->getId(), $sellerOrderObject->getOrderId());
                $totalTax = $amountTaxArray["total_tax"];
                $totalTaxedAmount = $amountTaxArray["total_amount"] + $totalTax;
                $totalUntaxedAmount = $amountTaxArray["total_amount"];
                $totalTaxedAmountPostage = $totalTaxedAmount + $sellerOrderObject->getPostage();
                
                // Delivery Ref
                $sellerOrdereliveryRefQuery =  new AmpSellerOrderDeliveryReferenceQuery();
                $sellerOrdereliveryRef = $sellerOrdereliveryRefQuery->findOneByOrderSellerId($sellerOrderObject->getId());
                
            }

            $loopResultRow = new LoopResultRow($order);
            $loopResultRow
                    ->set('ID', $sellerOrderObject->getId())
                    ->set('REF', $sellerOrderObject->getSellerOrderRef())
                    ->set('CUSTOMER', $order->getCustomerId())
                    ->set('ORDER_PRODUCT_ID', $sellerOrderObject->getOrderProductId())
                    ->set('ORDER_ID', $sellerOrderObject->getOrderId())
                    ->set('DELIVERY_ADDRESS', $order->getDeliveryOrderAddressId())
                    ->set('INVOICE_ADDRESS', $order->getInvoiceOrderAddressId())
                    ->set('INVOICE_DATE', $order->getInvoiceDate())
                    ->set('CURRENCY', $order->getCurrencyId())
                    ->set('CURRENCY_RATE', $order->getCurrencyRate())
                    ->set('TRANSACTION_REF', $order->getTransactionRef())
                    ->set('INVOICE_REF', $sellerOrderObject->getSellerOrderRef())
                    ->set('VIRTUAL', $hasVirtualDownload)
                    ->set('POSTAGE', $sellerOrderObject->getPostage())
                    ->set('POSTAGE_TAX', $sellerOrderObject->getPostageTax())
                    ->set('POSTAGE_UNTAXED', $sellerOrderObject->getUntaxedPostage())
                    ->set('POSTAGE_TAX_RULE_TITLE', $order->getPostageTaxRuleTitle())
                    ->set('PAYMENT_MODULE', $order->getPaymentModuleId())
                    ->set('DELIVERY_MODULE', $order->getDeliveryModuleId())
                    ->set('STATUS', $order->getStatusId())
                    ->set('STATUS_CODE', $order->getOrderStatus()->getCode())
                    ->set('LANG', $order->getLangId())
                    ->set('DISCOUNT', $sellerOrderObject->getDiscount())
                    ->set('TOTAL_TAX', $totalTax)
                    ->set('TOTAL_UNTAXED_AMOUNT', $totalUntaxedAmount)
                    ->set('TOTAL_TAXED_AMOUNT', $totalTaxedAmount)
                    ->set('TOTAL_TAXED_AMOUNT_POSTAGE', $totalTaxedAmountPostage)
                    ->set('WEIGHT', $sellerOrderObject->getWeight($sellerOrderObject->getId(), $sellerOrderObject->getOrderId()))
                    ->set('HAS_PAID_STATUS', $order->isPaid())
                    ->set('IS_PAID', $order->isPaid(false))
                    ->set('IS_CANCELED', $order->isCancelled())
                    ->set('IS_NOT_PAID', $order->isNotPaid())
                    ->set('IS_SENT', $order->isSent())
                    ->set('IS_PROCESSING', $order->isProcessing())
            ;

            if ($sellerOrder !== NULL) {
                $loopResultRow
                        ->set('SELLER_ORDER_ID', $sellerOrder->getOrderId())
                        ->set('ORDER_ID', $sellerOrder->getOrderId())
                        ->set('AMP_SELLER_ID', $seller->getId())
                        ->set('AMP_SELLER_NAME', $sellerName);
            }
            if ($sellerOrdereliveryRef !== NULL) {
                $loopResultRow
                        ->set('DELIVERY_REF', $sellerOrdereliveryRef->getDeliveryReference());
            }

            $this->addOutputFields($loopResultRow, $order);

            $loopResult->addRow($loopResultRow);
        }

        return $loopResult;
    }

    /**
     * @inheritdoc
     */
    public function buildModelCriteria() {
        $query = AmpSellerOrderQuery::create();

        if (null != $id = $this->getId()) {
            $query->filterById($id);
        }

        if (null != $amp_seller_id = $this->getAmpSellerId()) {
            $query->filterByAmpSellerId($amp_seller_id);
        }

        if (null != $customer_id = $this->getCustomerId()) {
            $query->filterByCustomerId($customer_id);
        }

        if (null != $order_id = $this->getOrderId()) {
            $query->filterByOrderId($order_id);
        }

        if (null != $customer = $this->getCustomer()) {


            if ($customer === 'current') {
                $currentCustomer = $this->securityContext->getCustomerUser();
                if ($currentCustomer === null) {
                    return null;
                } else {
                    $query->filterByCustomerId($currentCustomer->getId(), Criteria::EQUAL);
                }
            } elseif ($customer !== '*') {
                $query->filterByCustomerId($customer, Criteria::EQUAL);
            }
        }

        if (null != $intervalCreationOrder = $this->getIntervalCreationOrder()) {
            if ($intervalCreationOrder === 'today') {
                $query->filterByCreatedAt(array(
                    'min' => 'today'
                ));
            }
            if ($intervalCreationOrder === 'yesterday') {
                $query->filterByCreatedAt(array(
                    'min' => 'yesterday',
                    'max' => 'today'
                ));
            }
            if ($intervalCreationOrder === 'this_month') {
                $beginingThisMonth = mktime(0, 0, 0, date("m"), 01, date("Y"));
                $query->filterByCreatedAt(array(
                    'min' => $beginingThisMonth
                ));
            }
            if ($intervalCreationOrder === 'previous_month') {
                $beginingPreviousMonth = mktime(0, 0, 0, date("m") - 1, 01, date("Y"));
                $endPreviousMonth = mktime(0, 0, 0, date("m"), 01, date("Y")) - (24 * 60 * 60);
                $query->filterByCreatedAt(array(
                    'min' => $beginingPreviousMonth,
                    'max' => $endPreviousMonth
                ));
            }
            if ($intervalCreationOrder === 'this_year') {
                $beginingThisYear = mktime(0, 0, 0, 01, 01, date("Y"));
                $query->filterByCreatedAt(array(
                    'min' => $beginingThisYear
                ));
            }
            if ($intervalCreationOrder === 'previous_year') {
                $beginingPreviousYear = mktime(0, 0, 0, 01, 01, date("Y") - 1);
                $endPreviousYear = mktime(0, 0, 0, 12, 31, date("Y") - 1);
                $query->filterByCreatedAt(array(
                    'min' => $beginingThisYear,
                    'max' => $endPreviousYear
                ));
            }
        }
        return $query;
    }

    public function getSearchIn() {
        return array(
//            'ref',
//            'invoice_ref',
//            'delivery_ref',
//            'transaction_ref',
//            'customer_ref',
//            'customer_firstname',
//            'customer_lastname',
//            'customer_email',
        );
    }

    /**
     * @param AmpSellerOrderQuery $search
     * @param $searchTerm
     * @param $searchIn
     * @param $searchCriteria
     */
    public function doSearch(&$search, $searchTerm, $searchIn, $searchCriteria) {
//        $search->_and();
//        foreach ($searchIn as $index => $searchInElement) {
//            if ($index > 0) {
//                $search->_or();
//            }
//            switch ($searchInElement) {
//                case 'ref':
//                    $search->filterByRef($searchTerm, $searchCriteria);
//                    break;
//                case 'invoice_ref':
//                    $search->filterByInvoiceRef($searchTerm, $searchCriteria);
//                    break;
//                case 'delivery_ref':
//                    $search->filterByDeliveryRef($searchTerm, $searchCriteria);
//                    break;
//                case 'transaction_ref':
//                    $search->filterByTransactionRef($searchTerm, $searchCriteria);
//                    break;
//                case 'customer_ref':
//                    $search->filterByCustomer(
//                            CustomerQuery::create()->filterByRef($searchTerm, $searchCriteria)->find()
//                    );
//                    break;
//                case 'customer_firstname':
//                    $search->filterByOrderAddressRelatedByInvoiceOrderAddressId(
//                            AmpSellerOrderAddressQuery::create()->filterByFirstname($searchTerm, $searchCriteria)->find()
//                    );
//                    break;
//                case 'customer_lastname':
//                    $search->filterByOrderAddressRelatedByInvoiceOrderAddressId(
//                            AmpSellerOrderAddressQuery::create()->filterByLastname($searchTerm, $searchCriteria)->find()
//                    );
//                    break;
//                case 'customer_email':
//                    $search->filterByCustomer(
//                            CustomerQuery::create()->filterByEmail($searchTerm, $searchCriteria)->find()
//                    );
//                    break;
//            }
//        }
    }

}
