<?php

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

//global varable
global $showoutside;

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

//here the db files that include in the file
include("../public/include_dao.php");
//Storedetail
require_once('../models/dao/StoredetailDAO.class.php');
require_once('../models/dto/Storedetail.class.php');
require_once('../models/mysql/StoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/StoredetailMySqlExtDAO.class.php');
//Store
require_once('../models/dao/StoreDAO.class.php');
require_once('../models/dto/Store.class.php');
require_once('../models/mysql/StoreMySqlDAO.class.php');
require_once('../models/mysql/ext/StoreMySqlExtDAO.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');
//Productcat
require_once('../models/dao/ProductcatDAO.class.php');
require_once('../models/dto/Productcat.class.php');
require_once('../models/mysql/ProductcatMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatMySqlExtDAO.class.php');

//get the do the action


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


//Buybilldetail
require_once('../models/dao/BuybilldetailDAO.class.php');
require_once('../models/dto/Buybilldetail.class.php');
require_once('../models/mysql/BuybilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybilldetailMySqlExtDAO.class.php');


require_once('../models/dao/ReturnbuybilldetailDAO.class.php');
require_once('../models/dto/Returnbuybilldetail.class.php');
require_once('../models/mysql/ReturnbuybilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybilldetailMySqlExtDAO.class.php');

//Productunit
require_once('../models/dao/ProductunitDAO.class.php');
require_once('../models/dto/Productunit.class.php');
require_once('../models/mysql/ProductunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductunitMySqlExtDAO.class.php');

//Sizecolorstoredetail
require_once('../models/dao/SizecolorstoredetailDAO.class.php');
require_once('../models/dto/Sizecolorstoredetail.class.php');
require_once('../models/mysql/SizecolorstoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SizecolorstoredetailMySqlExtDAO.class.php');

//Usergroup
require_once('../models/dao/UsergroupDAO.class.php');
require_once('../models/dto/Usergroup.class.php');
require_once('../models/mysql/UsergroupMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupMySqlExtDAO.class.php');
//
require_once('../models/dao/ProductingredientsDAO.class.php');
require_once('../models/dto/Productingredient.class.php');
require_once('../models/mysql/ProductingredientsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductingredientsMySqlExtDAO.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');

//lang

$lang = $_SESSION['erp_lang'];
include_once("../views/languages/$lang/storedetail/storedetail.php");

$do = $_GET['do'];
$lastLevelCatIDS;
/* ======================

  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
//Storedetail
$myStoredetail = new Storedetail();
$myStoredetailRecord = new StoredetailMySqlDAO();
$myStoredetailEx = new StoredetailMySqlExtDAO();
//Store
$myStoreRecord = new StoreMySqlDAO();
//Product
$myProductRecord = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();
//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();

$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

//Buybilldetail
$buyBillDetail = new Buybilldetail();
$buyBillDetailDAO = new BuybilldetailMySqlDAO();
$buyBillDetailExt = new BuybilldetailMySqlExtDAO();

//Returnbuybilldetail
$returnBuyBillDetail = new Returnbuybilldetail();
$returnBuyBillDetailDAO = new ReturnbuybilldetailMySqlDAO();
$returnBuyBillDetailExt = new ReturnbuybilldetailMySqlExtDAO();
//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();
eval(base64_decode("ZnVuY3Rpb24gc2VyaWFsY2hlY2soKSB7CiAgICAvL3V1aWQgb2Ygd2luZG93cwogICAgZXhlYygnQzpcV2luZG93c1xTeXN0ZW0zMlx3YmVtXHdtaWMgY3Nwcm9kdWN0IGdldCAiVVVJRCInLCAkbWFjYWRkcmVzcywgJGlzRXhlY3V0ZWQpOwogICAgJG1hY2FkZHJlc3MgPSAkbWFjYWRkcmVzc1sxXTsKICAgICRtYWMgPSBzdHJfcmVwbGFjZShhcnJheSgnLScpLCAnJywgJG1hY2FkZHJlc3MpOwogICAgaWYgKGVtcHR5KCRtYWNhZGRyZXNzKSkgey8vbm90IHdpbmRvd3MgdXNlIGxpbnV4IG1hYwogICAgICAgIC8vbWFjIG9mIGxpbnV4CiAgICAgICAgJG1hY2FkZHJlc3MgPSBleGVjKCJpcCBsaW5rIik7CiAgICAgICAgLy8kbWFjYWRkcmVzcyA9IGV4ZWMoImlwIC1icmllZiBsaW5rIik7CiAgICAgICAgLy8kbWFjYWRkcmVzcyA9IGV4ZWMoImNhdCAvc3lzL2NsYXNzL25ldC8qL2FkZHJlc3MiKTsKICAgICAgICAkbWFjYWRkcmVzcyA9IHRyaW0oc3RyX3JlcGxhY2UoJ2xpbmsvZXRoZXIgJywgJycsICRtYWNhZGRyZXNzKSk7CiAgICAgICAgJG1hY2FkZHJlc3MgPSBzdWJzdHIoJG1hY2FkZHJlc3MsIDAsIDE3KTsKICAgICAgICAkbWFjID0gc3RyX3JlcGxhY2UoYXJyYXkoJzonKSwgJycsICRtYWNhZGRyZXNzKTsKICAgIH0KCiAgICAkcmFuZG9tX3NhbHQgPSBoYXNoKCdzaGE1MTInLCAnMTMwNScpOwogICAgLy8gQ3JlYXRlIHNhbHRlZCBwYXNzd29yZAogICAgJGhhc2hlZE1hYyA9IGhhc2goJ3NoYTUxMicsICRtYWMgLiAkcmFuZG9tX3NhbHQpOwogICAgcmV0dXJuICRoYXNoZWRNYWM7Cn0="));
eval(base64_decode("JHNlcmlhbENhbCA9IHNlcmlhbGNoZWNrKCk7CiAgICBpZiAoJHByb2ctPnNlcmlhbCAhPSAkc2VyaWFsQ2FsIHx8ICRfU0VTU0lPTlsnbGljX2RhdGV0byddIDwgZGF0ZSgnWS1tLWQnKSkgewogICAgICAgIC8vc2VuZCB0aGUgdXNlciB0byB0aGUgbG9nb3V0IHBhZ2UKICAgICAgICBoZWFkZXIoImxvY2F0aW9uOmxvZ291dC5waHAiKTsKICAgICAgICBleGl0KCk7CiAgICB9"));
//Sellbilldetail
$sellbilldetail = new Sellbilldetail();
$sellbilldetailDAO = new SellbilldetailMySqlDAO();
$sellbilldetailEX = new SellbilldetailMySqlExtDAO();

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

//
$sizeColorStoreDetail = new Sizecolorstoredetail();
$sizeColorStoreDetailDAO = new SizecolorstoredetailMySqlDAO();
$sizeColorStoreDetailEX = new SizecolorstoredetailMySqlExtDAO();

$myUserGroup = new Usergroup();
$myUserGroupRecord = new UsergroupMySqlDAO();
$myUserGroupEx = new UsergroupMySqlExtDAO();
eval(base64_decode("aWYgKCFmdW5jdGlvbl9leGlzdHMoJ3NlcmlhbGNoZWNrJykpIHsKICAgIENVUkxfSVQyKGFycmF5KCksICdzZWxsYmlsbEFqYXhDb250cm9sbGVyLnBocD9kbz1jYXRjaCcpOwogICAgaGVhZGVyKCJsb2NhdGlvbjpsb2dvdXQucGhwIik7Cn0="));
//Productingredient
$productIngredients = new Productingredient();
$productIngredientsDAO = new ProductingredientsMySqlDAO();
$productIngredientsEX = new ProductingredientsMySqlExtDAO();


$myusergroupdata = $myUserGroupRecord->load($_SESSION['usergroupid']);
$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);
$catsIDS = '';
//check and use the condition that suite this action
if ($do == "show" || empty($do)) {
    //here the permission check
    include_once("../public/authentication.php");

    //  radio btn
    $search = $_POST['search'];
    $storeData = loadStore();
    $smarty->assign("storeData", $storeData);

    $productCatData = $productCatExt->getProductCatParents();
    $smarty->assign("productCatData", $productCatData);

//    $catWithProduct = loadProductCategories();
//    $smarty->assign("catWithProduct", $catWithProduct);

    $productId = $_REQUEST['productId'];
    $storeId = $_REQUEST['storeId'];
    $productCatId = $_REQUEST['productCatId0'];
    //    echo "$myusergroupdata->hidecat".$myusergroupdata->hidecat;
    $smarty->assign('hidecat', $myusergroupdata->hidecat);
    $smarty->assign('showstoredetailprice', $myusergroupdata->showstoredetailprice);


    if (isset($productId) && $productId != "-1" && $productId != "" || isset($storeId) && $storeId != "-1" || isset($productCatId) && $productCatId != "-1" || $search == 1) {
        $storedetailData = showunittype(0);
    }



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

    /* print_r('<pre>');
      print_r($storedetailData);
      print_r('<pre>'); */

    $sumValue = round($storedetailData[1], 2);
    $smarty->assign('sumValue', $sumValue);

    if ($search == 0) {
        //here the smarty templates
        $container_array = array();
        $x = 1;
        $productquantity = 0;
        $minusQuantity = 0;
        $plusQuantity = 0;
        $minusPrice = 0;
        $plusPrice = 0;
        foreach ($storedetailData[0] as $value) {
            switch ($Programsettingdata->Inventoryevaluation) {
                case "first":
                    $buyprice = (float) $value->productBuyPrice;
                    break;
                case "last":
                    $buyprice = (float) $value->lastbuyprice;
                    break;
                case "mean":
                    $buyprice = (float) $value->meanbuyprice;
                    break;
                case "last_discount":
                    $buyprice = (float) $value->lastbuyprice_withDiscount;
                    break;
                case "mean_discount":
                    $buyprice = (float) $value->meanbuyprice_withDiscount;
                    break;
                case "generalPrice":
                    $buyprice = (float) $value->overAllAveragePrice;
                    break;
                case "tax":
                    $buyprice = (float) $value->lastbuyprice_withTax;
                    break;
                case "mean_tax":
                    $buyprice = (float) $value->meanbuyprice_withTax;
                    break;
            }
            $container_array[] = array(
                'itra' => $x,
                'storeName' => $value->storeName,
                'productName' => $value->productName,
                'productCatName' => $value->productCatName,
                'parcode' => $value->parcode,
                'productquantity' => $value->productquantity,
                'productBuyPrice' => $buyprice,
                //                'productBuyPrice' => $value->productBuyPrice,
                'storedetaildate' => $value->storedetaildate,
                'storeid' => $value->storeid,
                'unittype' => $value->unittype,
                'productid' => $value->productid,
                'productDataSAC' => $value->productDataSAC,
                'productDataSOC' => $value->productDataSOC,
                'productDataING' => $value->productDataING,
            );
            $x++;
            if ($value->productquantity > 0) {
                $plusQuantity += $value->productquantity;
                //                $plusPrice += $value->productquantity * $value->productBuyPrice;
                $plusPrice += $value->productquantity * $buyprice;
            } else {
                $minusQuantity += $value->productquantity;
                //                $minusPrice += $value->productquantity * $value->productBuyPrice;
                $minusPrice += $value->productquantity * $buyprice;
            }
            $productquantity += $value->productquantity;
        }

        $smarty->assign('productquantity', $productquantity);
        $smarty->assign('plusQuantity', $plusQuantity);
        $smarty->assign('minusQuantity', $minusQuantity);

        $smarty->assign('plusPrice', $plusPrice);
        $smarty->assign('minusPrice', $minusPrice);

        $smarty->assign('storedetailData', $container_array);
        $smarty->display("storedetailview/show.html");
    } else {

        foreach ($storedetailData[2] as $value) {
            switch ($Programsettingdata->Inventoryevaluation) {
                case "first":
                    $buyprice = (float) $value->productBuyPrice;
                    break;
                case "last":
                    $buyprice = (float) $value->lastbuyprice;
                    break;
                case "mean":
                    $buyprice = (float) $value->meanbuyprice;
                    break;
                case "last_discount":
                    $buyprice = (float) $value->lastbuyprice_withDiscount;
                    break;
                case "mean_discount":
                    $buyprice = (float) $value->meanbuyprice_withDiscount;
                    break;
                case "generalPrice":
                    $buyprice = (float) $value->overAllAveragePrice;
                    break;
                case "tax":
                    $buyprice = (float) $value->lastbuyprice_withTax;
                    break;
                case "mean_tax":
                    $buyprice = (float) $value->meanbuyprice_withTax;
                    break;
            }


            $productBuyPrice = $buyprice;
            $productQuantity = $value->productquantity;
            $SumProductPrice = $productBuyPrice * $productQuantity;
            $value->productSellAllPrice = $SumProductPrice;
        }
        $smarty->assign('sellbilldata', $storedetailData[2]);
        $smarty->display("storedetailview/showquantity.html");
    }
    $smarty->assign("settlementstoreshow", 1);
} elseif ($do == "showsizeandcolor") {
    //  radio btn
    $search = $_POST['search'];
    $storeData = loadStore();
    $smarty->assign("storeData", $storeData);

    $productCatData = $productCatExt->getProductCatParents();
    $smarty->assign("productCatData", $productCatData);

    $catWithProduct = loadProductCategories();
    $smarty->assign("catWithProduct", $catWithProduct);

    $productId = $_REQUEST['productId'];
    $storeId = $_REQUEST['storeId'];
    $productCatId = $_REQUEST['productCatId0'];
    //    echo "$myusergroupdata->hidecat".$myusergroupdata->hidecat;
    $smarty->assign('hidecat', $myusergroupdata->hidecat);
    $smarty->assign('showsizeandcolor', $myusergroupdata->showsizeandcolor);
    $smarty->assign('showstoredetailprice', $myusergroupdata->showstoredetailprice);

    if (isset($productId) && $productId != "-1" && $productId != "" || isset($storeId) && $storeId != "-1" || isset($productCatId) && $productCatId != "-1") {
        $storedetailData = showStoreSizeAndColor();
    }
    /* print_r('<pre>');
      print_r($storedetailData);
      print_r('<pre>'); */
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);


    $sumValue = round($storedetailData[1], 2);
    $smarty->assign('sumValue', $sumValue);

    if ($search == 0) {
        //here the smarty templates
        $container_array = array();
        $x = 1;
        $productquantity = 0;
        $minusQuantity = 0;
        $plusQuantity = 0;
        $minusPrice = 0;
        $plusPrice = 0;
        foreach ($storedetailData[0] as $value) {
            switch ($Programsettingdata->Inventoryevaluation) {
                case "first":
                    $buyprice = (float) $value->productBuyPrice;
                    break;
                case "last":
                    $buyprice = (float) $value->lastbuyprice;
                    break;
                case "mean":
                    $buyprice = (float) $value->meanbuyprice;
                    break;
                case "last_discount":
                    $buyprice = (float) $value->lastbuyprice_withDiscount;
                    break;
                case "mean_discount":
                    $buyprice = (float) $value->meanbuyprice_withDiscount;
                    break;
                case "generalPrice":
                    $buyprice = (float) $value->overAllAveragePrice;
                    break;
                case "tax":
                    $buyprice = (float) $value->lastbuyprice_withTax;
                    break;
                case "mean_tax":
                    $buyprice = (float) $value->meanbuyprice_withTax;
                    break;
            }
            $container_array[] = array(
                'itra' => $x,
                'storeName' => $value->storeName,
                'productName' => $value->productName,
                'parcode' => $value->parcode,
                'productquantity' => $value->quantity,
                'productBuyPrice' => $buyprice,
                //                'productBuyPrice' => $value->productBuyPrice,
                'storedetaildate' => $value->sysdate,
                'productid' => $value->productid,
            );
            $x++;
            if ($value->quantity > 0) {
                $plusQuantity += $value->quantity;
                //                $plusPrice += $value->quantity * $value->productBuyPrice;
                $plusPrice += $value->quantity * $buyprice;
            } else {
                $minusQuantity += $value->quantity;
                //                $minusPrice += $value->quantity * $value->productBuyPrice;
                $minusPrice += $value->quantity * $buyprice;
            }
            $productquantity += $value->quantity;
        }

        $smarty->assign('productquantity', $productquantity);
        $smarty->assign('plusQuantity', $plusQuantity);
        $smarty->assign('minusQuantity', $minusQuantity);

        $smarty->assign('plusPrice', $plusPrice);
        $smarty->assign('minusPrice', $minusPrice);

        $smarty->assign('storedetailData', $container_array);
        $smarty->display("storedetailview/showSizeAndColor.html");
    }
    /* else {
      $smarty->assign('sellbilldata', $storedetailData[2]);
      $smarty->display("storedetailview/showSizeAndColor.html");
      } */
    $smarty->assign("settlementstoreshow", 1);
}
//here the global templates
$smarty->display("footer.html");

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

