<?php

//the global file operation
include("../public/impOpreation.php");

//global varable
global $showoutside;

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.php");
include("reportfunctions.php");

//here the db files that include in the file
include("../public/include_dao.php");
//Sellbill
require_once('../models/dao/SellbillDAO.class.php');
require_once('../models/dto/Sellbill.class.php');
require_once('../models/mysql/SellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillMySqlExtDAO.class.php');
//Returnsellbill
require_once('../models/dao/ReturnsellbillDAO.class.php');
require_once('../models/dto/Returnsellbill.class.php');
require_once('../models/mysql/ReturnsellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbillMySqlExtDAO.class.php');
//Sellbillandrutern
require_once('../models/dao/SellbillandruternDAO.class.php');
require_once('../models/dto/Sellbillandrutern.class.php');
require_once('../models/mysql/SellbillandruternMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillandruternMySqlExtDAO.class.php');
//Sellbilldetail
require_once('../models/dao/SellbilldetailDAO.class.php');
require_once('../models/dto/Sellbilldetail.class.php');
require_once('../models/mysql/SellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbilldetailMySqlExtDAO.class.php');
//Returnsellbilldetail
require_once('../models/dao/ReturnsellbilldetailDAO.class.php');
require_once('../models/dto/Returnsellbilldetail.class.php');
require_once('../models/mysql/ReturnsellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbilldetailMySqlExtDAO.class.php');
//Sellandruternbilldetail
require_once('../models/dao/SellandruternbilldetailDAO.class.php');
require_once('../models/dto/Sellandruternbilldetail.class.php');
require_once('../models/mysql/SellandruternbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SellandruternbilldetailMySqlExtDAO.class.php');
//Product
require_once('../models/dao/ProductDAO.class.php');
require_once('../models/dto/Product.class.php');
require_once('../models/mysql/ProductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductMySqlExtDAO.class.php');
//Productunit
require_once('../models/dao/ProductunitDAO.class.php');
require_once('../models/dto/Productunit.class.php');
require_once('../models/mysql/ProductunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductunitMySqlExtDAO.class.php');
//Buybill
require_once('../models/dao/BuybillDAO.class.php');
require_once('../models/dto/Buybill.class.php');
require_once('../models/mysql/BuybillMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybillMySqlExtDAO.class.php');
//Buybilldetail
require_once('../models/dao/BuybilldetailDAO.class.php');
require_once('../models/dto/Buybilldetail.class.php');
require_once('../models/mysql/BuybilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybilldetailMySqlExtDAO.class.php');
//Buyandruternbill
require_once('../models/dao/BuyandruternbillDAO.class.php');
require_once('../models/dto/Buyandruternbill.class.php');
require_once('../models/mysql/BuyandruternbillMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbillMySqlExtDAO.class.php');
//Buyandruternbilldetail
require_once('../models/dao/BuyandruternbilldetailDAO.class.php');
require_once('../models/dto/Buyandruternbilldetail.class.php');
require_once('../models/mysql/BuyandruternbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbilldetailMySqlExtDAO.class.php');
//Returnbuybill
require_once('../models/dao/ReturnbuybillDAO.class.php');
require_once('../models/dto/Returnbuybill.class.php');
require_once('../models/mysql/ReturnbuybillMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybillMySqlExtDAO.class.php');
//Returnbuybilldetail
require_once('../models/dao/ReturnbuybilldetailDAO.class.php');
require_once('../models/dto/Returnbuybilldetail.class.php');
require_once('../models/mysql/ReturnbuybilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybilldetailMySqlExtDAO.class.php');
//Productcat
require_once('../models/dao/ProductcatDAO.class.php');
require_once('../models/dto/Productcat.class.php');
require_once('../models/mysql/ProductcatMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatMySqlExtDAO.class.php');

//Programsetting
require_once('../models/dao/ProgramsettingsDAO.class.php');
require_once('../models/dto/Programsetting.class.php');
require_once('../models/mysql/ProgramsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProgramsettingsMySqlExtDAO.class.php');

require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');

//get the do the action
$do = $_GET['do'];

/* ======================
  Controller Name :- profitreportCTRL تقرير أرباح منتج

  OPERTATION in Controller

  1- search with product name or date
  ======================== */

//here the global templates
$smarty->display("header.html");

//here goes the instances and general variables
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
//Sellbill
$mySellbillEx = new SellbillMySqlExtDAO();
$mySellbillRecord = new SellbillMySqlDAO();
//Returnsellbill
$myReturnsellbillEx = new ReturnsellbillMySqlExtDAO();
$myReturnsellbillRecord = new ReturnsellbillMySqlDAO();
//Sellbillandrutern
$mySellbillandruternRecord = new SellbillandruternMySqlDAO();
$mySellbillandruternEx = new SellbillandruternMySqlExtDAO();
//Sellbilldetail
$mySellbilldetailEx = new SellbilldetailMySqlExtDAO();
//Returnsellbilldetail
$myReturnsellbilldetailEx = new ReturnsellbilldetailMySqlExtDAO();
//Sellandruternbilldetail
$mySellandruternbilldetailEx = new SellandruternbilldetailMySqlExtDAO();
//Product
$myProductRecord = new ProductMySqlDAO();
$myProductEx = new ProductMySqlExtDAO();
//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();
$myProductunitRecord = new ProductunitMySqlDAO();
//Buybill
$myBuybillRecord = new BuybillMySqlDAO();
//Buybilldetail
$myBuybilldetailEx = new BuybilldetailMySqlExtDAO();
//Buyandruternbill
$myBuyandruternbillRecord = new BuyandruternbillMySqlDAO();
//Buyandruternbilldetail
$myBuyandruternbilldetailEx = new BuyandruternbilldetailMySqlExtDAO();
//Returnbuybill
$myReturnbuybillRecord = new ReturnbuybillMySqlDAO();
//Returnbuybilldetail
$myReturnbuybilldetailEx = new ReturnbuybilldetailMySqlExtDAO();
//Productcat
$myProductcatRecord = new ProductcatMySqlDAO();
$myProductcatEx = new ProductcatMySqlExtDAO();


//billsproducts
$billsProducts = new Billsproduct();
$billsProductsDAO = new BillsproductsMySqlDAO();
$billsProductsEX = new BillsproductsMySqlExtDAO();

//billsproducts
$billsReturnProducts = new Billsreturnproduct();
$billsReturnProductsDAO = new BillsreturnproductsMySqlDAO();
$billsReturnProductsEX = new BillsreturnproductsMySqlExtDAO();


$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();


//check and use the condetion that suite this action
if ($do == "show" || empty($do)) {
    include_once("../public/authentication.php");
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    ##التصنيفات
    $catDataReport = getCategoryChilds();
    $smarty->assign("catDataReport", $catDataReport[1]);

    $dis = filter_input(INPUT_GET, 'dis');

    $productSearchId = $_REQUEST['productId'];
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $isOptic = filter_input(INPUT_POST, 'proIsOptic');
    if (!isset($isOptic) || empty($isOptic)) {
        $isOptic = 0;
    }
    if ($isOptic == 2) {
        $productsOfCat = $ProductEX->queryByProductCatIdIn($productSearchId);
        $productId = '0';
        foreach ($productsOfCat as $value) {
            $productId .= ',' . $value->productId;
        }
    }

//    $Programsettingdata = $ProgramsettingDAO->load(1);
    ########
    if (empty($startDate) && empty($endDate)) {
        $startDate = date('Y-m-d');
        $endDate = date('Y-m-d');
    }
    ########
    $Programsetting = $ProgramsettingDAO->load(1);
    $smarty->assign("programsettingsdata", $Programsetting);
    if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
        $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
        $endDate = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($endDate)));
        $startDate = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($startDate)));
    } else {
        $endDate = $endDate . ' 23:59:59';
        $startDate = $startDate . " 00:00:00";
    }
    #############



    if (isset($startDate) && isset($endDate) && $startDate != "" && $endDate != "" && isset($productSearchId) && $productSearchId != "-1" && $productSearchId != "") {
        if ($isOptic == 2) {
            $productData = $myProductcatEx->getCategoryAndParentByCatId($productSearchId);
            $message = "تقرير أرباح للمنتج <h4>" . $productData->productCatName . "/ " . $productData->parentName . "</h4> والتاريخ من " . $startDate . " إلى " . $endDate;
            $productData->productName = $productData->productCatName . "/ " . $productData->parentName;
            $smarty->assign("productData", $productData);
        } else {
            $productData = $myProductEx->loadProduct($productSearchId);
            $overAllAveragePrice = $productData->overAllAveragePrice;
            $message = "تقرير أرباح للمنتج <h4>" . $productData->productName . "/ " . $productData->productCatName . "</h4> والتاريخ من " . $startDate . " إلى " . $endDate;
            $productData->productName = $productData->productName . "/ " . $productData->productCatName;
            $smarty->assign("productData", $productData);
        }
        $smarty->assign("message", $message);
        if ($isOptic == 2) {
            $productSearchId = $productId;
        }
        getProductInBillByDateAndProductId($startDate, $endDate, $productSearchId, $overAllAveragePrice);
    }
    if ($dis == 'T') {
        //here the smarty templates
        $smarty->display("profitproductview/showdiscount.html");
    } else {
        //here the smarty templates
        $smarty->display("profitproductview/show.html");
    }
    $smarty->assign("settlementstoreshow", 1);
}
//here the global templates
$smarty->display("footer.html");

