<?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');


//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');

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');


//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');
//Billsreturnproduct
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');

//Government
require_once('../models/dao/GovernmentDAO.class.php');
require_once('../models/dto/Government.class.php');
require_once('../models/mysql/GovernmentMySqlDAO.class.php');
require_once('../models/mysql/ext/GovernmentMySqlExtDAO.class.php');

//GovernArea
require_once('../models/dao/GoverareaDAO.class.php');
require_once('../models/dto/Goverarea.class.php');
require_once('../models/mysql/GoverareaMySqlDAO.class.php');
require_once('../models/mysql/ext/GoverareaMySqlExtDAO.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');

$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();

//Sellbilldetail
$sellbilldetail = new Sellbilldetail();
$sellbilldetailDAO = new SellbilldetailMySqlDAO();
$sellbilldetailEX = new SellbilldetailMySqlExtDAO();
//Returnsellbilldetail
$returnSellBillDetail = new Returnsellbilldetail();
$returnSellBillDetailDAO = new ReturnsellbilldetailMySqlDAO();
$returnSellBillDetailEX = new ReturnsellbilldetailMySqlExtDAO();
//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();
//billsReturnproducts
$billsReturnProducts = new Billsreturnproduct();
$billsReturnProductsDAO = new BillsreturnproductsMySqlDAO();
$billsReturnProductsEX = new BillsreturnproductsMySqlExtDAO();

///////////////product///////////////
$ProductDAO = new ProductMySqlDAO();
$Product = new Product();
$ProductEX = new ProductMySqlExtDAO();
//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();

//# government
$governmentDAO = new GovernmentMySqlDAO();

//# governArea
$governAreaDAO = new GoverareaMySqlDAO();

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

//# client
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

