<?php

require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/custom/ntak/class/ntakconnector/ntak_config.class.php';
require_once DOL_DOCUMENT_ROOT.'/custom/ntak/class/ntakconnector/ntak_const.class.php';
require_once DOL_DOCUMENT_ROOT.'/custom/ntak/class/ntakconnector/ntak_date.class.php';
require_once DOL_DOCUMENT_ROOT.'/custom/ntak/class/ntakproduct.class.php';

class NtakInvoice extends Facture
{
    const HUF = 'HUF';

    public $payments;

    public function loadPayments(): void
    {
        $this->payments = $this->getListOfPayments();
    }
    /**
     * 
     */
    public function isHufInvoice(): bool
    {
        return ($this->multicurrency_code == self::HUF);
    }
    /**
     * 
     */
    public function getExchangeRate(): float
    {
        return $this->multicurrency_tx;
    }
    /**
     * 
     */
    public function getNtakPaymentMethod(): string
    {
        $paymentType = null;
        $isHufInvoice = $this->isHufInvoice();

        $paymentMethod = $this->mode_reglement_code;
        if (empty($paymentMethod) && !empty($this->payments[0]['type'])) {
            $paymentMethod = $this->payments[0]['type'];
        }

        if ($paymentMethod == 'LIQ') {
            // cash
            $paymentType = ($isHufInvoice) ? NtakConst::PAYMENT_METHOD_CASH_HUF : NtakConst::PAYMENT_METHOD_CASH_EUR;            
        } else if ($paymentMethod == 'CB') {
            // credit card
            $paymentType = NtakConst::PAYMENT_METHOD_CREDIT_CARD;
        }

        return $paymentType;
    }
    /**
     * 
     */
    public function ntakPaymentMethods(): array
    {
        $result = [];

        $paymentMethod = $this->getNtakPaymentMethod();

        $prices = $this->getRoundedTransactionPrices();

        extract($prices, EXTR_PREFIX_SAME, '');

        //$diff = (int) MoneyHandler::round($diff);

        $result[] = [
            'fizetesiMod' => $paymentMethod,
            'fizetettOsszegHUF' => $rounded
        ];

        if ($diff != 0) {
            $result[] = [
                'fizetesiMod' => "KEREKITES",
                'fizetettOsszegHUF' => $diff
            ];
        }

        return $result;
    }
    /**
     * 
     */
    public function getRoundedTransactionPrices(): array
    {
        $paymentMethod = $this->getNtakPaymentMethod();
        $diff = 0;
        $rounded = $this->getTotalTransaction();
        $payedTotal = $rounded;

        if ($paymentMethod === NtakConst::PAYMENT_METHOD_CASH_HUF) {
            // KP HUF - 0 & 5
            $rounded = (int) MoneyHandler::round($payedTotal);

            if ($rounded > $payedTotal) {
                $diff = $payedTotal - $rounded;
            } else if ($rounded < $payedTotal) {
                $diff = $payedTotal - $rounded;
            }
        } else if ($paymentMethod === NtakConst::PAYMENT_METHOD_CASH_EUR) {
            // KP EUR - INT
            //$rounded = (int) MoneyHandler::round($this->total_ttc);
            //$rounded = floor($this->total_ttc);
            $rounded = round($this->total_ttc);


            //var_dump($this->total_ttc);
            //var_dump(round($this->total_ttc));
            //var_dump($rounded);
            //die;

            //$rounded = round($rounded);
        }

        return [
            'rounded' => $rounded,
            'diff' => $diff
        ];
    }
    /**
     * 
     */
    public function getTotalTransaction(): int
    {
        return floor($this->total_ttc);
        //return $this->multicurrency_total_ttc;

        // sum items
        /*
        $total = array_reduce(
            $this->lines, 
            function($carry, $item) {                
                return $carry + $item->total_ttc;
            }
        );

        if (!$this->isHufInvoice()) {
            $rate = $this->getExchangeRate();
            $total = $total * $rate;
        }

        return $total;
        */
    }