//select all product data
function loadProducts() {
    //to use the variable out side the funcion
    global $myProductRecord;

    //load all product data
    $productData = $myProductRecord->queryByConditions(0);

    return $productData;
}

//select all store data
function loadStore() {
    //to use the variable out side the funcion
    global $myStoreRecord;

    //load all store data
    $storeData = $myStoreRecord->queryByConditions(0);

    return $storeData;
}

function loadProductCategories() {
    global $productExt;
    global $productCatDAO;
    global $smarty;
    $categories;

    //NOTICE: select categories which have products in it only, not all categories.
    $productsData = $productExt->queryAllProducts();

    if (count($productsData) > 0) {
        $i = 0;
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            $pathArr = fetch_recursive($parentId, $categories);
            $smarty->assign("names" . $i, $pathArr);
            $smarty->assign("parentId" . $i, $parentId);
            $i++;
        }
        $itr = $i - 1;
        $smarty->assign("itr", $itr);
    }

    return $productsData;
}

function fetch_recursive($parentid, $categories) {
    global $productCatExt;
    $catData = $productCatExt->getCategoryAndParentByCatId($parentid);

    if (count($catData) > 0) {
        $categories .= $catData->productCatName . '/';
        $newParentId = $catData->productCatParent;

        if ($newParentId != 0) {
            $newParentName = $catData->parentName;
            $categories .= $newParentName . '/';
            fetch_recursive($newParentId, $categories);
        }
    }
    $categories = substr($categories, 0, strlen($categories) - 1);
    return $categories;
}