/* ===============================
  function in this CONTROLLER
  ================================ */

function getProductInBillByDateAndProductId($startDate, $endDate, $productId, $overAllAveragePrice) {
    global $mySellbilldetailEx;
    global $myProductRecord;
    global $Programsetting;

    global $smarty;

    //sellbill
    $sellPriceData = getTotalSellPriceByDateAndProductId($startDate, $endDate, $productId, $overAllAveragePrice);

    $sellPricePulsData = getTotalAditionalSellPriceByDateAndProductId($startDate, $endDate, $productId, $overAllAveragePrice);

    $sellOpticData = getTotalOpticByDateAndProductId($startDate, $endDate, $productId);
    $sellPrice = $sellPriceData[0] + $sellPricePulsData[0] + $sellOpticData[0];
    $quantityUnit = $sellPriceData[1] + $sellPricePulsData[1] + $sellOpticData[1];
    $discountPrice = $sellPriceData[3] + $sellPricePulsData[3] + $sellOpticData[3];





    $totalSellPrice = $totalSellPrice + $sellPrice;
    $totalQuantityUnit = $totalQuantityUnit + $quantityUnit;

    //return sellbill
    $returnSellPriceData = getTotalReturnSellPriceByDateAndProductId($startDate, $endDate, $productId, $overAllAveragePrice);

    $returnSellPricePulsData = getTotalAditionalReturnSellPriceByDateAndProductId($startDate, $endDate, $productId, $overAllAveragePrice);

    $returnOpticData = getTotalReturnOpticByDateAndProductId($startDate, $endDate, $productId);

    /* 	print_r("المردودات".$returnSellPriceData[0]);
      print_r("<br>سعر الاصلى المردودات".$returnSellPriceData[2]);
      //finalbuypric
      print_r("<br>");
      print_r("المبيعات فى المردودات".$returnSellPricePulsData[0]);

      print_r("<br>سعر الاصلى المردودات".$returnSellPricePulsData[2]);
      print_r("<br>");
      //print_r($sellPricePulsData);
      print_r("<br>");
     */
    $returnSellPrice = $returnSellPriceData[0] + $returnSellPricePulsData[0] + $returnOpticData[0];
    $returnQuantityUnit = $returnSellPriceData[1] + $returnSellPricePulsData[1] + $returnOpticData[1];

    $totalReturnSellPrice = $totalReturnSellPrice + $returnSellPrice;
    $totalreturnQuantityUnit = $totalreturnQuantityUnit + $returnQuantityUnit;

    //buybill
    $buybillPriceData = getTotalBuyPriceByDateAndProductId($startDate, $endDate, $productId, $overAllAveragePrice);

    $buybillPricePulsData = getTotalAditionalBuyPriceByDateAndProductId($startDate, $endDate, $productId, $overAllAveragePrice);

    $buybillPrice = $buybillPriceData[0] + $buybillPricePulsData[0];
    $buyQuantityUnit = $buybillPriceData[1] + $buybillPricePulsData[1];


    $totalBuybillPrice = $totalBuybillPrice + $buybillPrice;
    $totalBuyQuantityUnit = $totalBuyQuantityUnit + $buyQuantityUnit;

    //return buybill
    $returnBuybillPriceData = getTotalReturnBuyPriceByDateAndProductId($startDate, $endDate, $productId, $overAllAveragePrice);

    $returnBuybillPricePulsData = getTotalAditionalBuyPriceByDateAndProductId($startDate, $endDate, $productId, $overAllAveragePrice);

    $returnBuybillPrice = $returnBuybillPriceData[0] + $returnBuybillPricePulsData[0];
    $returnBuyQuantityUnit = $returnBuybillPriceData[1] + $returnBuybillPricePulsData[1];

    $totalReturnBuybillPrice = $totalReturnBuybillPrice + $returnBuybillPrice;
    $totalReturnBuyQuantityUnit = $totalReturnBuyQuantityUnit + $returnBuyQuantityUnit;

    /* print("sellPrice: ".$sellPrice."<br>");
      print("returnBuybillPrice: ".$returnBuybillPrice."<br>");
      print("buybillPrice: ".$buybillPrice."<br>");
      print("returnSellPrice: ".$returnSellPrice."<br>");


     */
    $yy = $sellPrice - $returnSellPrice;
    //print("yy: ".$yy."<br>");


    /* print_r("المبيعات".$sellPriceData[0]);
      print_r("<br>سعر الاصلى للمبيعات".$sellPriceData[2]);
      //finalbuypric
      print_r("<br>");
      print_r("المبيعات فى الردودات".$sellPricePulsData[0]);

      print_r("<br>سعر الاصلى للمبيعات".$sellPricePulsData[2]);
      print_r("<br>");
      //print_r($sellPricePulsData);
      print_r("<br>");
     */
    //$profitForOneProduct = ($sellPrice + $returnBuybillPrice) - ($buybillPrice + $returnSellPrice);
    //$profitForOneProduct =($sellPriceData[0]+$sellPricePulsData[0])-($sellPriceData[2]+$sellPricePulsData[2]);


    print_r($profitForOneProduct);
    $quantityForOneProduct = $quantityUnit - $returnQuantityUnit;

    //سعر الوحده
    $xx = ($buybillPrice) / $quantityUnit;
    //print("xx: ".$xx."<br>");
    //print("quantityForOneProduct: ".$quantityForOneProduct."<br>");
    ###
    ###
    //* 1.15 "vatValue" include vat to buy price to make profit calculations true like sales includes vat
    $vatValue = 1 + ($Programsetting->vatValue / 100);
    $profitForOneProduct = ($yy) - ($quantityForOneProduct * $xx * $vatValue);
    $smarty->assign("discountPrice", $discountPrice);
    $smarty->assign("profitForOneProduct", round($profitForOneProduct, 2));
    $smarty->assign("quantityForOneProduct", $quantityForOneProduct);
}

