<?php

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

// get the config file
include_once("../public/config.php");

//here the db files that include in the file
include("../public/include_dao.php");


//here the db files that include in the file
include("reportfunctions.php");

//user
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.class.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');
//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');
//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');
//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');
//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');
//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');


//Bill
require_once('../models/dao/BillsDAO.class.php');
require_once('../models/dto/Bill.class.php');
require_once('../models/mysql/BillsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsMySqlExtDAO.class.php');
//Billsproduct
require_once('../models/dao/BillsproductsDAO.class.php');
require_once('../models/dto/Billsproduct.class.php');
require_once('../models/mysql/BillsproductsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsproductsMySqlExtDAO.class.php');
//
require_once('../models/dao/BillsreturnDAO.class.php');
require_once('../models/dto/Billsreturn.class.php');
require_once('../models/mysql/BillsreturnMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsreturnMySqlExtDAO.class.php');

require_once('../models/dao/BillsreturnproductsDAO.class.php');
require_once('../models/dto/Billsreturnproduct.class.php');
require_once('../models/mysql/BillsreturnproductsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsreturnproductsMySqlExtDAO.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');

//Client
require_once('../models/dao/ClientDAO.class.php');
require_once('../models/dto/Client.class.php');
require_once('../models/mysql/ClientMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientMySqlExtDAO.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');

$do = $_GET['do'];

/* ======================

  Controller Name :- storedetailCTRL تقرير مخزون اول مدة

  OPERTATION in Controller

  1-load save data
  2-display show form

  ======================== */

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

//here goes the instances and general variables
//user
$user = new User();
$userDAO = new UserMySqlDAO();
$userEX = new UserMySqlExtDAO();

//Sellbill
$sellBill = new Sellbill();
$sellBillDAO = new SellbillMySqlDAO();
$sellBillEX = new SellbillMySqlExtDAO();
//Sellbilldetail
$sellbilldetail = new Sellbilldetail();
$sellbilldetailDAO = new SellbilldetailMySqlDAO();
$sellbilldetailEX = new SellbilldetailMySqlExtDAO();
//Returnsellbill
$returnSellBill = new Returnsellbill();
$returnSellBillDAO = new ReturnsellbillMySqlDAO();
$returnSellBillEX = new ReturnsellbillMySqlExtDAO();
//Returnsellbilldetail
$returnSellBillDetail = new Returnsellbilldetail();
$returnSellBillDetailDAO = new ReturnsellbilldetailMySqlDAO();
$returnSellBillDetailEX = new ReturnsellbilldetailMySqlExtDAO();
//Sellandruternbill
$sellAndRuternBill = new Sellbillandrutern();
$sellAndRuternBillDAO = new SellbillandruternMySqlDAO();
$sellAndRuternBillEX = new SellbillandruternMySqlExtDAO();
//Sellandruternbilldetail
$sellAndRuternBillDetail = new Sellandruternbilldetail();
$sellAndRuternBillDetailDAO = new SellandruternbilldetailMySqlDAO();
$sellAndRuternBillDetailEX = new SellandruternbilldetailMySqlExtDAO();
##################################
//bill
$bills = new Bill();
$billsDAO = new BillsMySqlDAO();
$billsEX = new BillsMySqlExtDAO();

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

//bill
$billsReturn = new Billsreturn();
$billsReturnDAO = new BillsreturnMySqlDAO();
$billsReturnEX = new BillsreturnMySqlExtDAO();

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

///////////////product///////////////
$ProductDAO = new ProductMySqlDAO();
$Product = new Product();
$ProductEX = new ProductMySqlExtDAO();

//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientEX = new ClientMySqlExtDAO();

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


$today = date("Y-m-d");

