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


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

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

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

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

//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();

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

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

    ###########################################################################
    //search
    $datefrom = filter_input(INPUT_POST, 'datefrom');
    $dateto = filter_input(INPUT_POST, 'dateto');

    $datefromold = $datefrom;
    $datetoold = $dateto;
    if (empty($datefromold)) {
        $datefromold = date('Y-m-d');
    }
    if (empty($datetoold)) {
        $datetoold = date('Y-m-d');
    }
    $smarty->assign("olddatefrom", $datefromold);
    $smarty->assign("olddateto", $datetoold);

    $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)) {
        $queryString .= 'and  date(bills.billdate)  >= "' . $datefrom . '" ';
        $queryStringR .= 'and  date(billsreturn.`date`)  >= "' . $datefrom . '" ';
        $queryString1 .= 'and  date(sellbill.sellbilldate)  >= "' . $datefrom . '" ';
        $queryString1R .= 'and  date(returnsellbill.returnsellbilldate)  >= "' . $datefrom . '" ';
        $queryString1SR .= 'and  date(sellbillandrutern.sellbilldate)  >= "' . $datefrom . '" ';
    }
    if (isset($dateto) && !empty($dateto)) {
        $queryString .= 'and  date(bills.billdate)  <= "' . $dateto . '" ';
        $queryStringR .= 'and   date(billsreturn.`date`)  <= "' . $dateto . '" ';
        $queryString1 .= 'and  date(sellbill.sellbilldate)  <= "' . $dateto . '" ';
        $queryString1R .= 'and  date(returnsellbill.returnsellbilldate)  <= "' . $dateto . '" ';
        $queryString1SR .= 'and  date(sellbillandrutern.sellbilldate)  <= "' . $dateto . '" ';
    }

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



    $smarty->assign("salesreport", 1);

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

    //here the smarty templates
    $smarty->display("freesalesview/show.html");

    //$smarty->assign("settlementstoreshow", 1);
} elseif ($do == "detail") {
    //here the permission check
    include_once("../public/authentication.php");

    //search
    $datefrom = filter_input(INPUT_GET, 'datefrom');
    $dateto = filter_input(INPUT_GET, 'dateto');
    $productId = filter_input(INPUT_GET, 'id');
//    $isOptic = filter_input(INPUT_GET, 'proIsOptic');
//    if (!isset($isOptic) || empty($isOptic)) {
//        $isOptic = 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)) {
        $queryString .= 'and  date(bills.billdate)  >= "' . $datefrom . '" ';
        $queryStringR .= 'and  date(billsreturn.`date`)  >= "' . $datefrom . '" ';
        $queryString1 .= 'and  date(sellbill.sellbilldate)  >= "' . $datefrom . '" ';
        $queryString1R .= 'and  date(returnsellbill.returnsellbilldate)  >= "' . $datefrom . '" ';
        $queryString1SR .= 'and  date(sellbillandrutern.sellbilldate)  >= "' . $datefrom . '" ';
    }
    if (isset($dateto) && !empty($dateto)) {
        $queryString .= 'and  date(bills.billdate)  <= "' . $dateto . '" ';
        $queryStringR .= 'and   date(billsreturn.`date`)  <= "' . $dateto . '" ';
        $queryString1 .= 'and  date(sellbill.sellbilldate)  <= "' . $dateto . '" ';
        $queryString1R .= 'and  date(returnsellbill.returnsellbilldate)  <= "' . $dateto . '" ';
        $queryString1SR .= 'and  date(sellbillandrutern.sellbilldate)  <= "' . $dateto . '" ';
    }

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

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


    //here the smarty templates
    $smarty->display("freesalesview/detail.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;

    }

    $existId = array();
    $allDataArr = array();
    $totalsObj = new productData();
    $resultsCount = 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  date(sellbill.sellbilldate)  = "' . $today . '" ';
            $queryString1R .= 'and  date(returnsellbill.returnsellbilldate)  = "' . $today . '" ';
            $queryString1SR .= 'and  date(sellbillandrutern.sellbilldate)  = "' . $today . '" ';
        }

        $queryString .= 'and  billsproducts.producttotalprice = 0 ';
        $queryString1 .= 'and  sellbilldetail.sellbilldetailtotalprice = 0 ';
        $queryStringR .= 'and  billsreturnproducts.producttotalprice = 0 ';
        $queryString1R .= 'and  returnsellbilldetail.returnsellbilldetailtotalprice = 0 ';
        $queryString1SR .= 'and  sellandruternbilldetail.sellbilldetailtotalprice = 0 ';

        $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;
                }
                $dicount += ($theBill->productstotalprice - $theBill->finalnetbillvalue); //خصم النسبة و خصم الكشف
                $theDiscount = ($value->productno * $dicount) / $billNoOfProduct;
                $theDiscount = round($theDiscount, 2);
                ################


                $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;
                }
                $dicount += ($theBill->productstotalprice - $theBill->finalnetbillvalue); //خصم النسبة و خصم الكشف
                $theDiscount = ($value->productno * $dicount) / $billNoOfProduct;
                $theDiscount = round($theDiscount, 2);
                ################
                $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;
                }
                $theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
                $theDiscount -= $value->discountvalue;
                $theDiscount = round($theDiscount, 2);
                ################
                $myproduct->soldVal += $value->sellbilldetailtotalprice - $theDiscount;
                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;
                }
                $theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
                $theDiscount = round($theDiscount, 2);
                ################
                $myproduct->returnVal += $value->returnsellbilldetailtotalprice - $theDiscount;
                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;
                ##############
                ######get discount
                $dicount = 0;
                $billNoOfProduct = 0;
                $dicount = $value->parcode - $value->note;
                if ($dicount != 0) {
                    $billpecies = $sellAndRuternBillDetailEX->queryBillNoOfPecies($value->sellbillid);
                    $billNoOfProduct = $billpecies->note;
                }
                $theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
                $theDiscount -= $value->discountvalue;
                $theDiscount = round($theDiscount, 2);
                ################
                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 = "";
            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;
            }
            $smarty->assign("totalsObj", $totalsObj);
        }
    }
    $smarty->assign("resultsCount", $resultsCount);
    $smarty->assign("allDataArr", $allDataArr);
}