// show the form by date
function getTotalSellPriceByDateAndProductId($startDate, $endDate, $ProductIdselected, $overAllAveragePrice) {
    global $mySellbilldetailEx;
    global $myProductunitRecord;
    global $mySellbillRecord;
    global $myProductRecord;
    global $myProductEx;
    global $myProductunitEx;

    $sellPrice = 0;
    $quantityUnit = 0;
    $finalbuypric = 0;
    $discountPrice = 0;
    $sellbilldetailData = $mySellbilldetailEx->queryWithDateAndConditionsAndProductIdExt($startDate, $endDate, $ProductIdselected);

    $buyPriceType = $_POST["buyPriceType"];
    foreach ($sellbilldetailData as $sellbilldetail) {
        $quantity = $sellbilldetail->sellbilldetailquantity;
        $price = $sellbilldetail->sellbilldetailprice;
        $totalPrice = $sellbilldetail->sellbilldetailtotalprice;
        $discountValue = $sellbilldetail->discountvalue;
        $productunitId = $sellbilldetail->productunitid;
        $sellbillTotalBill = $sellbilldetail->sellbilltotalbill;
        $sellbillDiscount = $sellbilldetail->sellbilldiscount;
        $sellbillDiscountType = $sellbilldetail->sellbilldiscounttype;
//        if ($buyPriceType == "last") {
//            $buyPrice = (float) $sellbilldetail->lastbuyprice;
//        } else {
//            $buyPrice = (float) $sellbilldetail->meanbuyprice;
//        }

        switch ($buyPriceType) {
            case "first":
                $buyprice = (float) $sellbilldetail->buyprice;
                break;
            case "last":
                $buyprice = (float) $sellbilldetail->lastbuyprice;
                break;
            case "mean":
                $buyprice = (float) $sellbilldetail->meanbuyprice;
                break;
            case "last_discount":
                $buyprice = (float) $sellbilldetail->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyprice = (float) $sellbilldetail->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyprice = (float) $overAllAveragePrice;
                break;
            case "tax":
                $buyprice = (float) $sellbilldetail->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $buyprice = (float) $sellbilldetail->meanbuyprice_withTax;
                break;
        }

        if ($sellbillDiscountType == 2) {
            $sellbillDiscount = ($sellbillDiscount / 100) * $sellbillTotalBill;
        }

        $totalPriceBeforeDiscount = $price * $quantity; //product price before discount

        $productnumber = $myProductunitEx->getProductNumber($productunitId);

        $quantityUnit += ($quantity * $productnumber); //الكمية * عدد القطع في وحدة القياس
        //first Step قيمة خصم المنتج على الوحدة
        //$firstStep = $discountValue;
        //second Stepقيمة المنتج من الخصم على المنتج
        //$secondStep = $totalPrice / $sellbillTotalBill;

        if ($sellbillTotalBill == 0) {
            $sellbillTotalBill = 1;
        }
        //third Step قيمة الخصم للمنتجات
        $thirdStep = ($totalPrice / $sellbillTotalBill) * $sellbillDiscount;

        //fourth Step  قيمة خصم الفاتورة للوحدة
        //$fourthStep = $thirdStep;
        //$sellPriceForOneProduct= $totalPriceBeforeDiscount - ($firstStep + $fourthStep);
        $allbuyprice = $buyprice * $quantity;
        $finalbuypric += $allbuyprice;
        $totalPriceDiscount = $discountValue + $thirdStep;
        $sellPriceForOneProduct = $totalPriceBeforeDiscount - $totalPriceDiscount;
        $sellPrice += $sellPriceForOneProduct;
        $discountPrice += $totalPriceDiscount;
    }



    return array($sellPrice, $quantityUnit, $finalbuypric, $discountPrice);
}

// show the form by date
function getTotalAditionalSellPriceByDateAndProductId($startDate, $endDate, $ProductIdselected, $overAllAveragePrice) {
    global $mySellandruternbilldetailEx;
    global $mySellbillandruternRecord;
    global $myProductunitRecord;
    global $myProductRecord;
    global $myProductEx;
    global $myProductunitEx;

    $sellPrice = 0;
    $quantityUnit = 0;
    $fianlbuyprice = 0;
    $sellbillTotalBillnor = 0;

    $sellandreturndetailData = $mySellandruternbilldetailEx->queryWithDateAndConditionsTypeAndProductIdExt($startDate, $endDate, 0, $ProductIdselected);

    $buyPriceType = $_POST["buyPriceType"];
    foreach ($sellandreturndetailData as $sellandreturndetail) {

        //print_r($sellandreturndetail);
        $quantity = $sellandreturndetail->sellbilldetailquantity;
        $price = $sellandreturndetail->sellbilldetailprice;
        $totalPrice = $sellandreturndetail->sellbilldetailtotalprice;
        $discountValue = $sellandreturndetail->discountvalue;
        $productunitId = $sellandreturndetail->productunitid;
        $sellbillTotalBill = $sellandreturndetail->sellbillprice;
        $sellbillDiscount = $sellandreturndetail->sellbilldiscount; //محتاجة تتغير
        $sellbillDiscountType = $sellandreturndetail->sellbilldiscounttype;
        //$buyprice = $sellandreturndetail->buyprice;
//        if ($buyPriceType == "last") {
//            $buyPrice = (float) $sellandreturndetail->lastbuyprice;
//        } else {
//            $buyPrice = (float) $sellandreturndetail->meanbuyprice;
//        }


        switch ($buyPriceType) {
            case "first":
                $buyprice = (float) $sellandreturndetail->buyprice;
                break;
            case "last":
                $buyprice = (float) $sellandreturndetail->lastbuyprice;
                break;
            case "mean":
                $buyprice = (float) $sellandreturndetail->meanbuyprice;
                break;
            case "last_discount":
                $buyprice = (float) $sellandreturndetail->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyprice = (float) $sellandreturndetail->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyprice = (float) $overAllAveragePrice;
                break;
            case "tax":
                $buyprice = (float) $sellandreturndetail->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $buyprice = (float) $sellandreturndetail->meanbuyprice_withTax;
                break;
        }
        $returnsellbillprice = $sellandreturndetail->returnsellbillprice;



        if ($sellbillDiscountType == 2) {
            //$sellbillDiscount = ($sellbillDiscount / 100) * $sellbillTotalBill;
        }

        $sellbillTotalBillnor = $sellbillTotalBillnor + $totalPrice;
//
//			//load Product Data
//			$productData=$myProductRecord->load($productId);
//
//			$productSellPrice;
//			//تجزئة
//			if($priceType == 1)
//			{
//				$productSellPrice=$productData->productSellUnitPrice;
//			}
//			//جملة
//			elseif($priceType == 0)
//			{
//				$productSellPrice=$productData->productSellAllPrice;
//			}
//			//نصف جملة
//			elseif($priceType == 2)
//			{
//				$productSellPrice=$productData->productSellHalfPrice;
//			}
//

        $totalPriceBeforeDiscount = $price * $quantity;

        $productnumber = $myProductunitEx->getProductNumber($productunitId);

        $quantityUnit += ($quantity * $productnumber);

        if ($sellbillTotalBill == 0) {
            $sellbillTotalBill = 1;
        }
        //third Step قيمة الخصم للمنتجات
        $thirdStep = ($totalPrice / $sellbillTotalBill) * $sellbillDiscount;
        $allbuyprice = $quantity * $buyprice;
        $fianlbuyprice += $allbuyprice;
        $totalPriceDiscount = $discountValue + $thirdStep;

        $sellPriceForOneProduct = $totalPriceBeforeDiscount - $totalPriceDiscount;
        $sellPrice += $sellPriceForOneProduct;
    }
    $sellbillTotalBillnor = $sellbillTotalBillnor - $returnsellbillprice;
    ;
    /* print_r('<br>sellbillTotalBillnor'.$sellbillTotalBillnor);
      print_r('<br>returnsellbillprice'.$returnsellbillprice);
      print_r('<br>sellbillDiscount'.$sellbillDiscount); */
    if ($sellbillDiscountType == 2) {
        $sellbillDiscountxx = ($sellbillDiscount / 100) * $sellbillTotalBillnor;
        //print_r('<br>sellbillDiscountxx'.$sellbillDiscountxx);
    } else {
        $sellbillDiscountxx = ($sellbillDiscount);
    }

    $sellPrice = $sellPrice - $sellbillDiscountxx;

    $thirdStep = ($totalPrice / $sellbillTotalBill) * $sellbillDiscount;

    return array($sellPrice, $quantityUnit, $fianlbuyprice, $totalPriceDiscount);
}