// show the form by product name
function show() {
    global $smarty;
    //to use the variable out side the funcion
    global $myStoredetailEx;
    global $ProgramsettingDAO;
    global $buyBillDetail;
    global $buyBillDetailDAO;
    global $buyBillDetailExt;
    global $returnBuyBillDetail;
    global $returnBuyBillDetailDAO;
    global $returnBuyBillDetailExt;
    global $myStoreRecord;
    global $myProductRecord;
    global $productCatDAO;
    global $sellbilldetailEX;
    global $productExt;

    global $Programsettingdata;

    include_once("../public/authentication.php");
    $storeId = $_REQUEST['storeId'];
    $productCatId = $_REQUEST['productCatId'];
    $order = $_REQUEST["order"];
    $counter = $_POST['counter'];
    $childCast = $_POST["productChild" . ($counter - 1)];
    $productId = $_POST["productId" . $counter];

    // print_r($childCast . '<br>');
    $searchType = filter_input(INPUT_POST, 'search');
    $queryString = ' AND';
    $message = "تقرير بضاعة أول مدة : ";
    $mystordata = $myStoreRecord->load($storeId);
    if ($searchType == 0) {




        if (isset($productCatId) && $productCatId != '-1') {


            if (isset($childCast) && !empty($childCast) && $childCast != -1 && isset($productCatId) && !empty($productCatId) && $productCatId != -1 && (empty($productId) || $productId == -1)) {
                $catIds = getAllSubCat($childCast);
                $catIds = ltrim($catIds, ',');
                //   print_r($catIds);
                $productsOfCat = $productExt->queryByProductCatIdInNotService($catIds);
                $IDS = '0';
                foreach ($productsOfCat as $value) {
                    $IDS .= ',' . $value->productId;
                }
                $queryString .= '  product.productId in (' . $IDS . ') AND';
            } else {
                $catIds = getAllSubCat($productCatId);
                $catIds = ltrim($catIds, ',');
                //   print_r($catIds);
                $productsOfCat = $productExt->queryByProductCatIdInNotService($catIds);
                $IDS = '0';
                foreach ($productsOfCat as $value) {
                    $IDS .= ',' . $value->productId;
                }
                $queryString .= '  product.productId in (' . $IDS . ') AND';
            }

            $myProductCatData = $productCatDAO->load($productCatId);
            $message = $message . $myProductCatData->productCatName;
        }

        if (isset($productId) && $productId != '-1' && $productId != '') {
            // print_r($productId . 'aaaaaaaaaaa' . $storeId . 'bbbbbbbbbbbbbbbbb' . $productCatId . 'ccccccccccccccccccc' . $order);

            $myprodactdata = $myProductRecord->load($productId);

            $message = $message . " للمنتج  :" . $myprodactdata->productName . "  ";


            $queryString .= ' storedetail.productId = ' . $productId . ' AND';
        }

        if (isset($storeId) && $storeId != '-1') {
            $queryString .= '  storedetail.storeid = ' . $storeId . ' AND';

            $message = $message . "    والمخزن : " . $mystordata->storeName . "";
        }
        $arr = explode(' ', $queryString);
        //print_r($arr);
        if (isset($arr) && count($arr) > 0) {
            $lastWord = end($arr);
            if ($lastWord == 'AND') {//remove it
                array_pop($arr);
                //form the string again
                $queryString = implode(' ', $arr);
            }

            // print("<br> " . $queryString . "<br>");
        }

        //select all data from storedetail by productId
        $storedetailData = $myStoredetailEx->queryWithqueryString($queryString, $order);


        // print_r($message);
        $smarty->assign('message', $message);
        $sumValue = 0;
        foreach ($storedetailData as $storedetail) {
            $myproduct = $myProductRecord->load($storedetail->productid);

            switch ($Programsettingdata->Inventoryevaluation) {
                case "first":
                    $buyprice = (float) $myproduct->productBuyPrice;
                    break;
                case "last":
                    $buyprice = (float) $myproduct->lastbuyprice;
                    break;
                case "mean":
                    $buyprice = (float) $myproduct->meanbuyprice;
                    break;
                case "last_discount":
                    $buyprice = (float) $myproduct->lastbuyprice_withDiscount;
                    break;
                case "mean_discount":
                    $buyprice = (float) $myproduct->meanbuyprice_withDiscount;
                    break;
                case "generalPrice":
                    $buyprice = (float) $myproduct->overAllAveragePrice;
                    break;
                case "tax":
                    $buyprice = (float) $myproduct->lastbuyprice_withTax;
                    break;
                case "mean_tax":
                    $buyprice = (float) $myproduct->meanbuyprice_withTax;
                    break;
            }
            if ($Programsettingdata->lastprice == "0") {
                if ($myproduct->lastprice == NULL) {
                    $myproduct->lastprice = $myproduct->productBuyPrice;
                }

                $productBuyPrice = round($buyprice, 2);
            } else {
                if ($myproduct->meanbuyprice == NULL || $myproduct->meanbuyprice == 0) {
                    $myproduct->meanbuyprice = $myproduct->productBuyPrice;
                }
                $productBuyPrice = round($buyprice, 2);
            }
            $storedetail->productBuyPrice = $productBuyPrice;
            $productQuantity = $storedetail->productquantity;
            $SumProductPrice = $productBuyPrice * $productQuantity;

            $sumValue = $SumProductPrice + $sumValue;

            ///////////To show product category name (the product whole path)
            $parentId = $storedetail->productCatId;
            //names of product's parents
            $pathArr = getProductPath_recursive($parentId, $categories);

            //new product name with all path

            if ($_SESSION['hidecat'] == 1) {



                $storedetail->productName = $pathArr . '/' . $storedetail->productName;
            } else {

                $storedetail->productName = $storedetail->productName;
            }
        }
    }
    // search by final product or category
    else {
        $sumValue = 0;
        $queryString1 = '';

        if (isset($childCast) && !empty($childCast) && $childCast != -1 && isset($productCatId) && !empty($productCatId) && $productCatId != -1 && (empty($productId) || $productId == -1)) {
            $x = getAllSubCat($childCast); //mode = 1 get all sub cats
            $x = ltrim($x, ',');
            $productsOfCat = $productExt->queryByProductCatIdInNotService($x);
            //  print_r($productsOfCat);
            $IDS = '0';
            foreach ($productsOfCat as $value) {
                $IDS .= ',' . $value->productId;
            }
            $queryString1 .= 'and   product.productId  in (' . $IDS . ') ';
            $storedetailData2 = $myStoredetailEx->queryWithqueryString2($queryString1, $order);

            // $sellBillData = $sellbilldetailEX->queryAllGeneralGrouped($queryString1);
            foreach ($storedetailData2 as $sum) {
                $sumValue = $sumValue + $sum->totQty;
            }
            $myProductCatData = $productCatDAO->load($childCast);
            $message = $message . $myProductCatData->productCatName;
        } elseif (isset($childCast) && !empty($childCast) && $childCast != -1 && isset($productId) && !empty($productId) && $productId != -1) {

            $queryString1 .= 'and   product.productId  in (' . $productId . ') ';
            $storedetailData2 = $myStoredetailEx->queryWithqueryString2($queryString1, $order);
            //$sellBillData = $sellbilldetailEX->queryAllGeneralGrouped($queryString1);
            foreach ($storedetailData2 as $sum) {
                $sumValue = $sumValue + $sum->totQty;
            }
            $myProductCatData = $productCatDAO->load($childCast);
            $message = $message . $myProductCatData->productCatName;

            $myprodactdata = $myProductRecord->load($productId);
            $message = $message . " للمنتج  :" . $myprodactdata->productName . "  ";
        } elseif (isset($productCatId) && !empty($productCatId) && $productCatId != -1 && empty($childCast) && empty($productId)) {

            $lastLevelCatIDS = '';
            $x = getAllSubCat($productCatId); //mode = 1 get all sub cats
            $x = ltrim($x, ',');

            $productsOfCat = $productExt->queryByProductCatIdInNotService($x);
            //  print_r($productsOfCat);
            $IDS = '0';
            foreach ($productsOfCat as $value) {
                $IDS .= ',' . $value->productId;
            }
            $queryString1 .= 'and   product.productId   in (' . $IDS . ') ';
            $storedetailData2 = $myStoredetailEx->queryWithqueryString2($queryString1, $order);

            //$sellBillData = $sellbilldetailEX->queryAllGeneralGrouped($queryString1);
            foreach ($storedetailData2 as $sum) {
                $sumValue = $sumValue + $sum->totQty;
            }
            $myProductCatData = $productCatDAO->load($productCatId);
            $message = $message . $myProductCatData->productCatName;
        } elseif (isset($productCatId) && !empty($productCatId) && $productCatId != -1 && empty($childCast) && $productId == -1) {

            $lastLevelCatIDS = '';
            $x = getAllSubCat($productCatId); //mode = 1 get all sub cats
            $x = ltrim($x, ',');

            $productsOfCat = $productExt->queryByProductCatIdInNotService($x);
            //  print_r($productsOfCat);
            $IDS = '0';
            foreach ($productsOfCat as $value) {
                $IDS .= ',' . $value->productId;
            }
            $queryString1 .= 'and  product.productId   in (' . $IDS . ') ';
            $storedetailData2 = $myStoredetailEx->queryWithqueryString2($queryString1, $order);

            //$sellBillData = $sellbilldetailEX->queryAllGeneralGrouped($queryString1);
            foreach ($storedetailData2 as $sum) {
                $sumValue = $sumValue + $sum->totQty;
            }
            $myProductCatData = $productCatDAO->load($productCatId);
            $message = $message . $myProductCatData->productCatName . " والمخزن " . $mystordata->storeName . "";
        } elseif (isset($productCatId) && !empty($productCatId) && $productCatId != -1 && isset($productId) && !empty($productId) && $productId != -1) {

            $product_IDS = $myProductRecord->queryByProductCatId($productId);
            if (!empty($product_IDS)) {
                foreach ($product_IDS as $value) {
                    $IDS .= ',' . $value->productId;
                }
                $IDS = ltrim($IDS, ',');
                $queryString1 .= 'and  product.productId  in (' . $IDS . ') ';
            } else {
                $queryString1 .= 'and  product.productId  in (' . $productId . ') ';
            }




            $storedetailData2 = $myStoredetailEx->queryWithqueryString2($queryString1, $order);

            //$sellBillData = $sellbilldetailEX->queryAllGeneralGrouped($queryString1);
            foreach ($storedetailData2 as $sum) {
                $sumValue = $sumValue + $sum->totQty;
            }
            $myProductCatData = $productCatDAO->load($productCatId);
            $message = $message . $myProductCatData->productCatName;
        }

        if (isset($storeId) && $storeId != '-1') {
            $queryString1 .= 'AND  storedetail.storeid = ' . $storeId . '   ';

            $message = $message . "    والمخزن : " . $mystordata->storeName . "";
        }

        $smarty->assign('message', $message);
    }




    $smarty->assign('storedetailData', $storedetailData);

    //print_r($storedetailData);
    return array($storedetailData, $sumValue, $storedetailData2);
}