$lastLevelCatIDS = array();
$catsIDS = "";
//check and use the condition that suite this action
if (empty($do)) {
    //here the permission check
    include_once("../public/authentication.php");
    $Programsetting = $ProgramsettingDAO->load(1);

    ##########################################################################
    //prepare search tools
    ##التصنيفات
    $catDataReport = getCategoryChilds();
    $smarty->assign("catDataReport", $catDataReport[1]);

    $governmentData = $governmentDAO->queryAll();
    $smarty->assign("governmentData", $governmentData);

    $user = $userDAO->load($_SESSION['userid']);
    $smarty->assign("user", $user);
    //if ($user->userstoreid == 0) {
    $storeData = loadStore();
    $smarty->assign("storeData", $storeData);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    //}
    if ($user->branchId == 0) {
        $branchData = loadBranch();
        $smarty->assign("branchData", $branchData);
    }
    $sellerData = loadseller();
    $smarty->assign("sellerData", $sellerData);
    $userData = loadusers();
    $smarty->assign("userData", $userData);
    ###########################################################################
    //search
    $datefrom = filter_input(INPUT_POST, 'datefrom');
    $dateto = filter_input(INPUT_POST, 'dateto');

    $storeId = filter_input(INPUT_POST, 'storeId');
    $branchId = filter_input(INPUT_POST, 'branchId');
    $sellerid = filter_input(INPUT_POST, 'sellerid');
    $userid = filter_input(INPUT_POST, 'userid');
    $governmentId = filter_input(INPUT_POST, 'governmentId');
    $areaid = filter_input(INPUT_POST, 'areaid');



    $level = filter_input(INPUT_POST, 'level');
    $productCatId = filter_input(INPUT_POST, 'productCatId' . $level);
    if (empty($productCatId) || $productCatId == -1) {
        $productCatId = filter_input(INPUT_POST, 'productCatId' . ($level - 1));
    }
    $productId = filter_input(INPUT_POST, 'productId');
    $searchtype = filter_input(INPUT_POST, 'searchtype');

    $isOptic = filter_input(INPUT_POST, 'proIsOptic');
    if (!isset($isOptic) || empty($isOptic)) {
        $isOptic = 0;
    }
    if ($isOptic == 2 && $searchtype == 1) {
        $productCatId = $productId;
    }

    $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)) {
        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
            $datefrom = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($datefrom)));
        } else {
            $datefrom = $datefrom . " 00:00:00";
        }
        $queryString .= 'and  bills.billdate  >= "' . $datefrom . '" ';
        $queryStringR .= 'and  billsreturn.`date`  >= "' . $datefrom . '" ';
        $queryString1 .= 'and  sellbill.sellbilldate  >= "' . $datefrom . '" ';
        $queryString1R .= 'and  returnsellbill.returnsellbilldate  >= "' . $datefrom . '" ';
        $queryString1SR .= 'and  sellbillandrutern.sellbilldate  >= "' . $datefrom . '" ';
    }
    if (isset($dateto) && !empty($dateto)) {
        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
            $dateto = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($dateto)));
        } else {
            $dateto = $dateto . ' 23:59:59';
        }
        $queryString .= 'and  bills.billdate  <= "' . $dateto . '" ';
        $queryStringR .= 'and   billsreturn.`date`  <= "' . $dateto . '" ';
        $queryString1 .= 'and  sellbill.sellbilldate  <= "' . $dateto . '" ';
        $queryString1R .= 'and  returnsellbill.returnsellbilldate  <= "' . $dateto . '" ';
        $queryString1SR .= 'and  sellbillandrutern.sellbilldate  <= "' . $dateto . '" ';
    }
    ##storeId
    $theStore;
    if (isset($storeId) && !empty($storeId) && $storeId != -1) {
        if ($user->userstoreid == 0) {
            $theStore = $storeId;
            //$queryString .= 'and  bills.sellbillstoreid  = ' . $storeId . ' ';
            $queryString1 .= 'and  sellbill.sellbillstoreid  = ' . $storeId . ' ';
            $queryString1R .= 'and  returnsellbill.returnsellbillstoreid  = ' . $storeId . ' ';
            $queryString1SR .= 'and  sellbillandrutern.sellbillstoreid  = ' . $storeId . ' ';
        } else {
            $theStore = $user->userstoreid;
            //$queryString .= 'and  bills.sellbillstoreid  = ' . $user->userstoreid . ' ';
            $queryString1 .= 'and  sellbill.sellbillstoreid  = ' . $user->userstoreid . ' ';
            $queryString1R .= 'and  returnsellbill.returnsellbillstoreid  = ' . $user->userstoreid . ' ';
            $queryString1SR .= 'and  sellbillandrutern.sellbillstoreid  = ' . $user->userstoreid . ' ';
        }
    }


    ##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 . ' ';
        }
    }

    ##sellerid
    if (isset($sellerid) && !empty($sellerid) && $sellerid != -1) {
        //$queryString .= 'and  bills.billdate  = "' . $dateto . '" ';
        $queryString1 .= 'and  sellbill.sellerid  = "' . $sellerid . '" ';
        $queryString1R .= 'and  returnsellbill.sellerid  = "' . $sellerid . '" ';
        $queryString1SR .= 'and  sellbillandrutern.sellerid  = "' . $sellerid . '" ';
    }
    ##userid
    if (isset($userid) && !empty($userid) && $userid != -1) {
        $queryString .= 'and  bills.userid  = ' . $userid . ' ';
        $queryStringR .= 'and  billsreturn.userid  = ' . $userid . ' ';
        $queryString1 .= 'and  sellbill.userid  = ' . $userid . ' ';
        $queryString1R .= 'and  returnsellbill.userid  = ' . $userid . ' ';
        $queryString1SR .= 'and  sellbillandrutern.userid  = ' . $userid . ' ';
    }

    ##government
    if (isset($governmentId) && $governmentId != '-1' && ( $areaid == '-1' || !isset($areaid))) {
        $clientids = '';
        if ($governmentId == 0) {
            $government_Data = $governAreaDAO->queryAll();
        } else {
            $government_Data = $governAreaDAO->queryByGovernmentid($governmentId);
        }

        foreach ($government_Data as $value) {
            $clientareaid = $value->clientareaid;
            $clientData = $clientExt->queryAllbyarea($clientareaid);
            foreach ($clientData as $client) {
                $clientids .= ',' . $client->clientid;
            }
        }
        $clientids = ltrim($clientids, ',');

        $queryString .= 'and  bills.clientid  in ( ' . $clientids . ' ) ';
        //$queryStringR .= 'and  billsreturn.userid  = ' . $userid . ' ';
        $queryString1 .= 'and  sellbill.sellbillclientid  in ( ' . $clientids . ' )  ';
        $queryString1R .= 'and  returnsellbill.returnsellbillclientid in ( ' . $clientids . ' ) ';
        $queryString1SR .= 'and  sellbillandrutern.sellbillclientid  in ( ' . $clientids . ' )  ';
    }


    ## area
    if (isset($areaid) && $areaid != '-1') {

        $clientids = '';

        $clientData = $clientExt->queryAllbyarea($areaid);
        foreach ($clientData as $client) {
            $clientids .= ',' . $client->clientid;
        }
        $clientids = ltrim($clientids, ',');

        $queryString .= 'and  bills.clientid  in ( ' . $clientids . ' ) ';
        //$queryStringR .= 'and  billsreturn.userid  = ' . $userid . ' ';
        $queryString1 .= 'and  sellbill.sellbillclientid  in ( ' . $clientids . ' )  ';
        $queryString1R .= 'and  returnsellbill.returnsellbillclientid in ( ' . $clientids . ' ) ';
        $queryString1SR .= 'and  sellbillandrutern.sellbillclientid  in ( ' . $clientids . ' )  ';
    }


    if ($searchtype == 0) {
        ##productId
        if (isset($productId) && !empty($productId) && $productId != -1) {
            if ($isOptic == 2) {
                $productsOfCat = $ProductEX->queryByProductCatIdIn($productId);
                $productId = '0';
                foreach ($productsOfCat as $value) {
                    $productId .= ',' . $value->productId;
                }
            }
            $queryString .= 'and  billsproducts.productid  in( ' . $productId . ' ) ';
            $queryStringR .= 'and  billsreturnproducts.productid  in( ' . $productId . ' ) ';
            $queryString1 .= 'and  sellbilldetail.sellbilldetailproductid  in( ' . $productId . ' ) ';
            $queryString1R .= 'and  returnsellbilldetail.returnsellbilldetailproductid  in( ' . $productId . ' ) ';
            $queryString1SR .= 'and  sellandruternbilldetail.sellbilldetailproductid  in( ' . $productId . ' ) ';
        } elseif (isset($productCatId) && !empty($productCatId) && $productCatId != -1) {
            ##get subcat of cat
            $catsIDS = '' . $productCatId;
            getAllSubCat($productCatId, 1); //mode = 1 get all sub cats
            $productsOfCat = $ProductEX->queryByProductCatIdIn($catsIDS);
            $IDS = '0';
            foreach ($productsOfCat as $value) {
                $IDS .= ',' . $value->productId;
            }

            $queryString .= 'and  billsproducts.productid  in (' . $IDS . ') ';
            $queryString1 .= 'and  sellbilldetail.sellbilldetailproductid  in (' . $IDS . ') ';
            $queryStringR .= 'and  billsreturnproducts.productid   in (' . $IDS . ') ';
            $queryString1R .= 'and  returnsellbilldetail.returnsellbilldetailproductid  in (' . $IDS . ') ';
            $queryString1SR .= 'and  sellandruternbilldetail.sellbilldetailproductid  in (' . $IDS . ') ';
        }

        getData($queryString, $queryString1, $queryStringR, $queryString1R, $queryString1SR, $searchtype, $productCatId, $theStore);
    } elseif ($searchtype == 1) {

        getData($queryString, $queryString1, $queryStringR, $queryString1R, $queryString1SR, $searchtype, $productCatId, $theStore);
    }



    $smarty->assign("salesreport", 1);
    //here the smarty templates
    $smarty->display("saleswithdetaileddiscountview/show.html");

    //$smarty->assign("settlementstoreshow", 1);
}
//here the global templates
$smarty->display("footer.html");

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