function getTotalReturnSellPriceByDateAndProductId($startDate, $endDate, $ProductIdselected) {
    global $myReturnsellbilldetailEx;
    global $myReturnsellbillRecord;
    global $myProductunitRecord;
    global $myProductRecord;
    global $myProductEx;
    global $myProductunitEx;

    $ReturnSellPrice = 0;
    $quantityUnit = 0;
    $finalbuyprice = 0;

    $returnsellbilldetailData = $myReturnsellbilldetailEx->queryWithDateAndConditionsAndProductIdExt($startDate, $endDate, $ProductIdselected);

    $buyPriceType = $_POST["buyPriceType"];
    foreach ($returnsellbilldetailData as $returnsellbilldetail) {
        $quantity = $returnsellbilldetail->returnsellbilldetailquantity;
        $price = $returnsellbilldetail->returnsellbilldetailprice;
        $totalPrice = $returnsellbilldetail->returnsellbilldetailtotalprice;
        $discountValue = $returnsellbilldetail->discountvalue;
        $productunitId = $returnsellbilldetail->productunitid;
        $sellbillTotalBill = $returnsellbilldetail->returnsellbilltotalbill;
        $sellbillDiscount = $returnsellbilldetail->returnsellbilldiscount;
        $sellbillDiscountType = $returnsellbilldetail->returnsellbilldiscounttype;
        //$buyprice = $returnsellbilldetail->buyprice;
//        if ($buyPriceType == "last") {
//            $buyPrice = (float) $returnsellbilldetail->lastbuyprice;
//        } else {
//            $buyPrice = (float) $returnsellbilldetail->meanbuyprice;
//        }

        switch ($buyPriceType) {
            case "first":
                $buyPrice = (float) $sellbilldetail->buyprice;
                break;
            case "last":
                $buyPrice = (float) $sellbilldetail->lastbuyprice;
                break;
            case "mean":
                $buyPrice = (float) $sellbilldetail->meanbuyprice;
                break;
            case "last_discount":
                $buyPrice = (float) $sellbilldetail->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyPrice = (float) $sellbilldetail->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyPrice = (float) $sellbilldetail->generalPrice;
                break;
            case "tax":
                $buyprice = (float) $sellbilldetail->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $buyprice = (float) $sellbilldetail->meanbuyprice_withTax;
                break;
            default:
                $buyPrice = (float) $sellbilldetail->meanbuyprice;
                break;
        }

        if ($sellbillDiscountType == 2) {
            $sellbillDiscount = ($sellbillDiscount / 100) * $sellbillTotalBill;
        }

        $totalPriceBeforeDiscount = $price * $quantity;

        $productnumber = $myProductunitEx->getProductNumber($productunitId);

        $quantityUnit += ($quantity * $productnumber);

        if ($sellbillTotalBill == 0) {
            $sellbillTotalBill = 1;
        }
        //third Step قيمة الخصم للمنتجات
        $thirdStep = ($totalPrice / $sellbillTotalBill) * $sellbillDiscount;


        $allbuyprice = $quantity * $buyprice;

        //print_r("<br>buyprice".$buyprice);
        //print_r("<br>quantity".$quantity);
        $finalbuyprice += $allbuyprice;
        $ReturnSellPriceForOneProduct = $totalPriceBeforeDiscount - ($discountValue + $thirdStep);
        $ReturnSellPrice += $ReturnSellPriceForOneProduct;
    }

//print($ReturnSellPrice."ReturnSellPrice<br>");

    return array($ReturnSellPrice, $quantityUnit, $finalbuyprice);
}

// show the form by date
function getTotalAditionalReturnSellPriceByDateAndProductId($startDate, $endDate, $ProductIdselected) {
    global $mySellandruternbilldetailEx;
    global $mySellbillandruternRecord;
    global $myProductunitRecord;
    global $myProductRecord;
    global $myProductunitEx;

    $ReturnSellPrice = 0;
    $quantityUnit = 0;
    $finalbuyprice = 0;

    $sellandreturndetailData = $mySellandruternbilldetailEx->queryWithDateAndConditionsTypeAndProductIdExt($startDate, $endDate, 1, $ProductIdselected);


    //print_r($sellandreturndetailData);
    $buyPriceType = $_POST["buyPriceType"];
    foreach ($sellandreturndetailData as $sellandreturndetail) {
        $quantity = $sellandreturndetail->sellbilldetailquantity;
        $price = $sellandreturndetail->sellbilldetailprice;
        $totalPrice = $sellandreturndetail->sellbilldetailtotalprice;
        $discountValue = $sellandreturndetail->discountvalue;
        $productunitId = $sellandreturndetail->productunitid;
        //$sellbillTotalBill=$sellbillData->sellbillprice;
        $sellbillDiscount = $sellandreturndetail->sellbilldiscount; //محتاجة تتغير
        $totalPrice = $sellandreturndetail->sellbilldetailtotalprice;
        $discountvalue = $sellandreturndetail->discountvalue;
        //$buyprice = $sellandreturndetail->buyprice;
//        if ($buyPriceType == "last") {
//            $buyPrice = (float) $sellandreturndetail->lastbuyprice;
//        } else {
//            $buyPrice = (float) $sellandreturndetail->meanbuyprice;
//        }

        switch ($buyPriceType) {
            case "first":
                $buyPrice = (float) $sellbilldetail->buyprice;
                break;
            case "last":
                $buyPrice = (float) $sellbilldetail->lastbuyprice;
                break;
            case "mean":
                $buyPrice = (float) $sellbilldetail->meanbuyprice;
                break;
            case "last_discount":
                $buyPrice = (float) $sellbilldetail->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyPrice = (float) $sellbilldetail->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyPrice = (float) $sellbilldetail->generalPrice;
                break;
            case "tax":
                $buyprice = (float) $sellbilldetail->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $buyprice = (float) $sellbilldetail->meanbuyprice_withTax;
                break;
            default:
                $buyPrice = (float) $sellbilldetail->meanbuyprice;
                break;
        }
        //print_r("<br>sellbillDiscount".$sellbillDiscount."<br>");
        //print_r("<br>price".$price."<br>");
        //print_r("<br>discountvalue".$discountvalue."<br>");
        //خصم نسبه
        /* if($sellbillDiscountType == 2)
          {
          $sellbillDiscount = ($sellbillDiscount / 100) * $sellbillTotalBill;
          }
         */
        $totalPriceBeforeDiscount = $price * $quantity;

        $productnumber = $myProductunitEx->getProductNumber($productunitId);

        $quantityUnit += ($quantity * $productnumber);

        if ($sellbillTotalBill == 0) {
            $sellbillTotalBill = 1;
        }
        //third Step قيمة الخصم للمنتجات
        $allbuyprice = $quantity * $buyprice;
        $finalbuyprice += $allbuyprice;
        $thirdStep = ($totalPrice / $sellbillTotalBill);
        //print_r("<br>totalPriceBeforeDiscount".$totalPriceBeforeDiscount."<br>");
        $ReturnSellPriceForOneProduct = $totalPriceBeforeDiscount - ($discountValue * $quantity);
        //$ReturnSellPriceForOneProduct = $totalPriceBeforeDiscount - ($discountValue + $thirdStep);
        //print_r("--------------<br>ReturnSellPriceForOneProduct".$ReturnSellPriceForOneProduct."<br>-------");
        $ReturnSellPrice += $ReturnSellPriceForOneProduct;
    }
    //print_r("<br>".$ReturnSellPrice."<br>");

    return array($ReturnSellPrice, $quantityUnit, $finalbuyprice);
}

function getTotalBuyPriceByDateAndProductId($startDate, $endDate, $ProductIdselected, $overAllAveragePrice) {
    global $mySellbilldetailEx;
    global $myProductunitRecord;
    global $mySellbillRecord;
    global $myProductRecord;
    global $myProductunitEx;

    $sellPrice = 0;
    $quantityUnit = 0;

    $sellbilldetailData = $mySellbilldetailEx->queryWithDateAndConditionsAndProductIdExt($startDate, $endDate, $ProductIdselected);


    $buyPriceType = $_POST["buyPriceType"];
    foreach ($sellbilldetailData as $sellbilldetail) {
        $quantity = $sellbilldetail->sellbilldetailquantity;
        $price = $sellbilldetail->sellbilldetailprice;
        $totalPrice = $sellbilldetail->sellbilldetailtotalprice;
        $discountValue = $sellbilldetail->discountvalue;
        $productunitId = $sellbilldetail->productunitid;
        //$buyPrice = $sellbilldetail->buyprice;
//        if ($buyPriceType == "last") {
//            $buyPrice = (float) $sellbilldetail->lastbuyprice;
//        } else {
//            $buyPrice = (float) $sellbilldetail->meanbuyprice;
//        }

        switch ($buyPriceType) {
            case "first":
                $buyPrice = (float) $sellbilldetail->buyprice;
                break;
            case "last":
                $buyPrice = (float) $sellbilldetail->lastbuyprice;
                break;
            case "mean":
                $buyPrice = (float) $sellbilldetail->meanbuyprice;
                break;
            case "last_discount":
                $buyPrice = (float) $sellbilldetail->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyPrice = (float) $sellbilldetail->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyPrice = (float) $overAllAveragePrice;
                break;
            case "tax":
                $buyprice = (float) $sellbilldetail->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $buyprice = (float) $sellbilldetail->meanbuyprice_withTax;
                break;
        }
        $buyDiscount = $sellbilldetail->buydiscount;
        $buyDiscountType = $sellbilldetail->buydiscounttype;

        $productnumber = $myProductunitEx->getProductNumber($productunitId);

        $productBuyPrice = $buyPrice;
        if ($buyDiscount > 0 && $buyDiscountType == 0) {
            $productBuyPrice = $buyPrice - $buyDiscount;
        } elseif ($buyDiscount > 0 && $buyDiscountType == 1) {
            $productBuyPrice = $buyPrice - (($buyDiscount / 100) * $buyPrice);
        }

        $productBuyPrice = $productBuyPrice * $productnumber * $quantity;

        $quantityUnit += ($quantity * $productnumber);

        $sellPrice += $productBuyPrice;
    }



    return array($sellPrice, $quantityUnit);
}