    /**
     * 
     */
    private function loadProduct(int $productId): NtakProduct
    {
        $product = new NtakProduct($this->db);
        if ($product->fetch($productId) < 1) {
            throw new \Exception('Product not found (PID: '.$productId.', Invoice ID: '.$this->id.')');
        }

        return $product;
    }
    /**
     * 
     */
    public function getProductDetails(): array
    {
        $products = [];

        foreach ($this->lines as $line) {
            $products[] = $this->loadProduct($line->fk_product);
        }
        /*
        $line = $this->lines[0];
        if ($line) {
            $product = $this->loadProduct($line->fk_product);
            // is this bundle?
            $associatedProducts = $product->getChildsArbo($product->id);
            if (empty($associatedProducts)) {
                $products[] = $product;
            } else {
                foreach ($associatedProducts as $prodId => $child) {
                    $products[] = $this->loadProduct($prodId);
                }
            }
        }
        */
        return $products;
    }
    /**
     * 
     */
    public function ntakSoldTickets(): array
    {
        $soldTickets = [];

        if (!empty($this->lines)) {
            $needTicketIdIndex = (count($this->lines) > 1);

            foreach ($this->lines as $i => $line) {
                $product = $this->loadProduct($line->fk_product);

                if ($this->isBpCard($product->ref)) {
                    continue;
                }

                //$price = doubleval($line->multicurrency_total_ttc);
                $price = doubleval($line->total_ttc);
                
                $ticketIdentifier = $this->ref;
                if ($needTicketIdIndex) {
                    $index = $i + 1;
                    $ticketIdentifier .= "-{$index}";
                }
                
                $isDiscountTicket = ($line->multicurrency_subprice == $line->multicurrency_total_ht || $line->remise_percent > 0);

                $soldTickets[] = [
                    'afaKategoria' => $product->getNtakVatCode(),
                    'azonnalFelhasznalt' => false,
                    'bruttoAr' => floor($price), //doubleval($product->price_ttc), //intval($price['rounded']), doubleval($this->total_ttc),
                    'ervenyessegKezdete' => NtakDate::timestampToRfc3339($this->date_modification),
                    'jegyAzonosito' => $ticketIdentifier,
                    'jegyErvenyessegTipusa' => $product->getNtakTicketValidType(),                    
                    /* NTAK TESZT */
                    'jegyMegnevezes' => ($isDiscountTicket) ? 'Egyszeri diák' : 'Egyszeri teljesárú felnőtt', 
                    'korcsoport' => ($isDiscountTicket) ? NtakConst::AGE_GROUP_STUDENT : NtakConst::AGE_GROUP_ADULT,
                    'maxBelepesekSzama' => 1, 
                    /* /NTAK TESZT */                    
                    //'jegyMegnevezes' => $product->label,
                    //'korcsoport' => NtakConst::AGE_GROUP_MIX,
                    //'maxBelepesekSzama' => $product->getNtakMaxNumberOfUse(),
                    'kedvezmenyek' => [],
                    'ntakRendszerKategoria' => NtakConst::SYSTEM_CATEGORY_INDIVIDUAL,
                    'programazonosito' => [
                        'tssProgramAzonosito' => $product->ref,
                        'utolsoModositasIdeje' => NtakDate::timestampToRfc3339(strtotime($product->date_modification))
                    ],
                    'szemelyekSzama' => 1
                ];
            }            
        }

        return $soldTickets;
    }
    /**
     * 
     */
    public function ntakDiscount(): array
    {
        $discount = [];
        
        if (!empty($this->lines[0])) {
            $line = $this->lines[0];

            $vat = (int) $line->tva_tx;
            $vatCategory = NtakConst::getVatCodeByVat($vat);

            if ($line->remise_percent > 0) {
                $vat = (int) $line->tva_tx;

                $price = $line->subprice;
                $grossPrice = $price * (1 + ($line->tva_tx / 100));
                //$discountPrice = $grossPrice * (1 - ($line->remise_percent / 100));

                $discountPrice = $line->total_ttc - $grossPrice;
                if ($this->getNtakPaymentMethod() != NtakConst::PAYMENT_METHOD_CREDIT_CARD) {
                    $discountPrice = (int) MoneyHandler::round($discountPrice);
                }
                
                $discount[] = [
                    'tetelAzonosito' => $line->id,
                    'tetelMegnevezes' => "Kedvezmény",
                    'kategoria' => NtakConst::ITEM_CATEGORY_DISCOUNT,
                    'tetelszam' => 1,
                    'bruttoEgysegAr' => $discountPrice, //(int) MoneyHandler::round(($line->total_ttc - $grossPrice)),  //($discountPrice - $grossPrice),
                    'afaKategoria' => $vatCategory
                ];
            }
            /* else {                
                $sumProducts = 0;
                $products = $this->getProductDetails();

                if (count($products) > 1) {
                    $sumProducts = array_sum(
                        array_column(
                            $products, 
                            'price_ttc'
                        )
                    );

                    $discountDiff = floatval($this->total_ttc) - $sumProducts;

                    $discount[] = [
                        'tetelAzonosito' => $line->id,
                        'tetelMegnevezes' => "Kedvezmény",
                        'kategoria' => NtakConst::ITEM_CATEGORY_DISCOUNT,
                        'tetelszam' => 1,
                        'bruttoEgysegAr' => $discountDiff,
                        'afaKategoria' => $vatCategory
                    ];  
                }                
            }
            */
        }
        

        return $discount;
    }
    /**
     * 
     */
    public function isBpCard(string $ref): bool
    {
        return (preg_match('/card/', $ref));
    }


    /**
     * 
     */
    public function ntakProgramDetails(): array
    {
        $result = [];

        $details = $this->getProductDetails();
        foreach ($details as $ntakProduct) {
            if ($this->isBpCard($ntakProduct->ref)) {
                continue;
            }

            $ntakProduct->isIndividualProgram = false;
            $result[] = $ntakProduct->getNtakProgramDetails();
        }

        $isCombined = (count($details) > 1);
        if ($isCombined) {
            $product = $this->loadProduct($this->lines[0]->fk_product);
            $product->associtedProducts = $details;
            $product->isCombinedProgram = true;

            $result[] = $product->getNtakProgramDetails();
        }

        return $result;
    }
    /**
     * 
     */
    public function ntakCustomerData(): array
    {
        $visitorData = [];
        if (!empty($this->array_options['options_customer_data_zip'])) {
            $visitorData['latogatokLakohelye'] = $this->array_options['options_customer_data_zip'];            
        } elseif (!empty($this->array_options['options_customer_data_countrycode'])) {
            $visitorData['latogatokLakohelye'] = $this->array_options['options_customer_data_countrycode'];
        } else {
            $visitorData['latogatokLakohelye'] = '';
        }

        $visitorData['kulfoldi'] = boolval($this->array_options['options_ntak_is_foreigner']);

        return $visitorData;
    }
}