function getData($queryString, $queryString1, $queryStringR, $queryString1R, $queryString1SR, $searchtype, $productCatId, $theStore) {
    global $billsProductsEX;
    global $billsDAO;
    global $billsEX;
    global $billsReturnDAO;
    global $billsReturnProductsEX;
    global $sellbilldetailEX;
    global $returnSellBillDetailEX;
    global $sellAndRuternBillDetailEX;
    global $ProductDAO;
    global $productCatDAO;
    global $ProductEX;
    global $smarty;
    global $lastLevelCatIDS;
    global $catsIDS;

    class productData {

        public $id;
        public $productName;
        public $soldNo = 0;
        public $soldVal = 0;
        public $returnNo = 0;
        public $returnVal = 0;
        public $netNo = 0;
        public $netVal = 0;
        public $realCost = 0;
        public $netProfit = 0;
        public $buyPrice = 0;
        public $currentQuantity = 0;
        public $discount = 0;

    }

    $existId = array();
    $allDataArr = array();
    $totalsObj = new productData();
    $resultsCount = 0;
    $flag = 0;

    if ($searchtype == 0) {
        ##if no search make it today
        if ($queryString == " where 1 ") {
            ##date
            $today = date("Y-m-d");
            $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 . '" ';
        }
        $billsData = $billsProductsEX->queryAllGeneral($queryString);
        $billsDataReturn = $billsReturnProductsEX->queryAllGeneral($queryStringR);
        $sellBillData = $sellbilldetailEX->queryAllGeneral($queryString1);
        $sellBillDataReturn = $returnSellBillDetailEX->queryAllGeneral($queryString1R);
        $sellBillDataSellAndReturn = $sellAndRuternBillDetailEX->queryAllGeneral($queryString1SR);
        $resultsCount = count($billsData) + count($billsDataReturn) + count($sellBillData) + count($sellBillDataReturn) + count($sellBillDataSellAndReturn);
        $smarty->assign("resultsCount", $resultsCount);
        if ($resultsCount > 0) {
            ##unique products
            ##مبيعات البصريات
            foreach ($billsData as $value) {
                if (in_array($value->productid, $existId)) {
                    $key = array_search($value->productid, $existId);
                    $myproduct = $allDataArr[$key];
                } else {
                    $key = -1;
                    $myproduct = new productData();
                    $myproduct->id = $value->productid;
                    array_push($existId, $value->productid);
                }

                $myproduct->productName = $value->productName;
                $myproduct->soldNo += $value->productno; //no directly no product unit used
                ##get discount
                $theBill = $billsDAO->load($value->billid);

                $dicount = 0;
                $billNoOfProduct = 0;
                if ($theBill->card == 1) {
                    if ($theBill->paymentnetworkid == 4) {
                        //مدى
                        $madaData = $billsEX->queryTotalNetworkReportMadaSimple($theBill->billdate);
                        if ($madaData->totalCarry < 5000)
                            $dicount = (7 * $madaData->totalCarry) / 1000;
                        else
                            $dicount = 40;
                    } else {
                        $dicount = ($theBill->cardvalue * $theBill->netdiscountpercent) / 100;
                    }
                }

                if ($dicount != 0) {
                    $billpecies = $billsProductsEX->queryBillNoOfPecies($value->billid);
                    $billNoOfProduct = $billpecies->deleted;
                    $flag = 1;
                }

                $dicount += ($theBill->productstotalprice - $theBill->finalnetbillvalue); //خصم النسبة و خصم الكشف

                if ($flag == 1) {
                    $theDiscount = ($value->productno * $dicount) / $billNoOfProduct;
                    $theDiscount = round($theDiscount, 2);
                    $flag = 0;
                } else {
                    $theDiscount = $dicount;
                    $theDiscount = round($theDiscount, 2);
                }
                ################
                $myproduct->discount += $theDiscount;

                $myproduct->soldVal += $value->producttotalprice - $theDiscount;
                $myproduct->buyPrice = $value->deleted;
                if ($key == -1) {
                    array_push($allDataArr, $myproduct);
                }
            }
            ##مرتجعات البصريات
            foreach ($billsDataReturn as $value) {
                if (in_array($value->productid, $existId)) {
                    $key = array_search($value->productid, $existId);
                    $myproduct = $allDataArr[$key];
                } else {
                    $key = -1;
                    $myproduct = new productData();
                    $myproduct->id = $value->productid;
                    array_push($existId, $value->productid);
                }

                $myproduct->productName = $value->productName;
                $myproduct->returnNo += $value->productno; //no directly no product unit used
                ##get discount
                $theBill = $billsDAO->load($value->billproductid);

                $dicount = 0;
                $billNoOfProduct = 0;
                if ($theBill->card == 1) {
                    if ($theBill->paymentnetworkid == 4) {
                        //مدى
                        $madaData = $billsEX->queryTotalNetworkReportMadaSimple($theBill->billdate);
                        if ($madaData->totalCarry < 5000)
                            $dicount = (7 * $madaData->totalCarry) / 1000;
                        else
                            $dicount = 40;
                    } else {
                        $dicount = ($theBill->cardvalue * $theBill->netdiscountpercent) / 100;
                    }
                }
                if ($dicount != 0) {
                    $billpecies = $billsProductsEX->queryBillNoOfPecies($value->billproductid);
                    $billNoOfProduct = $billpecies->deleted;
                    $flag = 1;
                }
                $dicount += ($theBill->productstotalprice - $theBill->finalnetbillvalue); //خصم النسبة و خصم الكشف

                if ($flag == 1) {
                    $theDiscount = ($value->productno * $dicount) / $billNoOfProduct;
                    $theDiscount = round($theDiscount, 2);
                    $flag = 0;
                } else {
                    $theDiscount = $dicount;
                    $theDiscount = round($theDiscount, 2);
                }
                ################
                $myproduct->discount -= $theDiscount;

                $myproduct->returnVal += $value->producttotalprice - $theDiscount;
                $myproduct->buyPrice = $value->deleted;
                if ($key == -1) {
                    array_push($allDataArr, $myproduct);
                }
            }
            ##فاتورة المبيعات
            foreach ($sellBillData as $value) {
                if (in_array($value->sellbilldetailproductid, $existId)) {
                    $key = array_search($value->sellbilldetailproductid, $existId);
                    $myproduct = $allDataArr[$key];
                } else {
                    $key = -1;
                    $myproduct = new productData();
                    $myproduct->id = $value->sellbilldetailproductid;
                    array_push($existId, $value->sellbilldetailproductid);
                }

                $myproduct->productName = $value->productName;
                #########get quantity بالقطعة
                $quantity = $value->sellbilldetailquantity;
                $productId = $value->sellbilldetailproductid;
                $productunitId = $value->productunitid;
                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                $productnumber = $productunitData->productnumber;
                $finalquantity = $quantity * $productnumber;
                ##############
                $myproduct->soldNo += $finalquantity; //العدد بالقطعة
                ######get discount
                $dicount = 0;
                $billNoOfProduct = 0;
                $dicount = $value->parcode - $value->note;

                if ($dicount != 0) {
                    $billpecies = $sellbilldetailEX->queryBillNoOfPecies($value->sellbillid);
                    $billNoOfProduct = $billpecies->note;
                    $flag = 1;
                }

                if ($flag == 1) {
                    $theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
                    $theDiscount -= $value->discountvalue;
                    $theDiscount = round($theDiscount, 2);
                    $flag = 0;
                } else {
                    $theDiscount = $dicount;
                    $theDiscount = round($theDiscount, 2);
                }
                ################
                $myproduct->discount += $theDiscount;

                $myproduct->soldVal += $value->sellbilldetailtotalprice - $theDiscount;
                $myproduct->buyPrice = $value->storeid;
                if ($key == -1) {
                    array_push($allDataArr, $myproduct);
                }
            }
            ##فاتورة مردود المبيعات
            foreach ($sellBillDataReturn as $value) {
                if (in_array($value->returnsellbilldetailproductid, $existId)) {
                    $key = array_search($value->returnsellbilldetailproductid, $existId);
                    $myproduct = $allDataArr[$key];
                } else {
                    $key = -1;
                    $myproduct = new productData();
                    $myproduct->id = $value->returnsellbilldetailproductid;
                    array_push($existId, $value->returnsellbilldetailproductid);
                }

                $myproduct->productName = $value->productName;
                #########get quantity بالقطعة
                $quantity = $value->returnsellbilldetailquantity;
                $productId = $value->returnsellbilldetailproductid;
                $productunitId = $value->productunitid;
                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                $productnumber = $productunitData->productnumber;
                $finalquantity = $quantity * $productnumber;
                ##############
                $myproduct->returnNo += $finalquantity; //العدد بالقطعة
                ######get discount
                $dicount = 0;
                $billNoOfProduct = 0;
                $dicount = $value->parcode - $value->note;
                if ($dicount != 0) {
                    $billpecies = $returnSellBillDetailEX->queryBillNoOfPecies($value->returnsellbillid);
                    $billNoOfProduct = $billpecies->note;
                    $flag = 1;
                }

                if ($flag == 1) {
                    $theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
                    $theDiscount = round($theDiscount, 2);
                    $flag = 0;
                } else {
                    $theDiscount = $dicount;
                    $theDiscount = round($theDiscount, 2);
                }
                ################
                $myproduct->discount -= $theDiscount;

                $myproduct->returnVal += $value->returnsellbilldetailtotalprice - $theDiscount;
                $myproduct->buyPrice = $value->storeid;
                if ($key == -1) {
                    array_push($allDataArr, $myproduct);
                }
            }
            ##فاتورة مبيعات و مردود
            foreach ($sellBillDataSellAndReturn as $value) {
                if (in_array($value->sellbilldetailproductid, $existId)) {
                    $key = array_search($value->sellbilldetailproductid, $existId);
                    $myproduct = $allDataArr[$key];
                } else {
                    $key = -1;
                    $myproduct = new productData();
                    $myproduct->id = $value->sellbilldetailproductid;
                    array_push($existId, $value->sellbilldetailproductid);
                }

                $myproduct->productName = $value->productName;
                #########get quantity بالقطعة
                $quantity = $value->sellbilldetailquantity;
                $productId = $value->sellbilldetailproductid;
                $productunitId = $value->productunitid;
                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                $productnumber = $productunitData->productnumber;
                $finalquantity = $quantity * $productnumber;
                $myproduct->buyPrice = $value->storeid;
                ##############
                ######get discount
                $dicount = 0;
                $billNoOfProduct = 0;
                $dicount = $value->parcode - $value->note;
                if ($dicount != 0) {
                    $billpecies = $sellAndRuternBillDetailEX->queryBillNoOfPecies($value->sellbillid);
                    $billNoOfProduct = $billpecies->note;
                    $flag = 1;
                }

                if ($flag == 1) {
                    $theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
                    $theDiscount -= $value->discountvalue;
                    $theDiscount = round($theDiscount, 2);
                    $flag = 0;
                } else {
                    $theDiscount = $dicount;
                    $theDiscount = round($theDiscount, 2);
                }
                ################
                $myproduct->discount += $theDiscount;

                if ($value->selltype == 0) {
                    $myproduct->soldNo += $finalquantity; //العدد بالقطعة
                    $myproduct->soldVal += $value->sellbilldetailtotalprice - $theDiscount;
                } else {
                    $myproduct->returnNo += $finalquantity; //العدد بالقطعة
                    $myproduct->returnVal += $value->sellbilldetailtotalprice - $theDiscount;
                }
                if ($key == -1) {
                    array_push($allDataArr, $myproduct);
                }
            }
            #############finally get net , real cost ,net profit
            $myQuery = "";
            if (isset($theStore) && !empty($theStore) && $theStore != -1) {
                $myQuery = " and storedetail.storeid = " . $theStore;
            }
            foreach ($allDataArr as $data) {
                $data->netNo = $data->soldNo - $data->returnNo;
                $data->netVal = $data->soldVal - $data->returnVal;
                ##realcost
//                $buyDatail = $ProductDAO->load($data->id); ## i may use ->loadext() to get quantity
//                $data->realCost = $data->netNo * $buyDatail->productBuyPrice;
//                $data->netProfit = $data->netVal - $data->realCost;
                if ($buyDatail->isOptic == 2) {
                    $catName = $ProductEX->loadProductCatNameOnly($data->id);
                    $data->productName = $data->productName . "/" . $catName;
                }

                ##currentQuantity
//                $buyDatail = $ProductEX->getProductQuantity($data->id, $myQuery);
//                $data->currentQuantity = $buyDatail->sumProductQuantity;
                ##totals
                $totalsObj->soldNo += $data->soldNo;
                $totalsObj->soldVal += $data->soldVal;
                $totalsObj->returnNo += $data->returnNo;
                $totalsObj->returnVal += $data->returnVal;
                $totalsObj->netNo += $data->netNo;
                $totalsObj->netVal += $data->netVal;
//                $totalsObj->realCost += $data->realCost;
//                $totalsObj->netProfit += $data->netProfit;
//                $totalsObj->currentQuantity += $data->currentQuantity;
                $totalsObj->discount += $data->discount;
            }
            $smarty->assign("totalsObj", $totalsObj);
        }
    }
    $smarty->assign("resultsCount", $resultsCount);

//    print_r('<pre>');
//        print_r($allDataArr);
//    print_r('<pre>');

    foreach ($allDataArr as $val) {

        $product_id = $val->id;
        $full_product_name = get_parents_of_products($product_id);

        $val->productName = $full_product_name;
    }

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

function getAllSubCat($catid, $mode) {
    global $productCatExt;
    global $productCatDAO;
    global $catsIDS;
    global $lastLevelCatIDS;
    //mode = 1 get all sub cats
    //mode = 2 get last level cats

    $result = $productCatExt->queryByParentExt($catid);
    if (count($result) > 0) {
        foreach ($result as $data) {
            if ($mode == 1) {
                $catsIDS .= "," . $data->productCatId;
                getAllSubCat($data->productCatId, $mode);
            } elseif ($mode == 2) {
                $childData = $productCatExt->queryByParentExt($data->productCatId);
                if (count($childData) > 0) {
                    getAllSubCat($data->productCatId, $mode);
                } else {
                    if (!empty($data->productCatId)) {
                        array_push($lastLevelCatIDS, $data->productCatId);
                    }
                }
            }
        }
    } else {
//        if ($mode == 2) {
//            $childData = $productCatExt->queryByParentExt($data->productCatId);
//            if (count($childData) > 0) {
//                getAllSubCat($data->productCatId, $mode);
//            } else {
//                if (!empty($data->productCatId)) {
//                    array_push($lastLevelCatIDS, $data->productCatId);
//                }
//            }
//        }
    }
}

//# pass $product_id to get parent of this product . M7md
function get_parents_of_products($product_id) {

    global $ProductDAO;


    $product_data = $ProductDAO->load($product_id);

    $product_name = $product_data->productName;
    $productCatId = $product_data->productCatId;

    $parent_name = '';
    $parents_name = get_parents($productCatId, $parent_name);

    $full_product_name = $parents_name . $product_name;

    return $full_product_name;
}

//# this function used to get productcat id and check its parent if = 0 or not . M7md
function get_parents($productCatId, $parent_name) {

    global $productCatDAO;

    $product_cat_data = $productCatDAO->load($productCatId);

    $parent_name = $product_cat_data->productCatName . ' / ' . $parent_name;

    $productCatParent = $product_cat_data->productCatParent;

    //# check if $productCatParent > 0 to get parent of parent .
    if ($productCatParent != 0) {

        $product_cat_data_parent = $productCatDAO->load($productCatParent);


        $parent_name = $product_cat_data_parent->productCatName . ' / ' . $parent_name;

        $productCatParent_parent = $product_cat_data_parent->productCatParent;

        if ($productCatParent_parent != 0) {

            get_parents($productCatParent_parent, $parent_name);
        }
    }

    return $parent_name;
    //print_r('<br> '.$parent_name);
}

?>