function getTotalAditionalBuyPriceByDateAndProductId($startDate, $endDate, $ProductIdselected, $overAllAveragePrice) {
    global $mySellandruternbilldetailEx;
    global $mySellbillandruternRecord;
    global $myProductunitRecord;
    global $myProductRecord;
    global $myProductunitEx;

    $sellPrice = 0;
    $quantityUnit = 0;

    $sellandreturndetailData = $mySellandruternbilldetailEx->queryWithDateAndConditionsTypeAndProductIdExt($startDate, $endDate, 0, $ProductIdselected);
    $buyPriceType = $_POST["buyPriceType"];
    foreach ($sellandreturndetailData as $sellandreturndetail) {
        $quantity = $sellandreturndetail->sellbilldetailquantity;
        $price = $sellandreturndetail->sellbilldetailprice;
        $totalPrice = $sellandreturndetail->sellbilldetailtotalprice;
        $discountValue = $sellandreturndetail->discountvalue;
        $productunitId = $sellandreturndetail->productunitid;
        //$buyPrice = $sellandreturndetail->buyprice;
//        if ($buyPriceType == "last") {
//            $buyPrice = (float) $sellandreturndetail->lastbuyprice;
//        } else {
//            $buyPrice = (float) $sellandreturndetail->meanbuyprice;
//        }

        switch ($buyPriceType) {
            case "first":
                $buyPrice = (float) $sellandreturndetail->buyprice;
                break;
            case "last":
                $buyPrice = (float) $sellandreturndetail->lastbuyprice;
                break;
            case "mean":
                $buyPrice = (float) $sellandreturndetail->meanbuyprice;
                break;
            case "last_discount":
                $buyPrice = (float) $sellandreturndetail->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyPrice = (float) $sellandreturndetail->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyPrice = (float) $overAllAveragePrice;
                break;
            case "tax":
                $buyprice = (float) $sellandreturndetail->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $buyprice = (float) $sellandreturndetail->meanbuyprice_withTax;
                break;
        }
        $buyDiscount = $sellandreturndetail->buydiscount;
        $buyDiscountType = $sellandreturndetail->buydiscounttype;

        $productnumber = $myProductunitEx->getProductNumber($productunitId);
        $discountPrice = 0;
        $productBuyPrice = $buyPrice;
        if ($buyDiscount > 0 && $buyDiscountType == 0) {
            $discountPrice = $buyDiscount;
            $productBuyPrice = $buyPrice - $discountPrice;
        } elseif ($buyDiscount > 0 && $buyDiscountType == 1) {
            $discountPrice = (($buyDiscount / 100) * $buyPrice);
            $productBuyPrice = $buyPrice - $discountPrice;
        }

        $productBuyPrice = $productBuyPrice * $productnumber * $quantity;

        $quantityUnit += ($quantity * $productnumber);

        $sellPrice += $productBuyPrice;
    }



    return array($sellPrice, $quantityUnit, $discountPrice);
}

function getTotalAditionalReturnBuyPriceByDateAndProductId($startDate, $endDate, $ProductIdselected) {
    global $mySellandruternbilldetailEx;
    global $mySellbillandruternRecord;
    global $myProductunitRecord;
    global $myProductRecord;
    global $myProductunitEx;

    $sellPrice = 0;
    $quantityUnit = 0;

    $sellandreturndetailData = $mySellandruternbilldetailEx->queryWithDateAndConditionsTypeAndProductIdExt($startDate, $endDate, 1, $ProductIdselected);
    $buyPriceType = $_POST["buyPriceType"];
    foreach ($sellandreturndetailData as $sellandreturndetail) {
        $quantity = $sellandreturndetail->sellbilldetailquantity;
        $price = $sellandreturndetail->sellbilldetailprice;
        $totalPrice = $sellandreturndetail->sellbilldetailtotalprice;
        $discountValue = $sellandreturndetail->discountvalue;
        $productunitId = $sellandreturndetail->productunitid;
        //$buyPrice = $sellandreturndetail->buyprice;
//        if ($buyPriceType == "last") {
//            $buyPrice = (float) $sellandreturndetail->lastbuyprice;
//        } else {
//            $buyPrice = (float) $sellandreturndetail->meanbuyprice;
//        }

        switch ($buyPriceType) {
            case "first":
                $buyPrice = (float) $sellandreturndetail->buyprice;
                break;
            case "last":
                $buyPrice = (float) $sellandreturndetail->lastbuyprice;
                break;
            case "mean":
                $buyPrice = (float) $sellandreturndetail->meanbuyprice;
                break;
            case "last_discount":
                $buyPrice = (float) $sellandreturndetail->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyPrice = (float) $sellandreturndetail->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyPrice = (float) $sellandreturndetail->generalPrice;
                break;
            case "tax":
                $buyprice = (float) $sellandreturndetail->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $buyprice = (float) $sellandreturndetail->meanbuyprice_withTax;
                break;
        }
        $buyDiscount = $sellandreturndetail->buydiscount;
        $buyDiscountType = $sellandreturndetail->buydiscounttype;

        $productnumber = $myProductunitEx->getProductNumber($productunitId);

        $productBuyPrice = $buyPrice;
        if ($buyDiscount > 0 && $buyDiscountType == 0) {
            $productBuyPrice = $buyPrice - $buyDiscount;
        } elseif ($buyDiscount > 0 && $buyDiscountType == 1) {
            $productBuyPrice = $buyPrice - (($buyDiscount / 100) * $buyPrice);
        }

        $productBuyPrice = $productBuyPrice * $productnumber * $quantity;


        $quantityUnit += ($quantity * $productnumber);

        $sellPrice += $productBuyPrice;
    }
    return array($sellPrice, $quantityUnit);
}

