<?php
/**
 * Packages manages required data for packages (prices especially)
 */
class Packages {
    const PACKAGE_TYPES = [
        'ID_STANDARD_TYPE' => 1,
        'ID_OPTION_TYPE' => 2,
        'ID_ADDITONAL_TYPE' => 3
    ];

    public function generatePackagePayRow($row, $orderType, $customerInfo, $commissionSplit, $totalCost, $interestRateValue){
        $prices = new Prices();

        $row['idOrderType'] = $orderType;
        $margins = $prices->getPriceMargins($commissionSplit, $row, $totalCost);
        if($customerInfo['isSameCompanyAsCl'] == 1){
            if($row['packagePayPeriod'] > 0){
                $row['fixedExtra'] = $row['minimalFixedPrice'];
                $row['recurentExtra'] = $prices->getRecurrentPriceMortage($row, $margins['clMargin'], $interestRateValue);
            }else{
                $row['fixedExtra'] = $row['minimalFixedPrice'] - $margins['clMargin'];
                $row['recurentExtra'] = 0;
            }
            $row['servicesExtra'] = $row['minimalServicesPrice'];
        }else{
            $row['fixedExtra'] = $row['fixedExtra'] + $row['minimalFixedPrice'];
            $row['recurentExtra'] = $row['packagePayPeriod'] > 0
                ? $row['recurentExtra'] +  $prices->getRecurrentPriceMortage($row, 0, $interestRateValue)
                : 0;
            $row['servicesExtra'] = $row['servicesExtra'] + $row['minimalServicesPrice'];
        }
        unset($row['minimalFixedPrice']);
        unset($row['minimalServicesPrice']);
        $row['isSameCompanyAsCl'] = $customerInfo['isSameCompanyAsCl'];

        return $row;
    }