//check and use the condition that suite this action
if (empty($do)) {
    //here the permission check
    include_once("../public/authentication.php");

    ##########################################################################
    //prepare search tools
    $user = $userDAO->load($_SESSION['userid']);
    $smarty->assign("user", $user);
    if ($user->branchId == 0) {
        $branchData = loadBranch();
        $smarty->assign("branchData", $branchData);
    }
    ###########################################################################
    //search
    $datefrom = filter_input(INPUT_POST, 'datefrom');
    $dateto = filter_input(INPUT_POST, 'dateto');
    $branchId = filter_input(INPUT_POST, 'branchId');
    $discountfrom = filter_input(INPUT_POST, 'discountfrom');
    $discountto = filter_input(INPUT_POST, 'discountto');
    if (!isset($discountfrom) || empty($discountfrom)) {
        $discountfrom = 0;
    }
    if (!isset($discountto) || empty($discountto)) {
        $discountto = 0;
    }
    $searchtype = 0;

    $queryString = " where 1 "; //bills
    $queryStringR = " where 1 "; //billsreturn
    $queryString1 = " where 1 "; //sellbill
    $queryString1R = " where 1 "; //sellbillreturn
    $queryString1SR = " where 1 "; //sellbillandreturn
    ##date
    if (isset($datefrom) && !empty($datefrom) && isset($dateto) && !empty($dateto) && $dateto < $datefrom) {
        $datefrom = $dateto = $today;
        $queryString .= 'and  date(bills.billdate)  = "' . $today . '" ';
        $queryStringR .= 'and  date(billsreturn.`date`)  = "' . $today . '" ';
        $queryString1 .= 'and  sellbill.sellbilldate  = "' . $today . '" ';
        $queryString1R .= 'and  returnsellbill.returnsellbilldate  = "' . $today . '" ';
        $queryString1SR .= 'and  sellbillandrutern.sellbilldate  = "' . $today . '" ';
    } else {
        if (isset($datefrom) && !empty($datefrom)) {
            $queryString .= 'and  date(bills.billdate)  >= "' . $datefrom . '" ';
            $queryStringR .= 'and  date(billsreturn.`date`)  >= "' . $datefrom . '" ';
            $queryString1 .= 'and  sellbill.sellbilldate  >= "' . $datefrom . '" ';
            $queryString1R .= 'and  returnsellbill.returnsellbilldate  >= "' . $datefrom . '" ';
            $queryString1SR .= 'and  sellbillandrutern.sellbilldate  >= "' . $datefrom . '" ';
        }
        if (isset($dateto) && !empty($dateto)) {
            $queryString .= 'and  date(bills.billdate)  <= "' . $dateto . '" ';
            $queryStringR .= 'and   date(billsreturn.`date`)  <= "' . $dateto . '" ';
            $queryString1 .= 'and  sellbill.sellbilldate  <= "' . $dateto . '" ';
            $queryString1R .= 'and  returnsellbill.returnsellbilldate  <= "' . $dateto . '" ';
            $queryString1SR .= 'and  sellbillandrutern.sellbilldate  <= "' . $dateto . '" ';
        }
    }
    ##branch
    if (isset($branchId) && !empty($branchId) && $branchId != -1) {
        if ($user->branchId == 0) {
            $queryString .= 'and  bills.branchid  = ' . $branchId . ' ';
            $queryStringR .= 'and  billsreturn.branchid  = ' . $branchId . ' ';
            //$queryString1 .= 'and  sellbill.sellbilldate  = ' . $branchId . ' ';
        } else {
            $queryString .= 'and  bills.branchid  = ' . $user->branchId . ' ';
            $queryStringR .= 'and  billsreturn.branchid  = ' . $user->branchId . ' ';
            //$queryString1 .= 'and  sellbill.sellbilldate  = ' . $user->branchId . ' ';
        }
    }

    $smarty->assign("branchIdS", $branchId);
    getData($queryString, $queryString1, $queryStringR, $queryString1R, $queryString1SR, $searchtype, $datefrom, $dateto, $discountfrom, $discountto);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $smarty->display("discountreportview/show.html");
}
//here the global templates
$smarty->display("footer.html");

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