function getTotalReturnBuyPriceByDateAndProductId($startDate, $endDate, $ProductIdselected, $overAllAveragePrice) {
    global $myReturnsellbilldetailEx;
    global $myReturnsellbillRecord;
    global $myProductunitRecord;
    global $myProductRecord;
    global $myProductunitEx;

    $sellPrice = 0;
    $quantityUnit = 0;


    $returnsellbilldetailData = $myReturnsellbilldetailEx->queryWithDateAndConditionsAndProductIdExt($startDate, $endDate, $ProductIdselected);

    $buyPriceType = $_POST["buyPriceType"];
    foreach ($returnsellbilldetailData as $returnsellbilldetail) {
        $quantity = $returnsellbilldetail->returnsellbilldetailquantity;
        $price = $returnsellbilldetail->returnsellbilldetailprice;
        $totalPrice = $returnsellbilldetail->returnsellbilldetailtotalprice;
        $discountValue = $returnsellbilldetail->discountvalue;
        $productunitId = $returnsellbilldetail->productunitid;
        //$buyPrice = $returnsellbilldetail->buyprice;
//        if ($buyPriceType == "last") {
//            $buyPrice = (float) $returnsellbilldetail->lastbuyprice;
//        } else {
//            $buyPrice = (float) $returnsellbilldetail->meanbuyprice;
//        }

        switch ($buyPriceType) {
            case "first":
                $buyPrice = (float) $returnsellbilldetail->buyprice;
                break;
            case "last":
                $buyPrice = (float) $returnsellbilldetail->lastbuyprice;
                break;
            case "mean":
                $buyPrice = (float) $returnsellbilldetail->meanbuyprice;
                break;
            case "last_discount":
                $buyPrice = (float) $returnsellbilldetail->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyPrice = (float) $returnsellbilldetail->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyPrice = (float) $overAllAveragePrice;
                break;
            case "tax":
                $buyprice = (float) $returnsellbilldetail->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $buyprice = (float) $returnsellbilldetail->meanbuyprice_withTax;
                break;
        }
        $buyDiscount = $returnsellbilldetail->buydiscount;
        $buyDiscountType = $returnsellbilldetail->buydiscounttype;

        $productnumber = $myProductunitEx->getProductNumber($productunitId);

        $productBuyPrice = $buyPrice;
        if ($buyDiscount > 0 && $buyDiscountType == 0) {
            $productBuyPrice = $buyPrice - $buyDiscount;
        } elseif ($buyDiscount > 0 && $buyDiscountType == 1) {
            $productBuyPrice = $buyPrice - (($buyDiscount / 100) * $buyPrice);
        }

        $productBuyPrice = $productBuyPrice * $productnumber * $quantity;

        $quantityUnit += ($quantity * $productnumber);

        $sellPrice += $productBuyPrice;
    }
    return array($sellPrice, $quantityUnit);
}