    /**
     * get all prices types for a package by commercial lead
     * @param  INT $idCommercialLead id for commercial lead
     * @param  INT $idPackage        id for package(in case of additional or optional it represents the parent package)
     * @param  INT $type             id for package type => see self::PACKAGE_TYPES
     * @return Array                 prices array
     */
    public function getPricesForPackages($idCommercialLead, $idPackage, $type, $idPaymentType = 0, $idCustomer = 0){
        global $database, $user;
        $data = [];
        $whereSql = "";
        $extraJoin = "";
        $prices = new Prices();
        $clCustomersInst = new ClCustomers();
        $orderTypeInst = new OrderType();
        $interestRate = new InterestRate();
        $customerInfo = $clCustomersInst->getClCustomerInfo($idCommercialLead);
        $orderType = $customerInfo['idOrderType'] ? $customerInfo['idOrderType'] : $orderTypeInst->getCLDefaultOrderType($idCommercialLead);

        if($idCustomer === 0){
            $customerSql = "c.idUser=".$user->getUserId();
        }else{
            $customerSql = "c.id=".$idCustomer;
        }

        if($type === self::PACKAGE_TYPES['ID_STANDARD_TYPE']){
             $whereSql = "AND plcl.idPackage=$idPackage";
        }

        if($type === self::PACKAGE_TYPES['ID_OPTION_TYPE']){
             $whereSql = "AND pog.idPackage=$idPackage";
             $extraJoin = "INNER JOIN ".TABLES['rel_group_options']." rgo
                               ON rgo.idOptionPackage=plcl.idPackage
                            INNER JOIN ".TABLES['package_option_groups']." pog
                               ON pog.id=rgo.idGroup";
        }

        $productPrices = $prices->getPackageProductPrices($idPackage);
        $totalCost = $prices->calculatePackageTotalCost($productPrices);
        $commissionSplit = $prices->getCommissionSplit($idPackage);
        $interestRateValue = $interestRate->getInterestRate();
        $interestRateCustomers = $interestRate->getInterestRateForCustomers();

        if($type === self::PACKAGE_TYPES['ID_ADDITONAL_TYPE']){
             $whereSql = "AND rap.idPackage=$idPackage";
             $extraJoin = " INNER JOIN ".TABLES['rel_additional_packages']." rap
                           ON rap.idAdditionalPackage=plcl.idPackage";
        }

        if($idPaymentType){
            $whereSql .= " AND plcl.idPaymentType=$idPaymentType";
        }

        $sql = "SELECT
                   IF(custom_prices.idCustomer != 0, custom_prices.idCustomer, c.id) AS idCustomer,
                   plcl.id as idPrice,
                   plb.idPackage,
                   plb.idPaymentType,
                   pt.payType,
                   pt.packagePayPeriod,
                   pt.servicesContractPeriod,
                   pt.periodUnit,
                   pt.maxContractPeriod,
                   plcl.fixedExtra,
                   plcl.recurentExtra,
                   plcl.servicesExtra,
                   plb.minimalFixedPrice,
                   plb.minimalServicesPrice,
                   plb.principalAmount
               FROM ".TABLES['price_list_broker']." plb
               INNER JOIN
                   (SELECT
                       plcl.idPackage,
                           plcl.idPaymentType,
                           plcl.idCommercialLead,
                           MAX(IFNULL(idCustomer, 0)) AS idCustomer
                   FROM
                       ".TABLES['price_list_commercial_lead']." plcl
                       $extraJoin
                       LEFT OUTER JOIN ".TABLES['customers']." c
                           ON c.id = plcl.idCustomer
                   WHERE
                       ($customerSql OR c.idUser IS NULL)
                        $whereSql
                        AND plcl.idCommercialLead=$idCommercialLead
                   GROUP BY plcl.idPackage , plcl.idPaymentType
               ) AS custom_prices
                   ON plb.idPackage = custom_prices.idPackage
                       AND plb.idPaymentType = custom_prices.idPaymentType
                   INNER JOIN ".TABLES['price_list_commercial_lead']." plcl
                       ON plcl.idPackage = custom_prices.idPackage
                           AND plcl.idPaymentType = custom_prices.idPaymentType
                           AND plcl.idCommercialLead = custom_prices.idCommercialLead
                           AND IFNULL(plcl.idCustomer, 0) = custom_prices.idCustomer
                           AND plcl.visibleToCustomer = 1
                   INNER JOIN ".TABLES['payment_types']." pt
                       ON pt.id = plb.idPaymentType
                   INNER JOIN ".TABLES['customers']." c
                       ON $customerSql";

       $query = $database->query($sql);
       while($row = $database->fetchArray($query)){
           $interestRateCust = array_key_exists($row['idCustomer'], $interestRateCustomers) ? $interestRateCustomers[$row['idCustomer']] : $interestRateValue['interestRate'];
           $row = $this->generatePackagePayRow($row, $orderType, $customerInfo, $commissionSplit, $totalCost, $interestRateCust);
           $data[$row['idPackage']][] = $row;
       }

       return $data;
    }

    /**
     * checks if the customer is from the same company as the commercial lead
     * @param  Int $idUser           id of the user
     * @param  Int $idCommercialLead id of the commercial lead
     * @return Int                   1 if they are from the same company
     */
    public function checkIfCustomerIsFromCommercialLeadCompany($idCommercialLead, $isForCart = false) {
        global $database, $user;
        $extraJoin = "";
        $joinClause = "";
        $whereClause = "";
        $idUser = $user->getUserId();

        if($user->getUserType() !== USER_TYPES['CUSTOMER']) {
            return;
        }

        if($isForCart) {
            $extraJoin = "INNER JOIN ".TABLES['web_shop_cart']." cart
                            ON cart.idUser = $idUser
                          INNER JOIN ".TABLES['rel_commercial_lead_customers']." rclc
                            ON rclc.id = cart.idCustomerInstance";
            $joinClause = "AND cl.id = rclc.idCommercialLead";
        } else {
            $whereClause = "WHERE cl.id = $idCommercialLead";
        }

        $sql = "SELECT
                 u.idCompany
               FROM
                 ".TABLES['users']." u
                 $extraJoin
                 INNER JOIN ".TABLES['commercial_leads']." cl
                   ON u.id = cl.idUser
                   $joinClause
                 INNER JOIN
                   (SELECT
                     us.idCompany
                   FROM
                     ".TABLES['users']." us
                   WHERE us.id = $idUser) userCompany
                   ON userCompany.idCompany = u.idCompany
                 $whereClause";
        $result = $database->query($sql);

        return $database->numRows($result) > 0;
    }
}