function getData($queryString, $queryString1, $queryStringR, $queryString1R, $queryString1SR, $searchtype, $datefrom, $dateto, $discountfrom, $discountto)
{
    global $billsProductsEX;
    global $billsReturnProductsEX;
    global $sellbilldetailEX;
    global $returnSellBillDetailEX;
    global $sellAndRuternBillDetailEX;
    global $ProductDAO;
    global $ProductEX;
    global $billsEX;
    global $billsReturnEX;
    global $sellBillEX;
    global $returnSellBillEX;
    global $sellAndRuternBillEX;
    global $smarty;
    global $billsDAO;
    global $ProgramsettingDAO;

    class billData
    {

        public $billId;
        public $billserial = "";
        public $billno;
        public $totalbill = 0;
        public $noOfpieces = 0;
        public $datetime;
        public $billdiscount = 0;
        public $networkDiscount = 0;
        public $billProfit = 0;
        public $clientName;
        public $sellerName;
        public $userName;
        public $billURL;
        public $billtype;
    }

    $Programsettingdata = $ProgramsettingDAO->load(1);


    $allDataArr = array();
    $totalsObj = new billData();

    ############################################################################
    ##run queries
    $billsData;
    $billsDataReturn;
    $sellBillData;
    $sellBillDataReturn;
    $sellBillDataSellAndReturn;

    $billsData = $billsEX->queryAllGeneral($queryString);
    $billsDataReturn = $billsReturnEX->queryAllGeneral($queryStringR);
    $sellBillData = $sellBillEX->queryAllGeneral_1($queryString1, 0);
    $sellBillDataReturn = $returnSellBillEX->queryAllGeneral_1($queryString1R, 0);
    $sellBillDataSellAndReturn = $sellAndRuternBillEX->queryAllGeneral($queryString1SR);

    $resultsCount = count($billsData) + count($billsDataReturn) + count($sellBillData) + count($sellBillDataReturn) + count($sellBillDataSellAndReturn);
    $smarty->assign("resultsCount", $resultsCount);


    if ($resultsCount > 0) {

        ##مبيعات البصريات
        foreach ($billsData as $value) {
            $myBill = new billData();
            $myBill->billtype = "مبيعات بصريات";
            $myBill->billId = $value->id;
            $myBill->billno = $value->id;
            $myBill->billserial = $value->billno;
            $myBill->totalbill = $value->finalnetbillvalue;
            $myBill->datetime = $value->billdate;
            $myBill->clientName = $value->clientname;
            $myBill->userName = $value->username;
            $myBill->sellerName = "";
            $myBill->billURL = "bills.php?do=details&id=" . $myBill->billId;

            $myBill->billdiscount = $value->discountvalue;
            $myBill->networkDiscount = 0;
            if ($value->card == 1) {
                if ($value->paymentnetworkid == 4) {
                    if ($searchtype == 1) {
                        //مدى
                        $madaData = $billsEX->queryTotalNetworkReportMadaSimple($value->billdate);
                        if ($madaData->totalCarry < 5000)
                            $myBill->networkDiscount = (7 * $madaData->totalCarry) / 1000;
                        else
                            $myBill->networkDiscount = 40;
                    }
                } else {
                    $myBill->networkDiscount = ($value->cardvalue * $value->netdiscountpercent) / 100;
                }
            }

            $billDetail = $billsProductsEX->queryAllGeneral(" and billid=" . $myBill->billId . " ");

            $productsCost = 0;
            $myBill->noOfpieces = 0;
            foreach ($billDetail as $mybillDetail) {
                $myBill->noOfpieces += $mybillDetail->productno;
                $productsCost += ($mybillDetail->deleted * $mybillDetail->productno);
            }

            $myBill->billProfit = ($value->netbillvalue - $value->discountvalue) - $productsCost;

            $totalDiscount = $myBill->networkDiscount + $value->discountvalue;
            $totalDiscountPer = ($totalDiscount / 100) * $myBill->totalbill;

            array_push($allDataArr, $myBill);
            //            if ($totalDiscountPer >= $discountfrom && $totalDiscountPer <= $discountto) {
            //                array_push($allDataArr, $myBill);
            //            }
        }



        ##مرتجعات البصريات
        foreach ($billsDataReturn as $value) {
            $myBill = new billData();
            $billData = $billsDAO->load($value->id);
            $myBill->billtype = "مرتجعات بصريات";
            $myBill->billId = $value->id;
            $myBill->billno = $value->id;
            $myBill->billserial = $billData->billno;

            $myBill->datetime = $value->date;
            $myBill->clientName = $value->clientname;
            $myBill->userName = $value->username;
            $myBill->sellerName = "";
            $myBill->billURL = "billsreturn.php?do=details&id=" . $myBill->billId;

            $myBill->billdiscount = $value->discountvalue;
            $myBill->networkDiscount = 0;

            $billDetail = $billsReturnProductsEX->queryAllGeneral(" and returnbillid=" . $myBill->billId . " ");
            $myBill->totalbill = $value->returnedprice;
            $productsCost = 0;
            $myBill->noOfpieces = 0;
            foreach ($billDetail as $mybillDetail) {
                $myBill->noOfpieces += $mybillDetail->productno;
                $productsCost += ($mybillDetail->deleted * $mybillDetail->productno);
            }

            $myBill->billProfit = abs($value->returnedprice - $productsCost) * -1;


            $totalDiscount = $myBill->networkDiscount + $value->discountvalue;
            $totalDiscountPer = ($totalDiscount / 100) * $myBill->totalbill;
            array_push($allDataArr, $myBill);
            //            if ($totalDiscountPer >= $discountfrom && $totalDiscountPer <= $discountto) {
            //                array_push($allDataArr, $myBill);
            //            }
        }
        ##فاتورة المبيعات
        foreach ($sellBillData as $value) {
            $myBill = new billData();
            $myBill->billtype = "فاتورة المبيعات";
            $myBill->billId = $value->sellbillid;
            $myBill->billno = $value->sellbillid;
            $myBill->billserial = $value->sellbillserial;
            $myBill->totalbill = $value->sellbilltotalbill;
            $myBill->datetime = $value->sellbilldate;
            $myBill->clientName = $value->clientname;
            $myBill->userName = $value->employeename;
            $myBill->sellerName = $value->useremployeename;
            $myBill->billURL = "sellbillController.php?do=showDetail&sellbillid=" . $myBill->billId;

            $myBill->billdiscount = 0;
            if ($value->sellbilldiscount > 0) {
                if ($value->sellbilldiscounttype == 1) {
                    $myBill->billdiscount = $value->sellbilldiscount;
                } elseif ($value->sellbilldiscounttype == 2) {
                    $myBill->billdiscount = $value->sellbilltotalbill * $value->sellbilldiscount / 100; //  - $value->sellbillaftertotalbill;
                }
            }
            $myBill->networkDiscount = 0;

            $billDetail = $sellbilldetailEX->queryAllGeneral(" and sellbilldetail.sellbillid=" . $myBill->billId . " ");

            $productsCost = 0;
            $myBill->noOfpieces = 0;
            foreach ($billDetail as $mybillDetail) {

                #########get quantity بالقطعة
                $quantity = $mybillDetail->sellbilldetailquantity;
                $productId = $mybillDetail->sellbilldetailproductid;
                $productunitId = $mybillDetail->productunitid;
                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                $productnumber = $productunitData->productnumber;
                $finalquantity = $quantity * $productnumber;
                $myproduct->buyPrice = $value->storeid;
                ##############

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

                $myBill->noOfpieces += $finalquantity;
                //                $productsCost += $mybillDetail->storeid * $finalquantity;
                $productsCost += $buyprice * $finalquantity;
            }

            $myBill->billProfit = $value->sellbillaftertotalbill - $productsCost;

            $totalDiscount = $myBill->networkDiscount + $value->discountvalue;
            $totalDiscountPer = ($totalDiscount / 100) * $myBill->totalbill;
            array_push($allDataArr, $myBill);
            //            if ($totalDiscountPer >= $discountfrom && $totalDiscountPer <= $discountto) {
            //                array_push($allDataArr, $myBill);
            //            }
        }
        ##فاتورة مردود المبيعات
        foreach ($sellBillDataReturn as $value) {
            $myBill = new billData();
            $myBill->billtype = "فاتورة مردود المبيعات";
            $myBill->billId = $value->returnsellbillid;
            $myBill->billno = $value->returnsellbillid;
            $myBill->billserial = $value->returnsellbillserial;
            $myBill->totalbill = $value->returnsellbilltotalbill * -1;
            $myBill->datetime = $value->returnsellbilldate;
            $myBill->clientName = $value->clientname;
            $myBill->userName = $value->employeename;
            $myBill->sellerName = $value->useremployeename;
            $myBill->billURL = "returnsellbillController.php?do=showDetail&returnsellbillid=" . $myBill->billId;

            $myBill->billdiscount = 0;
            if ($value->returnsellbilldiscount > 0) {
                if ($value->returnsellbilldiscounttype == 1) {
                    $myBill->billdiscount = $value->returnsellbilldiscount * -1;
                } elseif ($value->returnsellbilldiscounttype == 2) {
                    $myBill->billdiscount = $value->returnsellbilltotalbill * $value->returnsellbilldiscount / 100; // - $value->returnsellbillaftertotalbill;
                }
            }
            $myBill->networkDiscount = 0;

            $billDetail = $returnSellBillDetailEX->queryAllGeneral(" and returnsellbilldetail.returnsellbillid=" . $myBill->billId . " ");

            $productsCost = 0;
            $myBill->noOfpieces = 0;
            foreach ($billDetail as $mybillDetail) {

                #########get quantity بالقطعة
                $quantity = $mybillDetail->returnsellbilldetailquantity;
                $productId = $mybillDetail->returnsellbilldetailproductid;
                $productunitId = $mybillDetail->productunitid;
                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                $productnumber = $productunitData->productnumber;
                $finalquantity = $quantity * $productnumber;
                $myproduct->buyPrice = $value->storeid;
                ##############

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

                $myBill->noOfpieces += $finalquantity;
                $productsCost += $buyprice * $finalquantity;
                //                $productsCost += $mybillDetail->storeid * $finalquantity;
            }

            $myBill->billProfit = $value->returnsellbillaftertotalbill - $productsCost;

            $totalDiscount = $myBill->networkDiscount + $value->discountvalue;
            $totalDiscountPer = ($totalDiscount / 100) * $myBill->totalbill;
            array_push($allDataArr, $myBill);
            //            if ($totalDiscountPer >= $discountfrom && $totalDiscountPer <= $discountto) {
            //                array_push($allDataArr, $myBill);
            //            }
        }
        ##فاتورة مبيعات و مردود
        foreach ($sellBillDataSellAndReturn as $value) {
            $myBill = new billData();
            $myBill->billtype = "فاتورة مبيعات و مردود";
            $myBill->billId = $value->sellbillid;
            $myBill->billno = $value->sellbillid;
            $myBill->billserial = $value->sellbillserial;
            $myBill->totalbill = $value->sellbilltotalbill;
            $myBill->datetime = $value->sellbilldate;
            $myBill->clientName = $value->clientname;
            $myBill->userName = $value->employeename;
            $myBill->sellerName = $value->useremployeename;
            $myBill->billURL = "sellbillandruternController.php?do=showDetail&sellbillid=" . $myBill->billId;

            $myBill->billdiscount = 0;
            if ($value->sellbilldiscount > 0) {
                if ($value->sellbilldiscounttype == 1) {
                    $myBill->billdiscount = $value->sellbilldiscount;
                } elseif ($value->sellbilldiscounttype == 2) {
                    $myBill->billdiscount = $value->sellbilltotalbill  * $value->sellbilldiscount / 100; //- $value->sellbillaftertotalbill;
                }
            }
            $myBill->networkDiscount = 0;

            $billDetail = $sellAndRuternBillDetailEX->queryAllGeneral(" and sellandruternbilldetail.sellbillid=" . $myBill->billId . " ");

            $productsCost = 0;
            $myBill->noOfpieces = 0;
            foreach ($billDetail as $mybillDetail) {

                #########get quantity بالقطعة
                $quantity = $mybillDetail->sellbilldetailquantity;
                $productId = $mybillDetail->sellbilldetailproductid;
                $productunitId = $mybillDetail->productunitid;
                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                $productnumber = $productunitData->productnumber;
                $finalquantity = $quantity * $productnumber;
                ##############

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

                if ($value->selltype == 0) {
                    $myBill->noOfpieces += $finalquantity;
                    $productsCost += abs($buyprice * $finalquantity);
                } else {
                    $myBill->noOfpieces -= $finalquantity;
                    $productsCost -= abs($buyprice * $finalquantity) * -1;
                }
            }

            $myBill->billProfit = $value->sellbillaftertotalbill - $productsCost;

            $totalDiscount = $myBill->networkDiscount + $value->discountvalue;
            $totalDiscountPer = ($totalDiscount / 100) * $myBill->totalbill;
            array_push($allDataArr, $myBill);
            //            if ($totalDiscountPer >= $discountfrom && $totalDiscountPer <= $discountto) {
            //                array_push($allDataArr, $myBill);
            //            }
        }
        #############finally get net , real cost ,net profit
        foreach ($allDataArr as $data) {
            $totalsObj->totalbill += $data->totalbill;
            $totalsObj->noOfpieces += $data->noOfpieces;
            $totalsObj->billdiscount += $data->billdiscount;
            $totalsObj->networkDiscount += $data->networkDiscount;
            $totalsObj->billProfit += $data->billProfit;
        }
        $smarty->assign("totalsObj", $totalsObj);

        if ($searchtype == 1) {
            $allDataArr = unifyDate($allDataArr, $datefrom, $dateto);
        }
    }


    $smarty->assign("searchtype", $searchtype);
    $smarty->assign("allDataArr", $allDataArr);
}

function unifyDate($allDataArr, $datefrom, $dateto)
{
    $myArr = array();
    $existDate = array();
    foreach ($allDataArr as $value) {
        if (in_array($value->datetime, $existDate)) {
            $key = array_search($value->datetime, $existDate);
            $myObj = $myArr[$key];

            $myObj->totalbill += $value->totalbill;
            $myObj->billdiscount += $value->billdiscount;
            $myObj->noOfpieces += $value->noOfpieces;
            $myObj->networkDiscount += $value->networkDiscount;
            $myObj->billProfit += $value->billProfit;
            //$myObj->billURL .= '<a href="' . $value->billURL . '" target="_blank" style="color: blue;margin-right:5px"><u>' . $value->billId . '</u></a>';
        } else {
            array_push($existDate, $value->datetime);
            //$value->billURL = '<a href="' . $value->billURL . '" target="_blank" style="color: blue;margin-right:5px"><u>' . $value->billId . '</u></a>';
            array_push($myArr, $value);
        }
    }
    $allDataArr = $myArr;
    return $allDataArr;
}