// show the form by date
/* 	function getTotalSellPriceByDateAndProductId($startDate,$endDate, $ProductIdselected)
  {
  global $mySellbilldetailEx;
  global $myProductunitRecord;
  global $mySellbillRecord;
  global $myProductRecord;
  global $myProductEx;
  global $myProductunitEx;

  $sellPrice= 0;
  $quantityUnit=0;
  $finalbuypric=0;
  $sellbilldetailData=$mySellbilldetailEx->queryWithDateAndConditionsAndProductIdExt($startDate,$endDate, $ProductIdselected);

  foreach($sellbilldetailData as $sellbilldetail)
  {
  $quantity = $sellbilldetail->sellbilldetailquantity;
  $price = $sellbilldetail->sellbilldetailprice;
  $totalPrice = $sellbilldetail->sellbilldetailtotalprice;
  $discountValue = $sellbilldetail->discountvalue;
  $productunitId = $sellbilldetail->productunitid;
  $sellbillTotalBill = $sellbilldetail->sellbilltotalbill;
  $sellbillDiscount = $sellbilldetail->sellbilldiscount;
  $sellbillDiscountType = $sellbilldetail->sellbilldiscounttype;
  $buyprice = $sellbilldetail->buyprice;

  if($sellbillDiscountType == 2)
  {
  $sellbillDiscount = ($sellbillDiscount / 100) * $sellbillTotalBill;
  }

  $totalPriceBeforeDiscount = $price * $quantity; //product price before discount

  $productnumber = $myProductunitEx->getProductNumber($productunitId);

  $quantityUnit += ($quantity * $productnumber);//الكمية * عدد القطع في وحدة القياس

  //first Step قيمة خصم المنتج على الوحدة
  //$firstStep = $discountValue;

  //second Stepقيمة المنتج من الخصم على المنتج
  //$secondStep = $totalPrice / $sellbillTotalBill;

  if($sellbillTotalBill == 0)
  {
  $sellbillTotalBill = 1;
  }
  //third Step قيمة الخصم للمنتجات
  $thirdStep = ($totalPrice / $sellbillTotalBill) * $sellbillDiscount;

  //fourth Step  قيمة خصم الفاتورة للوحدة
  //$fourthStep = $thirdStep;

  //$sellPriceForOneProduct= $totalPriceBeforeDiscount - ($firstStep + $fourthStep);
  $allbuyprice=$buyprice*$quantity;
  $finalbuypric+=$allbuyprice;
  $sellPriceForOneProduct= $totalPriceBeforeDiscount - ($discountValue + $thirdStep);
  $sellPrice += $sellPriceForOneProduct;
  }



  return array($sellPrice, $quantityUnit,$finalbuypric);
  }

  // show the form by date
  function getTotalAditionalSellPriceByDateAndProductId($startDate,$endDate, $ProductIdselected)
  {
  global $mySellandruternbilldetailEx;
  global $mySellbillandruternRecord;
  global $myProductunitRecord;
  global $myProductRecord;
  global $myProductunitEx;

  $sellPrice= 0;
  $quantityUnit = 0;
  $finalallbuyprice=0;

  $sellandreturndetailData=$mySellandruternbilldetailEx->queryWithDateAndConditionsTypeAndProductIdExt($startDate,$endDate,0, $ProductIdselected);

  foreach($sellandreturndetailData as $sellandreturndetail)
  {
  $quantity=$sellandreturndetail->sellbilldetailquantity;
  $price=$sellandreturndetail->sellbilldetailprice;
  $totalPrice=$sellandreturndetail->sellbilldetailtotalprice;
  $discountValue=$sellandreturndetail->discountvalue;
  $productunitId=$sellandreturndetail->productunitid;
  $sellbillTotalBill=$sellandreturndetail->sellbillprice;
  $sellbillDiscount=$sellandreturndetail->sellbilldiscount; //محتاجة تتغير
  $sellbillDiscountType=$sellandreturndetail->sellbilldiscounttype;
  $buyprice=$sellandreturndetail->buyprice;

  if($sellbillDiscountType == 2)
  {
  $sellbillDiscount = ($sellbillDiscount / 100) * $sellbillTotalBill;
  }

  $totalPriceBeforeDiscount = $price * $quantity;

  $productnumber = $myProductunitEx->getProductNumber($productunitId);

  $quantityUnit += ($quantity * $productnumber);

  //third Step قيمة الخصم للمنتجات
  $thirdStep = ($totalPrice / $sellbillTotalBill) * $sellbillDiscount;

  $sellPriceForOneProduct = $totalPriceBeforeDiscount - (($discountValue * $quantity)+$sellbillDiscount);
  $sellPrice += $sellPriceForOneProduct;

  $allbuyprice=$quantity*$buyprice;
  $finalallbuyprice+=$allbuyprice;
  }
  return array($sellPrice, $quantityUnit,$finalallbuyprice);
  }

  function getTotalReturnSellPriceByDateAndProductId($startDate,$endDate, $ProductIdselected)
  {
  global $myReturnsellbilldetailEx;
  global $myReturnsellbillRecord;
  global $myProductunitRecord;
  global $myProductRecord;
  global $myProductunitEx;

  $ReturnSellPrice= 0;
  $quantityUnit=0;
  $finalallbuyprice=0;

  $returnsellbilldetailData=$myReturnsellbilldetailEx->queryWithDateAndConditionsAndProductIdExt($startDate,$endDate, $ProductIdselected);

  foreach($returnsellbilldetailData as $returnsellbilldetail)
  {


  $quantity=$returnsellbilldetail->returnsellbilldetailquantity;
  $price=$returnsellbilldetail->returnsellbilldetailprice;
  $totalPrice=$returnsellbilldetail->returnsellbilldetailtotalprice;
  $discountValue=$returnsellbilldetail->discountvalue;
  $productunitId=$returnsellbilldetail->productunitid;
  $sellbillTotalBill=$returnsellbilldetail->returnsellbilltotalbill;
  $sellbillDiscount=$returnsellbilldetail->returnsellbilldiscount;
  $sellbillDiscountType=$returnsellbilldetail->returnsellbilldiscounttype;
  $buyprice=$returnsellbilldetail->buyprice;

  if($sellbillDiscountType == 2)
  {
  $sellbillDiscount = ($sellbillDiscount / 100) * $sellbillTotalBill;
  }

  $totalPriceBeforeDiscount = $price * $quantity;

  $productnumber = $myProductunitEx->getProductNumber($productunitId);

  $quantityUnit += ($quantity * $productnumber);

  //third Step قيمة الخصم للمنتجات
  $thirdStep = ($totalPrice / $sellbillTotalBill) * $sellbillDiscount;


  $ReturnSellPriceForOneProduct= $totalPriceBeforeDiscount - ( ($discountValue * $quantity)+$sellbillDiscount);

  //print_r($ReturnSellPriceForOneProduct.'xxx');
  $ReturnSellPrice += $ReturnSellPriceForOneProduct;
  $allbuyprice=$quantity*$buyprice;
  $finalallbuyprice+=$allbuyprice;
  }
  return array($ReturnSellPrice, $quantityUnit,$finalallbuyprice);
  }

  // show the form by date
  function getTotalAditionalReturnSellPriceByDateAndProductId($startDate,$endDate, $ProductIdselected)
  {
  global $mySellandruternbilldetailEx;
  global $mySellbillandruternRecord;
  global $myProductunitRecord;
  global $myProductRecord;
  global $myProductunitEx;

  $ReturnSellPrice= 0;
  $quantityUnit =0;
  $finalallbuyprice=0;

  $sellandreturndetailData=$mySellandruternbilldetailEx->queryWithDateAndConditionsTypeAndProductIdExt($startDate,$endDate,1, $ProductIdselected);

  foreach($sellandreturndetailData as $sellandreturndetail)
  {
  $quantity=$sellandreturndetail->sellbilldetailquantity;
  $price=$sellandreturndetail->sellbilldetailprice;
  $totalPrice=$sellandreturndetail->sellbilldetailtotalprice;
  $discountValue=$sellandreturndetail->discountvalue;
  $productunitId=$sellandreturndetail->productunitid;
  $sellbillTotalBill=$sellandreturndetail->sellbillprice;
  $sellbillDiscount=$sellandreturndetail->sellbilldiscount; //محتاجة تتغير
  $sellbillDiscountType=$sellandreturndetail->sellbilldiscounttype;
  $buyprice=$sellandreturndetail->buyprice;

  if($sellbillDiscountType == 2)
  {
  $sellbillDiscount = ($sellbillDiscount / 100) * $sellbillTotalBill;
  }

  $totalPriceBeforeDiscount = $price * $quantity;

  $productnumber = $myProductunitEx->getProductNumber($productunitId);

  $quantityUnit += ($quantity * $productnumber);

  //third Step قيمة الخصم للمنتجات
  $thirdStep = ($totalPrice / $sellbillTotalBill);

  $ReturnSellPriceForOneProduct= $totalPriceBeforeDiscount - (($discountValue * $quantity)+$sellbillDiscount);
  $ReturnSellPrice += $ReturnSellPriceForOneProduct;

  $allbuyprice=$quantity*$buyprice;
  $finalallbuyprice+=$allbuyprice;
  }
  return array($ReturnSellPrice, $quantityUnit,$finalallbuyprice);
  }

  function getTotalBuyPriceByDateAndProductId($startDate,$endDate, $ProductIdselected)
  {
  global $mySellbilldetailEx;
  global $myProductunitRecord;
  global $mySellbillRecord;
  global $myProductRecord;
  global $myProductunitEx;

  $sellPrice= 0;
  $quantityUnit=0;

  $sellbilldetailData = $mySellbilldetailEx->queryWithDateAndConditionsAndProductIdExt($startDate,$endDate, $ProductIdselected);
  //print_r($sellbilldetailData);
  foreach($sellbilldetailData as $sellbilldetail)
  {
  $quantity=$sellbilldetail->sellbilldetailquantity;
  $price=$sellbilldetail->sellbilldetailprice;
  $totalPrice=$sellbilldetail->sellbilldetailtotalprice;
  $discountValue=$sellbilldetail->discountvalue;
  $productunitId=$sellbilldetail->productunitid;
  $buyPrice = $sellbilldetail->buyprice;
  $buyDiscount=$sellbilldetail->buydiscount;
  $buyDiscountType=$sellbilldetail->buydiscounttype;
  //print("buyPrice: ".$buyPrice."<br>");
  $productnumber = $myProductunitEx->getProductNumber($productunitId);

  $productBuyPrice = $buyPrice;
  if($buyDiscount > 0 && $buyDiscountType == 0)
  {
  $productBuyPrice= $buyPrice - $buyDiscount;
  }
  elseif($buyDiscount > 0 && $buyDiscountType == 1)
  {
  $productBuyPrice= $buyPrice - (($buyDiscount/100)*$buyPrice);
  }

  $productBuyPrice = $productBuyPrice * $productnumber * $quantity;

  $quantityUnit += ($quantity * $productnumber);

  $sellPrice += $productBuyPrice;
  }
  return array($sellPrice, $quantityUnit);
  }

  function getTotalAditionalBuyPriceByDateAndProductId($startDate,$endDate, $ProductIdselected)
  {
  global $mySellandruternbilldetailEx;
  global $mySellbillandruternRecord;
  global $myProductunitRecord;
  global $myProductRecord;
  global $myProductunitEx;

  $sellPrice= 0;
  $quantityUnit=0;

  $sellandreturndetailData=$mySellandruternbilldetailEx->queryWithDateAndConditionsTypeAndProductIdExt($startDate,$endDate,0, $ProductIdselected);

  foreach($sellandreturndetailData as $sellandreturndetail)
  {
  $quantity=$sellandreturndetail->sellbilldetailquantity;
  $price=$sellandreturndetail->sellbilldetailprice;
  $totalPrice=$sellandreturndetail->sellbilldetailtotalprice;
  $discountValue=$sellandreturndetail->discountvalue;
  $productunitId=$sellandreturndetail->productunitid;
  $buyPrice=$sellandreturndetail->buyprice;
  $buyDiscount=$sellandreturndetail->buydiscount;
  $buyDiscountType=$sellandreturndetail->buydiscounttype;

  $productnumber = $myProductunitEx->getProductNumber($productunitId);

  $productBuyPrice = $buyPrice;
  if($buyDiscount > 0 && $buyDiscountType == 0)
  {
  $productBuyPrice = $buyPrice - $buyDiscount;
  }
  elseif($buyDiscount > 0 && $buyDiscountType == 1)
  {
  $productBuyPrice = $buyPrice - (($buyDiscount/100) * $buyPrice);
  }

  $productBuyPrice = $productBuyPrice * $productnumber * $quantity;

  $quantityUnit += ($quantity * $productnumber);

  $sellPrice += $productBuyPrice;
  }
  return array($sellPrice, $quantityUnit);
  }

  function getTotalAditionalReturnBuyPriceByDateAndProductId($startDate,$endDate, $ProductIdselected)
  {
  global $mySellandruternbilldetailEx;
  global $mySellbillandruternRecord;
  global $myProductunitRecord;
  global $myProductRecord;
  global $myProductunitEx;

  $sellPrice= 0;
  $quantityUnit=0;

  $sellandreturndetailData=$mySellandruternbilldetailEx->queryWithDateAndConditionsTypeAndProductIdExt($startDate,$endDate,1, $ProductIdselected);

  foreach($sellandreturndetailData as $sellandreturndetail)
  {
  $quantity=$sellandreturndetail->sellbilldetailquantity;
  $price=$sellandreturndetail->sellbilldetailprice;
  $totalPrice=$sellandreturndetail->sellbilldetailtotalprice;
  $discountValue=$sellandreturndetail->discountvalue;
  $productunitId=$sellandreturndetail->productunitid;
  $buyPrice=$sellandreturndetail->buyprice;
  $buyDiscount=$sellandreturndetail->buydiscount;
  $buyDiscountType=$sellandreturndetail->buydiscounttype;

  $productnumber = $myProductunitEx->getProductNumber($productunitId);

  $productBuyPrice = $buyPrice;
  if($buyDiscount > 0 && $buyDiscountType == 0)
  {
  $productBuyPrice = $buyPrice - $buyDiscount;
  }
  elseif($buyDiscount > 0 && $buyDiscountType == 1)
  {
  $productBuyPrice = $buyPrice - (($buyDiscount/100) * $buyPrice);
  }

  $productBuyPrice = $productBuyPrice * $productnumber * $quantity;

  $quantityUnit += ($quantity * $productnumber);

  $sellPrice += $productBuyPrice;
  }
  return array($sellPrice, $quantityUnit);
  }


  function getTotalReturnBuyPriceByDateAndProductId($startDate,$endDate, $ProductIdselected)
  {
  global $myReturnsellbilldetailEx;
  global $myReturnsellbillRecord;
  global $myProductunitRecord;
  global $myProductRecord;
  global $myProductunitEx;

  $sellPrice= 0;
  $quantityUnit=0;

  $returnsellbilldetailData=$myReturnsellbilldetailEx->queryWithDateAndConditionsAndProductIdExt($startDate,$endDate, $ProductIdselected);

  foreach($returnsellbilldetailData as $returnsellbilldetail)
  {
  $quantity=$returnsellbilldetail->returnsellbilldetailquantity;
  $price=$returnsellbilldetail->returnsellbilldetailprice;
  $totalPrice=$returnsellbilldetail->returnsellbilldetailtotalprice;
  $discountValue=$returnsellbilldetail->discountvalue;
  $productunitId=$returnsellbilldetail->productunitid;
  $buyPrice=$returnsellbilldetail->buyprice;
  $buyDiscount=$returnsellbilldetail->buydiscount;
  $buyDiscountType=$returnsellbilldetail->buydiscounttype;

  $productnumber = $myProductunitEx->getProductNumber($productunitId);

  $productBuyPrice = $buyPrice;
  if($buyDiscount > 0 && $buyDiscountType == 0)
  {
  $productBuyPrice = $buyPrice - $buyDiscount;
  }
  elseif($buyDiscount > 0 && $buyDiscountType == 1)
  {
  $productBuyPrice = $buyPrice - (($buyDiscount/100) * $buyPrice);
  }

  $productBuyPrice = $productBuyPrice * $productnumber * $quantity;

  $quantityUnitForOneProduct=$quantity * $productnumber;
  $quantityUnit += ($quantity * $productnumber);

  $sellPrice += $productBuyPrice;
  }
  return array($sellPrice, $quantityUnit);
  }

 */