function showunittype($unittype) {
    global $smarty;
    //to use the variable out side the funcion
    global $myStoredetailEx;
    global $ProgramsettingDAO;
    global $buyBillDetail;
    global $buyBillDetailDAO;
    global $buyBillDetailExt;
    global $returnBuyBillDetail;
    global $returnBuyBillDetailDAO;
    global $returnBuyBillDetailExt;
    global $myStoreRecord;
    global $myProductRecord;
    global $productCatDAO;
    global $sellbilldetailEX;
    global $productExt;
    global $sizeColorStoreDetailEX;
    global $productIngredientsEX;

    global $Programsettingdata;
    global $catsIDS;

    include_once("../public/authentication.php");
    $storeId = $_REQUEST['storeId'];
    //    $productCatId = $_REQUEST['productCatId0'];
    $order = $_REQUEST["order"];
    $counter = $_POST['counter'];
    $proIsOptic = (int) $_POST['proIsOptic'];
    $childCast = $_POST["productChild" . ($counter - 1)];
    $productId = $_POST["productId" . $counter];
    $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));
    }
    $sizeId = $colorId = 0;
    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
        $sizeId = $productIdComplex[1];
        $colorId = $productIdComplex[2];
    }

    // print_r($childCast . '<br>');
    $showStoreBetweenQuantity = (int) $_REQUEST['showStoreBetweenQuantity'];
    $searchType = filter_input(INPUT_POST, 'search');
    $queryString = ' AND';
    $queryString2 = ' AND';
    $queryStringAll = '';
    $message = "تقرير بضاعة أول مدة : ";
    $mystordata = $myStoreRecord->load($storeId);
    if ($searchType == 0) {

        if (isset($productId) && $productId > 0) {
            // print_r($productId . 'aaaaaaaaaaa' . $storeId . 'bbbbbbbbbbbbbbbbb' . $productCatId . 'ccccccccccccccccccc' . $order);

            $myprodactdata = $myProductRecord->load($productId);

            $message = $message . " للمنتج  :" . $myprodactdata->productName . "  ";


            if ($proIsOptic == 2) {
                $queryString .= ' product.productId = ' . $myprodactdata->productCatId . ' AND';
                $queryString2 .= '  product.productCatId = ' . $myprodactdata->productCatId . ' AND';
            } else {
                $queryString .= ' product.productId = ' . $productId . ' AND';
                $queryString2 .= '  product.productCatId = ' . $productId . ' AND';
            }

            $queryStringAll = ' where isOptic = ' . $proIsOptic . ' ';
        } else if (isset($productCatId) && $productCatId > 0) {


            //              print_r('productCatId'.$productCatId);
            //isset($childCast) && !empty($childCast) && $childCast != -1 &&         //$childCast always = null
            if (isset($productCatId) && $productCatId > 0 && $productId < 1) {
                $catsIDS = $productCatId;
                $catsIDS = getAllSubCat($productCatId);
                $catsIDS = ltrim($catsIDS, ',');

                $productsOfCat = $productExt->queryByProductCatIdInNotService($catsIDS);
                $IDS = '0';
                foreach ($productsOfCat as $value) {
                    $IDS .= ',' . $value->productId;
                }
                $queryString .= '  product.productId in (' . $IDS . ') AND';
                $queryString2 .= '  product.productCatId in (' . $catsIDS . ') AND';
            } else {
                $catsIDS = $productCatId;
                $catsIDS = getAllSubCat($productCatId);
                //                var_dump($catIds);
                $catsIDS = ltrim($catsIDS, ',');
                //                   print_r($catIds);
                $catsIDS = $catsIDS . ',' . $productCatId;
                $productsOfCat = $productExt->queryByProductCatIdInNotService($catsIDS);
                $IDS = '0';
                // print_r('vvvvvvvvvvvv'.$productsOfCat);
                foreach ($productsOfCat as $value) {
                    $IDS .= ',' . $value->productId;
                }

                $queryString .= '  product.productId in (' . $IDS . ') AND';
                $queryString2 .= '  product.productCatId in (' . $catsIDS . ') AND';
            }

            $myProductCatData = $productCatDAO->load($productCatId);
            $message = $message . $myProductCatData->productCatName;
        }


        $queryStringStore = '';
        $SCqueryStringStore = '';
        $queryStringStoreMoveBetween = '';
        if (isset($storeId) && $storeId != '-1') {
//            $queryString .= '  storedetail.storeid = ' . $storeId . ' AND';
//            $queryString2 .= '  storedetail.storeid = ' . $storeId . ' AND';
            $queryStringStore = '  AND storedetail.storeid = ' . $storeId . ' ';
            $SCqueryStringStore = '  AND sizecolorstoredetail.storeid = ' . $storeId . ' ';
            $queryStringStoreMoveBetween = '  AND storemovement.storeidto = ' . $storeId . ' ';
            $message = $message . "    والمخزن : " . $mystordata->storeName . "";
        }
        $SCqueryString = '';
        if ($sizeId > 0 && $colorId > 0) {
            $SCqueryString = " and  sizecolorstoredetail.sizeid = $sizeId  and  sizecolorstoredetail.colorid = $colorId ";
        }
        $arr = explode(' ', $queryString);
        //print_r($arr);
        if (isset($arr) && count($arr) > 0) {
            $lastWord = end($arr);
            if ($lastWord == 'AND') {//remove it
                array_pop($arr);
                //form the string again
                $queryString = implode(' ', $arr);
            }

            // print("<br> " . $queryString . "<br>");
        }
        $arr = explode(' ', $queryString2);
        //print_r($arr);
        if (isset($arr) && count($arr) > 0) {
            $lastWord = end($arr);
            if ($lastWord == 'AND') {//remove it
                array_pop($arr);
                //form the string again
                $queryString2 = implode(' ', $arr);
            }

            // print("<br> " . $queryString . "<br>");
        }
        ## get store detail
//        if ($Programsettingdata->scunitname != '0') {
//            $storedetailData = $myStoredetailEx->queryWithqueryStringandunittypeFatma($queryString, $queryString2, $queryStringAll, $order, 0);
//        } else {
//            $storedetailData = $myStoredetailEx->queryWithqueryStringFatma($queryString, $queryString2, $queryStringAll, $order);
//        }
        ## get results
        $storedetailDataFromProducts = R::getAll('SELECT product.parcode,product.productId, product.productName, product.productBuyPrice,product.productSellUnitPrice,product.productCatId
                ,product.lastbuyprice,product.meanbuyprice,product.overAllAveragePrice,product.meanbuyprice_withDiscount,product.lastbuyprice_withDiscount,lastbuyprice_withTax,meanbuyprice_withTax
                ,product.isOptic,product.conditions,product.logo,product.productDescription,product.hasSizeAndColor
                FROM product where product.conditions = 0 and product.isOptic != 2 ' . $queryString);
        $storedetailDataFromCats = R::getAll('SELECT -1 as parcode,product.productCatId as productId,product.productCatName as productName,-1 as productBuyPrice,-1 as productSellUnitPrice,productCatParent as productCatId
                ,-1 as lastbuyprice,-1 as meanbuyprice,-1 as overAllAveragePrice,-1 as meanbuyprice_withDiscount,-1 as lastbuyprice_withDiscount,-1 as lastbuyprice_withTax,-1 as meanbuyprice_withTax
                ,product.isOptic,product.conditions,product.logo,product.productCatDescription as productDescription,0 as hasSizeAndColor
                FROM productcat as product where product.conditions = 0 and product.isOptic = 2 ' . $queryString2);
        ##get storedetail quantities
        $unittypeQuery = '';
        if ($Programsettingdata->scunitname != '0')
            $unittypeQuery = ' and unittype = ' . $unittype . ' ';

        if ($showStoreBetweenQuantity == 1) {
            //R::debug(true);
            $storeDetailDataArrProducts = R::getAll('
                select * from
                ((
                    SELECT storedetailid,productid,storedetail.storeid,sum(productquantity) as productquantity,storedetaildate,unittype,storeName
                    FROM storedetail
                    JOIN store ON  storedetail.storeid = store.storeId
                    where 1 ' . $unittypeQuery . ' ' . $queryStringStore . ' ' . str_replace("product.", "", $queryString) . '
                    group by productid,storeid
                )union(

                    select -1 as storedetailid,productid,storeidto as storeid,sum(transferproductamount) as productquantity,transferproductdate as storedetaildate,-1 as unittype
                    ,CONCAT(storeName, " وسيط ") AS storeName
                     from storemovement
                    JOIN store ON  storemovement.storeidto = store.storeId
                    where storemovement.conditions=0 and recieveType=1 and recieveUserid=0 ' . $queryStringStoreMoveBetween . ' ' . str_replace("product.", "", $queryString) . '
                    group by productid,storeid
                )) as temp

            ');
        } else {
            $storeDetailDataArrProducts = R::getAll('SELECT storedetailid,productid,storedetail.storeid,sum(productquantity)as productquantity,storedetaildate,unittype,storeName
                FROM storedetail
                JOIN store ON  storedetail.storeid = store.storeId
                where 1 ' . $unittypeQuery . ' ' . $queryStringStore . ' ' . str_replace("product.", "", $queryString) . ' group by productid,storedetail.storeid');
        }

        $storeDetailDataArrProducts = customArrayIndexMany($storeDetailDataArrProducts, 'productid');
        $storeDetailDataArrCats = R::getAll('SELECT storedetailid,storedetail.storeid,productquantity,storedetaildate,unittype,storeName,product.productCatId,product.productCatId as productid
                FROM storedetail
                JOIN store ON  storedetail.storeid = store.storeId
                join product on product.productId = storedetail.productid
                where 1 and product.isOptic = 2 ' . $unittypeQuery . ' ' . $queryStringStore . ' ' . $queryString2 . ' group by product.productCatId,store.storeId');
        list($productCatIdsOpticArr) = [[]];
        foreach ($storeDetailDataArrCats as $value) {
            $productCatIdsOpticArr [] = $value['productCatId'];
        }
        $productCatIdsOpticArr = !empty($productCatIdsOpticArr) ? array_unique($productCatIdsOpticArr) : [0];
        $storeDetailDataArrCats = customArrayIndexMany($storeDetailDataArrCats, 'productCatId');
        $tempDataArr = array();
        list($productCatIdsArr) = [[]];
        foreach ($storedetailDataFromProducts as $value) {
            foreach ($storeDetailDataArrProducts[$value['productId']] as $data) {
                foreach ($data as $key1 => $value1) {
                    $value[$key1] = $value1;
                }
                $productCatIdsArr [] = $value['productCatId'];
                $tempDataArr[] = $value;
            }
        }
        foreach ($storedetailDataFromCats as $value) {
            foreach ($storeDetailDataArrCats[$value['productId']] as $data) {//product id in value is cat id at $storeDetailDataArrCats
                foreach ($data as $key1 => $value1) {
                    $value[$key1] = $value1;
                }
                $productCatIdsArr [] = $value['productCatId'];
                $tempDataArr[] = $value;
            }
        }
        unset($storedetailDataFromProducts, $storedetailDataFromCats);
        $storedetailData = $tempDataArr;
        ## get catname
        $productCatIdsArr = !empty($productCatIdsArr) ? array_unique($productCatIdsArr) : [0];
        $productCatDataArr = R::getAll('select productCatId,productCatName,discounttype,buydiscount from productcat where productCatId in(' . implode(',', $productCatIdsArr) . ')');
        $productCatDataArr = customArrayIndexOne($productCatDataArr, 'productCatId');
        $tempDataArr = array();
        list($productIdsHasSizeAndColorArr, $productIdsCollectiveArr) = [[]];
        foreach ($storedetailData as $value) {
            $value['productCatName'] = $productCatDataArr[$value['productCatId']]['productCatName'];
            $value['discounttype'] = $productCatDataArr[$value['productCatId']]['discounttype'];
            $value['buydiscount'] = $productCatDataArr[$value['productCatId']]['buydiscount'];
            $value['productquantity'] = (float) $value['productquantity'];
            if ($value['hasSizeAndColor'] == 1)
                $productIdsHasSizeAndColorArr[] = $value['productId'];
            elseif ($value['isOptic'] != 2)
                $productIdsCollectiveArr[] = $value['productId'];


            $obj = new stdClass();
            foreach ($value as $key1 => $value1) {
                $obj->$key1 = $value1;
            }
            $tempDataArr[] = $obj;
            //$tempDataArr[] = $value;
        }
        $storedetailData = $tempDataArr;
        $productIdsHasSizeAndColorArr = !empty($productIdsHasSizeAndColorArr) ? array_unique($productIdsHasSizeAndColorArr) : [0];
        $productIdsCollectiveArr = !empty($productIdsCollectiveArr) ? array_unique($productIdsCollectiveArr) : [0];

        ##getting data of each product type "optic , collective ,sizecolor"
        #1- optic
        $opticDetails = R::getAll('SELECT product.*,storedetail.storeid,SUM(storedetail.productquantity) AS sumProductQuantity
                            FROM product
                            JOIN storedetail
                            ON storedetail.productid = product.productId WHERE productCatId in(' . implode(',', $productCatIdsOpticArr) . ') ' . $queryStringStore . ' and product.conditions = 0 group by storedetail.productid,storedetail.storeid');
        $opticDetails = customArrayManyIndexMany($opticDetails, array('productCatId', 'storeid'));
        $tempArr = array();
        foreach ($opticDetails as $key => $value) {
            foreach ($value as $value1) {
                $obj = new stdClass();
                foreach ($value1 as $key2 => $value2) {
                    $obj->$key2 = $value2;
                }
                $tempArr[$key][] = $obj;
            }
        }
        $opticDetails = $tempArr;
        #2- sizecolor
        $SCProductsDetails = R::getAll('SELECT sizecolorstoredetail.*,size.name as sizeName,color.name as colorName
                FROM sizecolorstoredetail
                left join sizecolor as size on size.id=sizecolorstoredetail.sizeid
                left join sizecolor as color on color.id=sizecolorstoredetail.colorid
                WHERE productid in(' . implode(',', $productIdsHasSizeAndColorArr) . ') ' . $SCqueryStringStore . ' ' . $SCqueryString . ' order by sizecolorstoredetail.id asc');
        $SCProductsDetails = customArrayManyIndexMany($SCProductsDetails, array('productid', 'storeid'));
        $tempArr = array();
        foreach ($SCProductsDetails as $key => $value) {
            foreach ($value as $value1) {
                $obj = new stdClass();
                foreach ($value1 as $key2 => $value2) {
                    $obj->$key2 = $value2;
                }
                $tempArr[$key][] = $obj;
            }
        }
        $SCProductsDetails = $tempArr;
        #3- ingredients of collective pro
        $collectiveProductDetails = R::getAll('SELECT productingredients.* ,product.productName ,product.productBuyPrice , unit.unitName
                ,productBuyPrice,lastbuyprice,lastbuyprice_withDiscount,meanbuyprice,meanbuyprice_withDiscount
                ,productnumber
                FROM productingredients
                JOIN product
			 ON product.productId = productingredients.ingridientId
		JOIN productunit
			 ON  productunit.productunitid=productingredients.unitId
		JOIN unit
         	 ON unit.unitId= productunit.unitid
                WHERE productingredients.productId in(' . implode(',', $productIdsCollectiveArr) . ')');
        $collectiveProductDetails = customArrayIndexMany($collectiveProductDetails, 'productId');
        $tempArr = array();
        foreach ($collectiveProductDetails as $key => $value) {
            foreach ($value as $value1) {
                $obj = new stdClass();
                foreach ($value1 as $key2 => $value2) {
                    $obj->$key2 = $value2;
                }
                $tempArr[$key][] = $obj;
            }
        }
        $collectiveProductDetails = $tempArr;

        // print_r($message);
        $smarty->assign('message', $message);
        $sumValue = 0;

        foreach ($storedetailData as $storedetail) {

            switch ($Programsettingdata->Inventoryevaluation) {
                case "first":
                    $buyprice = (float) $storedetail->productBuyPrice;
                    break;
                case "last":
                    $buyprice = (float) $storedetail->lastbuyprice;
                    break;
                case "mean":
                    $buyprice = (float) $storedetail->meanbuyprice;
                    break;
                case "last_discount":
                    $buyprice = (float) $storedetail->lastbuyprice_withDiscount;
                    break;
                case "mean_discount":
                    $buyprice = (float) $storedetail->meanbuyprice_withDiscount;
                    break;
                case "generalPrice":
                    $buyprice = (float) $storedetail->overAllAveragePrice;
                    break;
                case "tax":
                    $buyprice = (float) $storedetail->lastbuyprice_withTax;
                    break;
                case "mean_tax":
                    $buyprice = (float) $storedetail->meanbuyprice_withTax;
                    break;
            }
            if ($storedetail->parcode == -1) {
                $storedetail->parcode = '';
            }
            // print_r($storedetail);
            if ($Programsettingdata->scunitname != '0') {
//                $productid = $storedetail->productid;
//                $productdata = $myStoredetailEx->queryproductWithunittype($queryString, $productid, 1);
//
//                $storedetail->unittype = $productdata->productquantity + 0;
                $storedetail->unittype = $storedetail->productquantity;
                // print_r( '<br>unittype'. $storedetail->unittype);
            }

            //$myproduct = $myProductRecord->load($storedetail->productid);
            if ($Programsettingdata->lastprice == "0") {
                if ($storedetail->lastprice == NULL) {
                    $storedetail->lastprice = $storedetail->productBuyPrice;
                }

                $productBuyPrice = round($buyprice, 2);
            } else {
                if ($storedetail->meanbuyprice == NULL || $storedetail->meanbuyprice == 0) {
                    $storedetail->meanbuyprice = $storedetail->productBuyPrice;
                }
                $productBuyPrice = round($buyprice, 2);
            }
            #apply cat discount
            $discounttype = $storedetail->discounttype;
            $buydiscount = $storedetail->buydiscount;
            if ($discounttype == 0) { //خصم مباشر
                $productBuyPrice = $productBuyPrice - $buydiscount;
            } else { //خصم نسبة
                $productBuyPrice = $productBuyPrice - (( $buydiscount / 100) * $productBuyPrice);
            }

            $storedetail->productBuyPrice = $productBuyPrice;



            ///////////To show product category name (the product whole path)
            $parentId = $storedetail->productCatId;


            //new product name with all path

            if ($_SESSION['hidecat'] == 1) {

                //names of product's parents
                //$pathArr = getProductPath_recursive($parentId, $categories);
                $pathArr = $storedetail->productCatName;
                $storedetail->productName = $pathArr . '/' . $storedetail->productName;
            } else {

                $storedetail->productName = $storedetail->productName;
            }

            if ($storedetail->isOptic == 2) {
                //$productWithColor = $productExt->queryByProductCatIdWithCount($storedetail->productid);
                $productWithColor = $opticDetails[$storedetail->productCatId . ',' . $storedetail->storeid];
                $storedetail->productDataSAC = '[]';
                $storedetail->productDataING = '[]';
                $storedetail->productquantity = 0;
                $i = 0;
                foreach ($productWithColor as $sizeColor) {
                    $storedetail->productquantity += $sizeColor->sumProductQuantity;
                    if ($sizeColor->productId != $productId && $productId > 0) {
                        unset($productWithColor[$i]);
                    }
                    $i++;
                }
                $storedetail->productquantity2 = 0; //this calculate for selected color only
                //                foreach ($productWithColor as $sizeColor) {
                //                    $storedetail->productquantity2 += $sizeColor->sumProductQuantity;
                //                }
                $storedetail->productDataSOC = json_encode($productWithColor);
                ##price
                //$prices = $productExt->getPriceOfOptic($storedetail->productid); //$storedetail->productid this is the category that holds colors of product
                $storedetail->productBuyPrice = $productWithColor[0]->productBuyPrice; //$prices->productBuyPrice;
                $storedetail->lastbuyprice = $productWithColor[0]->lastbuyprice; //$prices->lastbuyprice;
                $storedetail->meanbuyprice = $productWithColor[0]->meanbuyprice; //$prices->meanbuyprice;
                $storedetail->lastbuyprice_withDiscount = $productWithColor[0]->lastbuyprice_withDiscount; //$prices->lastbuyprice_withDiscount;
                $storedetail->meanbuyprice_withDiscount = $productWithColor[0]->meanbuyprice_withDiscount; //$prices->meanbuyprice_withDiscount;
                $storedetail->overAllAveragePrice = $productWithColor[0]->overAllAveragePrice; //$prices->overAllAveragePrice;

                $productBuyPrice = 0;
                switch ($Programsettingdata->Inventoryevaluation) {
                    case "first":
                        $productBuyPrice = (float) $storedetail->productBuyPrice;
                        break;
                    case "last":
                        $productBuyPrice = (float) $storedetail->lastbuyprice;
                        break;
                    case "mean":
                        $productBuyPrice = (float) $storedetail->meanbuyprice;
                        break;
                    case "last_discount":
                        $productBuyPrice = (float) $storedetail->lastbuyprice_withDiscount;
                        break;
                    case "mean_discount":
                        $productBuyPrice = (float) $storedetail->meanbuyprice_withDiscount;
                        break;
                    case "generalPrice":
                        $productBuyPrice = (float) $storedetail->overAllAveragePrice;
                        break;
                    case "tax":
                        $productBuyPrice = (float) $storedetail->lastbuyprice_withTax;
                        break;
                    case "mean_tax":
                        $productBuyPrice = (float) $storedetail->meanbuyprice_withTax;
                        break;
                }
            } elseif ($storedetail->hasSizeAndColor == 1) {
//                $queryString = '';
//                if ($sizeId > 0 && $colorId > 0) {
//                    $queryString = " and  sizecolorstoredetail.sizeid = $sizeId  and  sizecolorstoredetail.colorid = $colorId ";
//                }
//                $storedetail->productDataSAC = json_encode($sizeColorStoreDetailEX->queryByProductidAndStoreIdEX($storedetail->productid, $storedetail->storeid, $queryString));
                $storedetail->productquantity = 0;
                foreach ($SCProductsDetails[$storedetail->productId . ',' . $storedetail->storeid] as $sizeColor) {
                    $storedetail->productquantity += $sizeColor->quantity;
                }
                $storedetail->productDataSAC = json_encode($SCProductsDetails[$storedetail->productId . ',' . $storedetail->storeid]);
                $storedetail->productDataSOC = '';
                $storedetail->productDataING = '[]';
            } else {
                //$ingridients = $productIngredientsEX->queryAllProductIngridientsEX($storedetail->productid);
                $ingridients = $collectiveProductDetails[$storedetail->productId];
                if (!isset($ingridients))
                    $ingridients = array();

                $storedetail->productDataING = json_encode($ingridients);
                $storedetail->productDataSAC = '[]';
                $storedetail->productDataSOC = '';
            }

            //            if ($storedetail->isOptic == 2) {
            //                $SumProductPrice = $productBuyPrice * $storedetail->productquantity2;
            //            } else {
            //                $SumProductPrice = $productBuyPrice * $storedetail->productquantity;
            //            }
            $SumProductPrice = $productBuyPrice * $storedetail->productquantity;
            $sumValue = $SumProductPrice + $sumValue;

            /// print_r( '<br>unittype'. $storedetail->unittype);
        }
    }
    // search by category
    else {
        $sumValue = 0;
        $queryString1 = '';
        $allQuantity = 0;

        if (isset($storeId) && $storeId != '-1') {
            $queryString1 .= 'AND  storedetail.storeid = ' . $storeId . '   ';
            //$message = $message . "    والمخزن : " . $mystordata->storeName . "";
        }

        ##1 cat selected,no product
        if (isset($productCatId) && !empty($productCatId) && $productCatId != -1 && (empty($productId) || $productId == -1)) {
            $catsIDS = $productCatId;
            $x = getAllSubCat($productCatId); //mode = 1 get all sub cats
            $x = ltrim($x, ',');

            $productsOfCat = $productExt->queryByProductCatIdInNotService($x);
            //  print_r($productsOfCat);
            $IDS = '0';
            foreach ($productsOfCat as $value) {
                $IDS .= ',' . $value->productId;
            }
            $queryString1 .= 'and   product.productId   in (' . $IDS . ') ';



            ##msg
            $myProductCatData = $productCatDAO->load($productCatId);
            $message = $message . $myProductCatData->productCatName;
        }
        ##2 cat selected, product selected
        elseif (isset($productCatId) && !empty($productCatId) && $productCatId != -1 && isset($productId) && !empty($productId) && $productId != -1) {

            //$product_IDS = $myProductRecord->queryByProductCatId($productId);
            $product_IDS = $productExt->queryByProductCatIdIncludingOptics($productCatId);
            if (!empty($product_IDS)) {
                foreach ($product_IDS as $value) {
                    $IDS .= ',' . $value->productId;
                }
                $IDS = ltrim($IDS, ',');
                $queryString1 .= 'and  product.productId  in (' . $IDS . ') ';
            } else {
                $queryString1 .= 'and  product.productId  in (' . $productId . ') ';
            }


            ##msg
            $myProductCatData = $productCatDAO->load($productCatId);
            $message = $message . $myProductCatData->productCatName;
        }
        ##3 no cat,no product
        elseif ((!isset($productCatId) || empty($productCatId) || $productCatId != -1) && (!isset($productId) || empty($productId) || $productId != -1)) {
            $queryString1 .= ' and product.isService = 0 ';
        }

        ##cotinue with msg
        if (isset($storeId) && $storeId != '-1') {
            $message = $message . "    والمخزن : " . $mystordata->storeName . "";
        }


        ##get result
        $storedetailData2 = $myStoredetailEx->queryWithqueryString2andunittypeNoSumNoGroup($queryString1, $order, $unittype);
        $storedetailData2Arr = array();
        foreach ($storedetailData2 as $storedetail) {
            if ($storedetail->isOptic == 2) {
                $storedetail->productid = $storedetail->productCatId;
                $cat = $productCatDAO->load($storedetail->productCatParent);
                $storedetail->productCatId = $cat->productCatId;
                $storedetail->productCatName = $cat->productCatName;
            }
            switch ($Programsettingdata->Inventoryevaluation) {
                case "first":
                    $buyprice = (float) $storedetail->productBuyPrice;
                    break;
                case "last":
                    $buyprice = (float) $storedetail->lastbuyprice;
                    break;
                case "mean":
                    $buyprice = (float) $storedetail->meanbuyprice;
                    break;
                case "last_discount":
                    $buyprice = (float) $storedetail->lastbuyprice_withDiscount;
                    break;
                case "mean_discount":
                    $buyprice = (float) $storedetail->meanbuyprice_withDiscount;
                    break;
                case "generalPrice":
                    $buyprice = (float) $storedetail->overAllAveragePrice;
                    break;
                case "tax":
                    $buyprice = (float) $storedetail->lastbuyprice_withTax;
                    break;
                case "mean_tax":
                    $buyprice = (float) $storedetail->meanbuyprice_withTax;
                    break;
            }

            $allQuantity = $allQuantity + $storedetail->totQty;

            if ($Programsettingdata->scunitname != '0') {
                $productid = $storedetail->productid;
                $productdata = $myStoredetailEx->queryproductWithunittype($queryString1, $productid, 1);

                $storedetail->unittype = $productdata->productquantity + 0;
                // print_r( '<br>unittype'. $storedetail->unittype);
            }

            //$myproduct = $myProductRecord->load($storedetail->productid);
            if ($Programsettingdata->lastprice == "0") {
                if ($storedetail->lastprice == NULL) {
                    $storedetail->lastprice = $storedetail->productBuyPrice;
                }

                $productBuyPrice = round($buyprice, 2);
            } else {
                if ($storedetail->meanbuyprice == NULL || $storedetail->meanbuyprice == 0) {
                    $storedetail->meanbuyprice = $storedetail->productBuyPrice;
                }
                $productBuyPrice = round($buyprice, 2);
            }
            $storedetail->productBuyPrice = $productBuyPrice;
            ##price
            if ($storedetail->isOptic == 2) {
                $prices = $productExt->getPriceOfOptic($storedetail->productid); //$storedetail->productid this is the category that holds colors of product
                $storedetail->productBuyPrice = $prices->productBuyPrice;
                $storedetail->lastbuyprice = $prices->lastbuyprice;
                $storedetail->meanbuyprice = $prices->meanbuyprice;
                $storedetail->lastbuyprice_withDiscount = $prices->lastbuyprice_withDiscount;
                $storedetail->meanbuyprice_withDiscount = $prices->meanbuyprice_withDiscount;
                $storedetail->overAllAveragePrice = $prices->overAllAveragePrice;

                $productBuyPrice = 0;
                switch ($Programsettingdata->Inventoryevaluation) {
                    case "first":
                        $productBuyPrice = (float) $storedetail->productBuyPrice;
                        break;
                    case "last":
                        $productBuyPrice = (float) $storedetail->lastbuyprice;
                        break;
                    case "mean":
                        $productBuyPrice = (float) $storedetail->meanbuyprice;
                        break;
                    case "last_discount":
                        $productBuyPrice = (float) $storedetail->lastbuyprice_withDiscount;
                        break;
                    case "mean_discount":
                        $productBuyPrice = (float) $storedetail->meanbuyprice_withDiscount;
                        break;
                    case "generalPrice":
                        $productBuyPrice = (float) $storedetail->overAllAveragePrice;
                        break;
                }
            }
            $productQuantity = $storedetail->productquantity;
            $SumProductPrice = $productBuyPrice * $productQuantity;

            $sumValue = $SumProductPrice + $sumValue;
            $storedetail->catTotal = $SumProductPrice;
            if (!isset($storedetailData2Arr[$storedetail->productCatId])) {
                $storedetailData2Arr[$storedetail->productCatId] = $storedetail;
            } else {
                $storedetailData2Arr[$storedetail->productCatId]->totQty += $storedetail->totQty;
                $storedetailData2Arr[$storedetail->productCatId]->productquantity += $storedetail->productquantity;
                $storedetailData2Arr[$storedetail->productCatId]->catTotal += $storedetail->catTotal;
            }
        }
        $storedetailData2 = $storedetailData2Arr;



        $smarty->assign('productquantity', $allQuantity);
        $smarty->assign('message', $message);
    }



    $smarty->assign('storedetailData', $storedetailData);
    //    var_dump($storedetailData);
    //    var_dump($sumValue);
    //    var_dump($storedetailData2);
    return array($storedetailData, $sumValue, $storedetailData2);
}

function showStoreSizeAndColor() {
    global $smarty;
    //to use the variable out side the funcion
    global $myStoredetailEx;
    global $ProgramsettingDAO;
    global $buyBillDetail;
    global $buyBillDetailDAO;
    global $buyBillDetailExt;
    global $returnBuyBillDetail;
    global $returnBuyBillDetailDAO;
    global $returnBuyBillDetailExt;
    global $myStoreRecord;
    global $myProductRecord;
    global $productCatDAO;
    global $sellbilldetailEX;
    global $productExt;
    global $sizeColorStoreDetailEX;

    global $Programsettingdata;

    include_once("../public/authentication.php");
    $storeId = $_REQUEST['storeId'];
    //    $productCatId = $_REQUEST['productCatId0'];
    $order = $_REQUEST["order"];
    $counter = $_POST['counter'];
    $proIsOptic = (int) $_POST['proIsOptic'];
    $childCast = $_POST["productChild" . ($counter - 1)];
    $productId = $_POST["productId" . $counter];
    $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));
    }
    $sizeId = $colorId = 0;
    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
        $sizeId = $productIdComplex[1];
        $colorId = $productIdComplex[2];
    }

    // print_r($childCast . '<br>');
    $searchType = filter_input(INPUT_POST, 'search');
    $queryString = '';
    $message = "تقرير بضاعة أول مدة : ";
    $mystordata = $myStoreRecord->load($storeId);
    if ($searchType == 0) {

        if (isset($productId) && $productId != '-1' && $productId != '') {
            // print_r($productId . 'aaaaaaaaaaa' . $storeId . 'bbbbbbbbbbbbbbbbb' . $productCatId . 'ccccccccccccccccccc' . $order);

            $myprodactdata = $myProductRecord->load($productId);

            $message = $message . " للمنتج  :" . $myprodactdata->productName . "  ";

            $queryString .= ' AND product.productId = ' . $productId;
        } else if (isset($productCatId) && $productCatId != '-1') {
            if (isset($childCast) && !empty($childCast) && $childCast != -1 && isset($productCatId) && !empty($productCatId) && $productCatId != -1 && (empty($productId) || $productId == -1)) {
                $catIds = getAllSubCat($childCast);
                $catIds = ltrim($catIds, ',');
                $productsOfCat = $productExt->queryByProductCatIdInNotService($catIds);
                $IDS = '0';
                foreach ($productsOfCat as $value) {
                    $IDS .= ',' . $value->productId;
                }
                $queryString .= ' AND product.productId in (' . $IDS . ')';
            } else {
                $catIds = getAllSubCat($productCatId);
                $catIds = ltrim($catIds, ',');
                $catIds = $catIds . ',' . $productCatId;
                $productsOfCat = $productExt->queryByProductCatIdInNotService($catIds);
                $IDS = '0';
                foreach ($productsOfCat as $value) {
                    $IDS .= ',' . $value->productId;
                }
                $queryString .= ' AND product.productId in (' . $IDS . ')';
            }

            $myProductCatData = $productCatDAO->load($productCatId);
            $message = $message . $myProductCatData->productCatName;
        }

        if (isset($storeId) && $storeId != '-1') {
            $queryString .= ' AND sizecolorstoredetail.storeid = ' . $storeId;
            $message = $message . "    والمخزن : " . $mystordata->storeName . "";
        }
        if ($sizeId > 0 && $colorId > 0) {
            $queryString .= " and  sizecolorstoredetail.sizeid = $sizeId  and  sizecolorstoredetail.colorid = $colorId ";
        }

        //select all data from storedetail by productId
        $storedetailData = $sizeColorStoreDetailEX->queryAllGeneralQueryString($queryString);
        // print_r($message);
        $smarty->assign('message', $message);
        $sumValue = 0;
        foreach ($storedetailData as $storedetail) {
            switch ($Programsettingdata->Inventoryevaluation) {
                case "first":
                    $buyprice = (float) $storedetail->productBuyPrice;
                    break;
                case "last":
                    $buyprice = (float) $storedetail->lastbuyprice;
                    break;
                case "mean":
                    $buyprice = (float) $storedetail->meanbuyprice;
                    break;
                case "last_discount":
                    $buyprice = (float) $storedetail->lastbuyprice_withDiscount;
                    break;
                case "mean_discount":
                    $buyprice = (float) $storedetail->meanbuyprice_withDiscount;
                    break;
                case "generalPrice":
                    $buyprice = (float) $storedetail->overAllAveragePrice;
                    break;
                case "tax":
                    $buyprice = (float) $storedetail->lastbuyprice_withTax;
                    break;
                case "mean_tax":
                    $buyprice = (float) $storedetail->meanbuyprice_withTax;
                    break;
            }

            //$myproduct = $myProductRecord->load($storedetail->productid);
            if ($Programsettingdata->lastprice == "0") {
                if ($storedetail->lastprice == NULL) {
                    $storedetail->lastprice = $storedetail->productBuyPrice;
                }

                $productBuyPrice = round($buyprice, 2);
            } else {
                if ($storedetail->meanbuyprice == NULL || $storedetail->meanbuyprice == 0) {
                    $storedetail->meanbuyprice = $storedetail->productBuyPrice;
                }
                $productBuyPrice = round($buyprice, 2);
            }
            $storedetail->productBuyPrice = $productBuyPrice;

            ///////////To show product category name (the product whole path)
            $parentId = $storedetail->productCatId;


            //new product name with all path
            if ($_SESSION['hidecat'] == 1) {
                //names of product's parents
                $pathArr = getProductPath_recursive($parentId, $categories);
                $storedetail->productName = $pathArr . '/' . $storedetail->productName;
            }

            $SumProductPrice = $productBuyPrice * $storedetail->quantity;
            $sumValue = $SumProductPrice + $sumValue;

            /// print_r( '<br>unittype'. $storedetail->unittype);
        }
    }
    // search by category i didnot do the logic
    /* else {
      $sumValue = 0;
      $queryString1 = '';
      $allQuantity = 0;

      if (isset($childCast) && !empty($childCast) && $childCast != -1 && isset($productCatId) && !empty($productCatId) && $productCatId != -1 && (empty($productId) || $productId == -1)) {
      $x = getAllSubCat($childCast); //mode = 1 get all sub cats
      $x = ltrim($x, ',');

      $productsOfCat = $productExt->queryByProductCatIdInNotService($x);
      //              print_r($productsOfCat);
      $IDS = '0';
      foreach ($productsOfCat as $value) {
      $IDS .= ',' . $value->productId;
      }
      $queryString1 .= 'and   product.productId  in (' . $IDS . ') ';
      $storedetailData2 = $myStoredetailEx->queryWithqueryString2andunittype($queryString1, $order, $unittype);

      // $sellBillData = $sellbilldetailEX->queryAllGeneralGrouped($queryString1);
      foreach ($storedetailData2 as $storedetail) {

      switch ($Programsettingdata->Inventoryevaluation) {
      case "first":
      $buyprice = (float) $storedetail->productBuyPrice;
      break;
      case "last":
      $buyprice = (float) $storedetail->lastbuyprice;
      break;
      case "mean":
      $buyprice = (float) $storedetail->meanbuyprice;
      break;
      case "last_discount":
      $buyprice = (float) $storedetail->lastbuyprice_withDiscount;
      break;
      case "mean_discount":
      $buyprice = (float) $storedetail->meanbuyprice_withDiscount;
      break;
      case "generalPrice":
      $buyprice = (float) $storedetail->overAllAveragePrice;
      break;
      }

      $allQuantity = $allQuantity + $storedetail->totQty;

      if ($Programsettingdata->scunitname != '0') {
      $productid = $storedetail->productid;
      $productdata = $myStoredetailEx->queryproductWithunittype($queryString1, $productid, 1);

      $storedetail->unittype = $productdata->productquantity + 0;
      // print_r( '<br>unittype'. $storedetail->unittype);
      }

      //$myproduct = $myProductRecord->load($storedetail->productid);
      if ($Programsettingdata->lastprice == "0") {
      if ($storedetail->lastprice == NULL) {
      $storedetail->lastprice = $storedetail->productBuyPrice;
      }

      $productBuyPrice = round($buyprice, 2);
      } else {
      if ($storedetail->meanbuyprice == NULL || $storedetail->meanbuyprice == 0) {
      $storedetail->meanbuyprice = $storedetail->productBuyPrice;
      }
      $productBuyPrice = round($buyprice, 2);
      }
      $storedetail->productBuyPrice = $productBuyPrice;

      $productQuantity = $storedetail->productquantity;
      $SumProductPrice = $productBuyPrice * $productQuantity;

      $sumValue = $SumProductPrice + $sumValue;
      }
      $myProductCatData = $productCatDAO->load($childCast);
      $message = $message . $myProductCatData->productCatName;
      } elseif (isset($childCast) && !empty($childCast) && $childCast != -1 && isset($productId) && !empty($productId) && $productId != -1) {
      $queryString1 .= 'and   product.productId  in (' . $productId . ') ';
      $storedetailData2 = $myStoredetailEx->queryWithqueryString2andunittype($queryString1, $order, $unittype);
      //$sellBillData = $sellbilldetailEX->queryAllGeneralGrouped($queryString1);
      foreach ($storedetailData2 as $storedetail) {

      switch ($Programsettingdata->Inventoryevaluation) {
      case "first":
      $buyprice = (float) $storedetail->productBuyPrice;
      break;
      case "last":
      $buyprice = (float) $storedetail->lastbuyprice;
      break;
      case "mean":
      $buyprice = (float) $storedetail->meanbuyprice;
      break;
      case "last_discount":
      $buyprice = (float) $storedetail->lastbuyprice_withDiscount;
      break;
      case "mean_discount":
      $buyprice = (float) $storedetail->meanbuyprice_withDiscount;
      break;
      case "generalPrice":
      $buyprice = (float) $storedetail->overAllAveragePrice;
      break;
      }

      $allQuantity = $allQuantity + $storedetail->totQty;

      if ($Programsettingdata->scunitname != '0') {
      $productid = $storedetail->productid;
      $productdata = $myStoredetailEx->queryproductWithunittype($queryString1, $productid, 1);

      $storedetail->unittype = $productdata->productquantity + 0;
      // print_r( '<br>unittype'. $storedetail->unittype);
      }

      //$myproduct = $myProductRecord->load($storedetail->productid);
      if ($Programsettingdata->lastprice == "0") {
      if ($storedetail->lastprice == NULL) {
      $storedetail->lastprice = $storedetail->productBuyPrice;
      }

      $productBuyPrice = round($buyprice, 2);
      } else {
      if ($storedetail->meanbuyprice == NULL || $storedetail->meanbuyprice == 0) {
      $storedetail->meanbuyprice = $storedetail->productBuyPrice;
      }
      $productBuyPrice = round($buyprice, 2);
      }
      $storedetail->productBuyPrice = $productBuyPrice;

      $productQuantity = $storedetail->productquantity;
      $SumProductPrice = $productBuyPrice * $productQuantity;

      $sumValue = $SumProductPrice + $sumValue;
      }
      $myProductCatData = $productCatDAO->load($childCast);
      $message = $message . $myProductCatData->productCatName;

      $myprodactdata = $myProductRecord->load($productId);
      $message = $message . " للمنتج  :" . $myprodactdata->productName . "  ";
      } elseif (isset($productCatId) && !empty($productCatId) && $productCatId != -1 && empty($childCast) && empty($productId)) {
      $lastLevelCatIDS = '';
      $x = getAllSubCat($productCatId); //mode = 1 get all sub cats
      $x = ltrim($x, ',');

      $productsOfCat = $productExt->queryByProductCatIdInNotService($x);
      //  print_r($productsOfCat);
      $IDS = '0';
      foreach ($productsOfCat as $value) {
      $IDS .= ',' . $value->productId;
      }
      $queryString1 .= 'and   product.productId   in (' . $IDS . ') ';
      $storedetailData2 = $myStoredetailEx->queryWithqueryString2andunittype($queryString1, $order, $unittype);

      //$sellBillData = $sellbilldetailEX->queryAllGeneralGrouped($queryString1);
      foreach ($storedetailData2 as $storedetail) {

      switch ($Programsettingdata->Inventoryevaluation) {
      case "first":
      $buyprice = (float) $storedetail->productBuyPrice;
      break;
      case "last":
      $buyprice = (float) $storedetail->lastbuyprice;
      break;
      case "mean":
      $buyprice = (float) $storedetail->meanbuyprice;
      break;
      case "last_discount":
      $buyprice = (float) $storedetail->lastbuyprice_withDiscount;
      break;
      case "mean_discount":
      $buyprice = (float) $storedetail->meanbuyprice_withDiscount;
      break;
      case "generalPrice":
      $buyprice = (float) $storedetail->overAllAveragePrice;
      break;
      }

      $allQuantity = $allQuantity + $storedetail->totQty;

      if ($Programsettingdata->scunitname != '0') {
      $productid = $storedetail->productid;
      $productdata = $myStoredetailEx->queryproductWithunittype($queryString1, $productid, 1);

      $storedetail->unittype = $productdata->productquantity + 0;
      // print_r( '<br>unittype'. $storedetail->unittype);
      }

      //$myproduct = $myProductRecord->load($storedetail->productid);
      if ($Programsettingdata->lastprice == "0") {
      if ($storedetail->lastprice == NULL) {
      $storedetail->lastprice = $storedetail->productBuyPrice;
      }

      $productBuyPrice = round($buyprice, 2);
      } else {
      if ($storedetail->meanbuyprice == NULL || $storedetail->meanbuyprice == 0) {
      $storedetail->meanbuyprice = $storedetail->productBuyPrice;
      }
      $productBuyPrice = round($buyprice, 2);
      }
      $storedetail->productBuyPrice = $productBuyPrice;

      $productQuantity = $storedetail->productquantity;
      $SumProductPrice = $productBuyPrice * $productQuantity;

      $sumValue = $SumProductPrice + $sumValue;
      }
      $myProductCatData = $productCatDAO->load($productCatId);
      $message = $message . $myProductCatData->productCatName;
      } elseif (isset($productCatId) && !empty($productCatId) && $productCatId != -1 && empty($childCast) && $productId == -1) {
      $lastLevelCatIDS = '';
      $x = getAllSubCat($productCatId); //mode = 1 get all sub cats
      $x = ltrim($x, ',');

      $productsOfCat = $productExt->queryByProductCatIdInNotService($x);
      //  print_r($productsOfCat);
      $IDS = '0';
      foreach ($productsOfCat as $value) {
      $IDS .= ',' . $value->productId;
      }
      $queryString1 .= 'and  product.productId   in (' . $IDS . ') ';
      $storedetailData2 = $myStoredetailEx->queryWithqueryString2andunittype($queryString1, $order, $unittype);

      //$sellBillData = $sellbilldetailEX->queryAllGeneralGrouped($queryString1);
      foreach ($storedetailData2 as $storedetail) {

      switch ($Programsettingdata->Inventoryevaluation) {
      case "first":
      $buyprice = (float) $storedetail->productBuyPrice;
      break;
      case "last":
      $buyprice = (float) $storedetail->lastbuyprice;
      break;
      case "mean":
      $buyprice = (float) $storedetail->meanbuyprice;
      break;
      case "last_discount":
      $buyprice = (float) $storedetail->lastbuyprice_withDiscount;
      break;
      case "mean_discount":
      $buyprice = (float) $storedetail->meanbuyprice_withDiscount;
      break;
      case "generalPrice":
      $buyprice = (float) $storedetail->overAllAveragePrice;
      break;
      }


      $allQuantity = $allQuantity + $storedetail->totQty;

      if ($Programsettingdata->scunitname != '0') {
      $productid = $storedetail->productid;
      $productdata = $myStoredetailEx->queryproductWithunittype($queryString1, $productid, 1);

      $storedetail->unittype = $productdata->productquantity + 0;
      // print_r( '<br>unittype'. $storedetail->unittype);
      }

      //$myproduct = $myProductRecord->load($storedetail->productid);
      if ($Programsettingdata->lastprice == "0") {
      if ($storedetail->lastprice == NULL) {
      $storedetail->lastprice = $storedetail->productBuyPrice;
      }

      $productBuyPrice = round($buyprice, 2);
      } else {
      if ($storedetail->meanbuyprice == NULL || $storedetail->meanbuyprice == 0) {
      $storedetail->meanbuyprice = $storedetail->productBuyPrice;
      }
      $productBuyPrice = round($buyprice, 2);
      }
      $storedetail->productBuyPrice = $productBuyPrice;

      $productQuantity = $storedetail->productquantity;
      $SumProductPrice = $productBuyPrice * $productQuantity;

      $sumValue = $SumProductPrice + $sumValue;
      }
      $myProductCatData = $productCatDAO->load($productCatId);
      $message = $message . $myProductCatData->productCatName . " والمخزن " . $mystordata->storeName . "";
      } elseif (isset($productCatId) && !empty($productCatId) && $productCatId != -1 && isset($productId) && !empty($productId) && $productId != -1) {

      $product_IDS = $myProductRecord->queryByProductCatId($productId);
      if (!empty($product_IDS)) {
      foreach ($product_IDS as $value) {
      $IDS .= ',' . $value->productId;
      }
      $IDS = ltrim($IDS, ',');
      $queryString1 .= 'and  product.productId  in (' . $IDS . ') ';
      } else {
      $queryString1 .= 'and  product.productId  in (' . $productId . ') ';
      }




      $storedetailData2 = $myStoredetailEx->queryWithqueryString2andunittype($queryString1, $order, $unittype);

      //$sellBillData = $sellbilldetailEX->queryAllGeneralGrouped($queryString1);
      foreach ($storedetailData2 as $storedetail) {

      switch ($Programsettingdata->Inventoryevaluation) {
      case "first":
      $buyprice = (float) $storedetail->productBuyPrice;
      break;
      case "last":
      $buyprice = (float) $storedetail->lastbuyprice;
      break;
      case "mean":
      $buyprice = (float) $storedetail->meanbuyprice;
      break;
      case "last_discount":
      $buyprice = (float) $storedetail->lastbuyprice_withDiscount;
      break;
      case "mean_discount":
      $buyprice = (float) $storedetail->meanbuyprice_withDiscount;
      break;
      case "generalPrice":
      $buyprice = (float) $storedetail->overAllAveragePrice;
      break;
      }
      $allQuantity = $allQuantity + $storedetail->totQty;

      if ($Programsettingdata->scunitname != '0') {
      $productid = $storedetail->productid;
      $productdata = $myStoredetailEx->queryproductWithunittype($queryString1, $productid, 1);

      $storedetail->unittype = $productdata->productquantity + 0;
      // print_r( '<br>unittype'. $storedetail->unittype);
      }

      //$myproduct = $myProductRecord->load($storedetail->productid);
      if ($Programsettingdata->lastprice == "0") {
      if ($storedetail->lastprice == NULL) {
      $storedetail->lastprice = $storedetail->productBuyPrice;
      }

      $productBuyPrice = round($buyprice, 2);
      } else {
      if ($storedetail->meanbuyprice == NULL || $storedetail->meanbuyprice == 0) {
      $storedetail->meanbuyprice = $storedetail->productBuyPrice;
      }
      $productBuyPrice = round($buyprice, 2);
      }
      $storedetail->productBuyPrice = $productBuyPrice;

      $productQuantity = $storedetail->productquantity;
      $SumProductPrice = $productBuyPrice * $productQuantity;

      $sumValue = $SumProductPrice + $sumValue;
      }
      $myProductCatData = $productCatDAO->load($productCatId);
      $message = $message . $myProductCatData->productCatName;
      }

      if (isset($storeId) && $storeId != '-1') {
      $queryString1 .= 'AND  storedetail.storeid = ' . $storeId . '   ';

      $message = $message . "    والمخزن : " . $mystordata->storeName . "";
      }
      $smarty->assign('productquantity', $allQuantity);
      $smarty->assign('message', $message);
      } */



    $smarty->assign('storedetailData', $storedetailData);
    //    var_dump($storedetailData);
    //    var_dump($sumValue);
    //    var_dump($storedetailData2);
    return array($storedetailData, $sumValue); //$storedetailData2
}

function getAllSubCat($catid) {
    global $productCatExt;
    global $productCatDAO;
    global $catsIDS;


    // print_r('<br>' . $catid . '<br>');
    $result = $productCatExt->queryByParentExt($catid);
    // print_r($result);
    // print_r($lastLevelCatIDS);

    if (count($result) > 0) {
        foreach ($result as $data) {


            $catsIDS .= "," . $data->productCatId;
            // print_r($catsIDS . '<br>');
            getAllSubCat($data->productCatId);
        }
    } else {
        $catsIDS .= ',' . $catid;
    }
    return $catsIDS;
}

// show the form by product name
function showByProductNameAndStore() {
    global $myStoredetailEx;
    global $ProgramsettingDAO;
    global $buyBillDetail;
    global $buyBillDetailDAO;
    global $buyBillDetailExt;
    global $returnBuyBillDetail;
    global $returnBuyBillDetailDAO;
    global $returnBuyBillDetailExt;
    global $myProductRecord;
    global $Programsettingdata;

    $productId = $_REQUEST['productId'];
    $storeId = $_REQUEST['storeId'];

    //select all data from storedetail by productId
    $storedetailData = $myStoredetailEx->queryWithProductIdAndStoreId($productId, $storeId);

    $sumValue = 0;
    foreach ($storedetailData as $storedetail) {
        $myproduct = $myProductRecord->load($storedetail->productid);
        switch ($Programsettingdata->Inventoryevaluation) {
            case "first":
                $buyprice = (float) $myproduct->productBuyPrice;
                break;
            case "last":
                $buyprice = (float) $myproduct->lastbuyprice;
                break;
            case "mean":
                $buyprice = (float) $myproduct->meanbuyprice;
                break;
            case "last_discount":
                $buyprice = (float) $myproduct->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyprice = (float) $myproduct->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyprice = (float) $myproduct->overAllAveragePrice;
                break;
            case "tax":
                $buyprice = (float) $myproduct->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $buyprice = (float) $myproduct->meanbuyprice_withTax;
                break;
        }


        if ($Programsettingdata->lastprice == "0") {
            if ($myproduct->lastprice == NULL) {
                $myproduct->lastprice = $myproduct->productBuyPrice;
            }
            $productBuyPrice = $buyprice;
            /* $buylastprice = $buyBillDetailDAO->queryByBuybilldetailproductid($storedetail->productid);
              if (count($buylastprice) != "0") {
              $storedetail->productBuyPrice = $buylastprice[0]->buybilldetailprice;
              } */
        } else {
            if ($myproduct->meanbuyprice == NULL || $myproduct->meanbuyprice == 0) {
                $myproduct->meanbuyprice = $myproduct->productBuyPrice;
            }
            $productBuyPrice = $buyprice;
        }
        $storedetail->productBuyPrice = $productBuyPrice;
        $productQuantity = $storedetail->productquantity;
        $SumProductPrice = $productBuyPrice * $productQuantity;

        $sumValue = $SumProductPrice + $sumValue;

        ///////////To show product category name (the product whole path)
        $parentId = $storedetail->productCatId;
        //names of product's parents
        $pathArr = getProductPath_recursive($parentId, $categories);

        //new product name with all path
        $storedetail->productName = $storedetail->productName . '/' . $pathArr;
    }

    return array($storedetailData, $sumValue);
}

// show the form by store Name
function showBystoreName() {
    global $myStoredetailEx;

    global $ProgramsettingDAO;
    global $buyBillDetail;
    global $buyBillDetailDAO;
    global $buyBillDetailExt;
    global $returnBuyBillDetail;
    global $returnBuyBillDetailDAO;
    global $returnBuyBillDetailExt;
    global $myProductRecord;
    global $Programsettingdata;



    $storeId = $_REQUEST['storeId'];

    $storedetailData = $myStoredetailEx->queryWithStoreId($storeId);


    $sumValue = 0;
    foreach ($storedetailData as $storedetail) {
        $myproduct = $myProductRecord->load($storedetail->productid);

        switch ($Programsettingdata->Inventoryevaluation) {
            case "first":
                $buyprice = (float) $myproduct->productBuyPrice;
                break;
            case "last":
                $buyprice = (float) $myproduct->lastbuyprice;
                break;
            case "mean":
                $buyprice = (float) $myproduct->meanbuyprice;
                break;
            case "last_discount":
                $buyprice = (float) $myproduct->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyprice = (float) $myproduct->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyprice = (float) $myproduct->overAllAveragePrice;
                break;
            case "tax":
                $buyprice = (float) $myproduct->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $buyprice = (float) $myproduct->meanbuyprice_withTax;
                break;
        }
        if ($Programsettingdata->lastprice == "0") {
            if ($myproduct->lastprice == NULL) {
                $myproduct->lastprice = $myproduct->productBuyPrice;
            }
            $productBuyPrice = $buyprice;
            /* $buylastprice = $buyBillDetailDAO->queryByBuybilldetailproductid($storedetail->productid);
              if (count($buylastprice) != "0") {
              $storedetail->productBuyPrice = $buylastprice[0]->buybilldetailprice;
              } */
        } else {
            if ($myproduct->meanbuyprice == NULL || $myproduct->meanbuyprice == 0) {
                $myproduct->meanbuyprice = $myproduct->productBuyPrice;
            }
            $productBuyPrice = $buyprice;
        }
        $storedetail->productBuyPrice = $productBuyPrice;
        $productQuantity = $storedetail->productquantity;
        $SumProductPrice = $productBuyPrice * $productQuantity;

        $sumValue = $SumProductPrice + $sumValue;

        ///////////To show product category name (the product whole path)
        $parentId = $storedetail->productCatId;
        //names of product's parents
        $pathArr = getProductPath_recursive($parentId, $categories);

        //new product name with all path
        $storedetail->productName = $storedetail->productName . '/' . $pathArr;
    }
    return array($storedetailData, $sumValue);
}

// show the form by product category Name
function showByProductCatNameAndStoreId() {
    global $myStoredetailEx;
    global $ProgramsettingDAO;
    global $buyBillDetail;
    global $buyBillDetailDAO;
    global $buyBillDetailExt;
    global $returnBuyBillDetail;
    global $returnBuyBillDetailDAO;
    global $returnBuyBillDetailExt;
    global $myProductRecord;
    global $Programsettingdata;

    $productCatId = $_REQUEST['productCatId'];
    $storeId = $_REQUEST['storeId'];

    if (isset($productCatId)) {
        $storedetailData = $myStoredetailEx->queryWithProductCatAndStoreId($productCatId, $storeId);

        $sumValue = 0;
        foreach ($storedetailData as $storedetail) {
            $myproduct = $myProductRecord->load($storedetail->productid);

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

            if ($Programsettingdata->lastprice == "0") {
                if ($myproduct->lastprice == NULL) {
                    $myproduct->lastprice = $myproduct->productBuyPrice;
                }
                $productBuyPrice = $buyprice;
                /* $buylastprice = $buyBillDetailDAO->queryByBuybilldetailproductid($storedetail->productid);
                  if (count($buylastprice) != "0") {
                  $storedetail->productBuyPrice = $buylastprice[0]->buybilldetailprice;
                  } */
            } else {
                if ($myproduct->meanbuyprice == NULL || $myproduct->meanbuyprice == 0) {
                    $myproduct->meanbuyprice = $myproduct->productBuyPrice;
                }
                $productBuyPrice = $buyprice;
            }

            $storedetail->productBuyPrice = $productBuyPrice;
            $productQuantity = $storedetail->productquantity;
            $SumProductPrice = $productBuyPrice * $productQuantity;

            $sumValue = $SumProductPrice + $sumValue;

            ///////////To show product category name (the product whole path)
            $parentId = $storedetail->productCatId;
            //names of product's parents
            $pathArr = getProductPath_recursive($parentId, $categories);

            //new product name with all path
            $storedetail->productName = $storedetail->productName . '/' . $pathArr;
        }
    }
    return array($storedetailData, $sumValue);
}

// show the form
function showAll() {
    global $myStoredetailEx;
    global $ProgramsettingDAO;
    global $Programsettingdata;

    $storedetailData = $myStoredetailEx->queryWithOrder();

    $sumValue = 0;
    if (count($storedetailData) > 0) {
        foreach ($storedetailData as $storedetail) {

            switch ($Programsettingdata->Inventoryevaluation) {
                case "first":
                    $buyprice = (float) $storedetail->productBuyPrice;
                    break;
                case "last":
                    $buyprice = (float) $storedetail->lastbuyprice;
                    break;
                case "mean":
                    $buyprice = (float) $storedetail->meanbuyprice;
                    break;
                case "last_discount":
                    $buyprice = (float) $storedetail->lastbuyprice_withDiscount;
                    break;
                case "mean_discount":
                    $buyprice = (float) $storedetail->meanbuyprice_withDiscount;
                    break;
                case "generalPrice":
                    $buyprice = (float) $storedetail->overAllAveragePrice;
                    break;
                case "tax":
                    $buyprice = (float) $storedetail->lastbuyprice_withTax;
                    break;
                case "mean_tax":
                    $buyprice = (float) $storedetail->meanbuyprice_withTax;
                    break;
            }
            //إجمالي سعر المنتجات
            $productBuyPrice = $buyprice;
            $productQuantity = $storedetail->productquantity;
            $SumProductPrice = $productBuyPrice * $productQuantity;

            $sumValue += $SumProductPrice;

            ///////////To show product category name (the product whole path)
            $parentId = $storedetail->productCatId;
            //names of product's parents
            $pathArr = getProductPath_recursive($parentId, $categories);

            //new product name with all path
            $storedetail->productName = $storedetail->productName . '/' . $pathArr;
        }
    }
    return array($storedetailData, $sumValue);
}

function getProductPath_recursive($parentid, $categories) {
    global $productCatExt;

    $catData = $productCatExt->getCategoryAndParentByCatId($parentid);

    if (count($catData) > 0) {
        $categories = $catData->productCatName . '/' . $categories;
        $newParentId = $catData->productCatParent;

        return getProductPath_recursive($newParentId, $categories);
    }
    $categories = substr($categories, 0, strlen($categories) - 1);
    return $categories;
}

function loadProductUnitWithProductAndUnit($productId, $unitId) {

    //to use the variable out side the funcion
    global $myProductunitEx;

    // select all data from productunit tbl
    $productunitData = $myProductunitEx->queryWithProductIdAndUnitId($productId, $unitId);

    return $productunitData;
}

function CURL_IT2($data_arr, $url) {
    ##preparing session data
    //$projectURL = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/';
    $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $url;

    ##appending necessary data
    $data_arr['curlpost'] = '1';
    $data_arr['sessionlist'] = json_encode($_SESSION);


    // set post fields
//    $post = [
//        'data_arr' => json_encode($data_arr), //encode it as it is array
//    ];
    $post = $data_arr;
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        //echo 'Error : ' . curl_error($ch);
    }

    // close the connection, release resources used
    curl_close($ch);
    // do anything you want with your response
    //var_dump($response);
    //print_r($response);
    return $response;
}

?>