function getDetails($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;
    global $myProductunitEx;

    class productDetails {

        public $billid = 0;
        public $billURL;
        public $billdate;
        public $productno = 0;
        public $clientname;
        public $storename;

    }

    $allDataArr = array();

    ##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  date(sellbill.sellbilldate ) = "' . $today . '" ';
        $queryString1R .= 'and  date(returnsellbill.returnsellbilldate)  = "' . $today . '" ';
        $queryString1SR .= 'and  date(sellbillandrutern.sellbilldate)  = "' . $today . '" ';
    }
    $queryString .= 'and  billsproducts.producttotalprice = 0 ';
    $queryString1 .= 'and  sellbilldetail.sellbilldetailtotalprice = 0 ';
    $queryStringR .= 'and  billsreturnproducts.producttotalprice = 0 ';
    $queryString1R .= 'and  returnsellbilldetail.returnsellbilldetailtotalprice = 0 ';
    $queryString1SR .= 'and  sellandruternbilldetail.sellbilldetailtotalprice = 0 ';

    $billsData = $billsProductsEX->queryAllGeneralSimple($queryString);
    $billsDataReturn = $billsReturnProductsEX->queryAllGeneralSimple($queryStringR);
    $sellBillData = $sellbilldetailEX->queryAllGeneralSimple($queryString1);
    $sellBillDataReturn = $returnSellBillDetailEX->queryAllGeneralSimple($queryString1R);
    $sellBillDataSellAndReturn = $sellAndRuternBillDetailEX->queryAllGeneralSimple($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) {
            $myproduct = new productDetails();
            $myproduct->billid = $value->id;
            $myproduct->billURL = "bills.php?do=details&id=" . $value->id;
            $myproduct->billdate = $value->note;
            $myproduct->productno = $value->productno;
            $myproduct->clientname = $value->deleted;
            $myproduct->storename = ""; //$value->storename;
            array_push($allDataArr, $myproduct);
        }
        ##مرتجعات البصريات
        foreach ($billsDataReturn as $value) {
            $myproduct = new productDetails();
            $myproduct->billid = $value->id;
            $myproduct->billURL = "billsreturn.php?do=details&id=" . $value->id;
            $myproduct->billdate = $value->billproductid;
            $myproduct->productno = $value->productno;
            $myproduct->clientname = $value->deleted;
            $myproduct->storename = ""; //$value->storename;
            array_push($allDataArr, $myproduct);
        }
        ##فاتورة المبيعات
        foreach ($sellBillData as $value) {
            $myproduct = new productDetails();
            $myproduct->billid = $value->sellbillid;
            $myproduct->billURL = "sellbillController.php?do=showDetail&sellbillid=" . $value->sellbillid;
            $myproduct->billdate = $value->sellbilldate;
            #########get quantity بالقطعة
            $quantity = $value->sellbilldetailquantity;
            $productunitId = $value->productunitid;
            $productnumber = $myProductunitEx->getProductNumber($productunitId);
            $finalquantity = $quantity * $productnumber;
            ##############
            $myproduct->productno = $finalquantity;
            $myproduct->clientname = $value->discountvalue;
            $myproduct->storename = $value->note;
            array_push($allDataArr, $myproduct);
        }
        ##فاتورة مردود المبيعات
        foreach ($sellBillDataReturn as $value) {
            $myproduct = new productDetails();
            $myproduct->billid = $value->returnsellbillid;
            $myproduct->billURL = "returnsellbillController.php?do=showDetail&returnsellbillid=" . $value->returnsellbillid;
            $myproduct->billdate = $value->returnsellbilldate;
            #########get quantity بالقطعة
            $quantity = $value->returnsellbilldetailquantity;
            $productunitId = $value->productunitid;
            $productnumber = $myProductunitEx->getProductNumber($productunitId);
            $finalquantity = $quantity * $productnumber;
            ##############
            $myproduct->productno = $finalquantity;
            $myproduct->clientname = $value->discountvalue;
            $myproduct->storename = $value->note;
            array_push($allDataArr, $myproduct);
        }
        ##فاتورة مبيعات و مردود
        foreach ($sellBillDataSellAndReturn as $value) {
            $myproduct = new productDetails();
            $myproduct->billid = $value->sellbillid;
            $myproduct->billURL = "sellbillandruternController.php?do=showDetail&sellbillid=" . $value->sellbillid;
            $myproduct->billdate = $value->sellbilldate;
            #########get quantity بالقطعة
            $quantity = $value->sellbilldetailquantity;
            $productunitId = $value->productunitid;
            $productnumber = $myProductunitEx->getProductNumber($productunitId);
            $finalquantity = $quantity * $productnumber;
            ##############
            $myproduct->productno = $finalquantity;
            $myproduct->clientname = $value->discountvalue;
            $myproduct->storename = $value->note;
            array_push($allDataArr, $myproduct);
        }
    }

    $smarty->assign("resultsCount", $resultsCount);
    $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);
//                }
//            }
//        }
    }
}

?>