// select from Product tbl
function loadProduct() {
    global $myProductEx;

    // select all data from producttbl
    $productData = $myProductEx->queryWithCoditionsAndCatConditions();

    foreach ($productData as $product) {
        $productcatName;
        $product->productName = loadProductCatNameById($product->productCatId, $productcatName, 1) . "/" . $product->productName;
    }
    return $productData;
}

// select from Product tbl
function loadProductCatNameById($productCatId, $productcatName, $itr) {
    global $myProductcatRecord;

    $productcatNamex = $productcatName;
    // select all data from producttbl
    $productcatData = $myProductcatRecord->load($productCatId);

    if (count($productcatData) > 0) {
        if ($itr == 1) {
            $productcatNamex = $productcatData->productCatName;
        } elseif ($itr == 2) {
            $productcatNamex = $productcatData->productCatName . "/" . $productcatNamex;
        }

        if ($productcatData->productCatParent != 0) {
            return loadProductCatNameById($productcatData->productCatParent, $productcatNamex, 2);
        }
    }
    return $productcatNamex;
}

function loadProductCatById($productCatId) {
    global $myProductcatRecord;
    $productCatSearchData = $myProductcatRecord->load($productCatId);
    return $productCatSearchData;
}

function getTotalOpticByDateAndProductId($startDate, $endDate, $ProductIdselected) {
    global $billsProductsEX;

    $sellPrice = 0;
    $quantityUnit = 0;
    $finalbuypric = 0;
    $sellOpticData = $billsProductsEX->queryWithDateAndConditionsAndProductIdExt($startDate, $endDate, $ProductIdselected);
    $buyPriceType = $_POST["buyPriceType"];
    foreach ($sellOpticData as $sellbilldetail) {
        $quantity = $sellbilldetail->productno;
        $price = $sellbilldetail->productprice;
        $totalPrice = $sellbilldetail->producttotalprice;
        $discountValue = $sellbilldetail->discountvalue;
        $sellbillTotalBill = $sellbilldetail->netbillvalue;
        $sellbillDiscount = $sellbilldetail->discountvalue;
        $sellbillDiscountType = $sellbilldetail->discounttype;
        //$buyprice = $sellbilldetail->productBuyPrice;
//        if ($buyPriceType == "last") {
//            $buyPrice = (float) $sellbilldetail->lastbuyprice;
//        } else {
//            $buyPrice = (float) $sellbilldetail->meanbuyprice;
//        }

        switch ($buyPriceType) {
            case "first":
                $buyprice = (float) $sellbilldetail->buyprice;
                break;
            case "last":
                $buyprice = (float) $sellbilldetail->lastbuyprice;
                break;
            case "mean":
                $buyprice = (float) $sellbilldetail->meanbuyprice;
                break;
            case "last_discount":
                $buyprice = (float) $sellbilldetail->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyprice = (float) $sellbilldetail->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyprice = (float) $sellbilldetail->generalPrice;
                break;
        }

        if ($sellbillDiscountType == 2) {
            $sellbillDiscount = ($sellbillDiscount / 100) * $sellbillTotalBill;
        }

        $totalPriceBeforeDiscount = $price * $quantity; //product price before discount

        $quantityUnit += $quantity; //الكمية * عدد القطع في وحدة القياس


        if ($sellbillTotalBill == 0) {
            $sellbillTotalBill = 1;
        }
        //third Step قيمة الخصم للمنتجات
        $thirdStep = ($totalPrice / $sellbillTotalBill) * $sellbillDiscount;

        //fourth Step  قيمة خصم الفاتورة للوحدة
        //$fourthStep = $thirdStep;
        //$sellPriceForOneProduct= $totalPriceBeforeDiscount - ($firstStep + $fourthStep);
        $allbuyprice = $buyprice * $quantity;
        $finalbuypric += $allbuyprice;
        $discountPrice = $discountValue + $thirdStep;
        $sellPriceForOneProduct = $totalPriceBeforeDiscount - $discountPrice;
        $sellPrice += $sellPriceForOneProduct;
    }



    return array($sellPrice, $quantityUnit, $finalbuypric, $discountPrice);
}

function getTotalReturnOpticByDateAndProductId($startDate, $endDate, $ProductIdselected) {
    global $billsReturnProductsEX;

    $ReturnSellPrice = 0;
    $quantityUnit = 0;
    $finalbuyprice = 0;

    $returnOpticData = $billsReturnProductsEX->queryWithDateAndConditionsAndProductIdExt($startDate, $endDate, $ProductIdselected);

    $buyPriceType = $_POST["buyPriceType"];
    foreach ($returnOpticData as $returnsellbilldetail) {
        $quantity = $returnsellbilldetail->productno;
        $price = $returnsellbilldetail->productprice;
        $totalPrice = $returnsellbilldetail->producttotalprice;
        $sellbillTotalBill = $returnsellbilldetail->returnedprice;
        //$buyprice = $returnsellbilldetail->productBuyPrice;
//        if ($buyPriceType == "last") {
//            $buyPrice = (float) $returnsellbilldetail->lastbuyprice;
//        } else {
//            $buyPrice = (float) $returnsellbilldetail->meanbuyprice;
//        }


        switch ($buyPriceType) {
            case "first":
                $buyprice = (float) $returnsellbilldetail->buyprice;
                break;
            case "last":
                $buyprice = (float) $returnsellbilldetail->lastbuyprice;
                break;
            case "mean":
                $buyprice = (float) $returnsellbilldetail->meanbuyprice;
                break;
            case "last_discount":
                $buyprice = (float) $returnsellbilldetail->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyprice = (float) $returnsellbilldetail->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyprice = (float) $returnsellbilldetail->generalPrice;
                break;
        }
        $totalPriceBeforeDiscount = $price * $quantity;

        $quantityUnit += $quantity;

        if ($sellbillTotalBill == 0) {
            $sellbillTotalBill = 1;
        }
        //third Step قيمة الخصم للمنتجات
        $thirdStep = ($totalPrice / $sellbillTotalBill);


        $allbuyprice = $quantity * $buyprice;

        //print_r("<br>buyprice".$buyprice);
        //print_r("<br>quantity".$quantity);
        $finalbuyprice += $allbuyprice;
        $ReturnSellPriceForOneProduct = $totalPriceBeforeDiscount - $thirdStep;
        $ReturnSellPrice += $ReturnSellPriceForOneProduct;
    }

//print($ReturnSellPrice."ReturnSellPrice<br>");

    return array($ReturnSellPrice, $quantityUnit, $finalbuyprice);
}

?>