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

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

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

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

$do = $_GET['do'];

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

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

  OPERTATION in Controller

  1-load save data
  2-display show form

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

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

//here goes the instances and general variables
//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();

$myUserGroup = new Usergroup();
$myUserGroupRecord = new UsergroupMySqlDAO();
$myUserGroupEx = new UsergroupMySqlExtDAO();

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


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

    $storeData = loadStore();
    $smarty->assign("storeData", $storeData);

//    $productCatData = loadProductCategories();
//    $smarty->assign("productCatData", $productCatData);
//    $productId = $_REQUEST['productId'];
//    $productCatId = $_REQUEST['productCatId'];

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

    $Programsettingdata = $ProgramsettingDAO->load(1);
    $smarty->assign("Programsettingdata", $Programsettingdata);

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


    $level = filter_input(INPUT_POST, 'level');
    $productCatId = filter_input(INPUT_POST, 'productCatId' . $level);
    if (empty($productCatId) || $productCatId == -1) {
        $productCatId = filter_input(INPUT_POST, 'productCatId' . ($level - 1));
    }
    $productId = filter_input(INPUT_POST, 'productId');
    $storeId = $_REQUEST['storeId'];
    $smarty->assign("productSellAllPrice", 1);
    $smarty->assign("story_az", 1);
    //echo "$myusergroupdata->hidecat".$myusergroupdata->hidecat;
    $smarty->assign('hidecat', $myusergroupdata->hidecat);

    /* if(isset($productId) && $productId != "-1" && $productId != "" && isset($storeId) && $storeId != "-1" )
      {
      $mystordata=$myStoreRecord->load($storeId);
      $myprodactdata=$myProductRecord->load($productId);

      $message="تقرير بضاعة أول مدة للمنتج  : ".$myprodactdata->productName."    والمخزن : ".$mystordata->storeName."";

      $smarty->assign('message',$message);
      $storedetailData=showByProductNameAndStore();
      }
      elseif(isset($productId) && $productId != "-1" && $productId != "" &&  $storeId == "-1" )
      {
      $myprodactdata=$myProductRecord->load($productId);
      $message="تقرير بضاعة أول مدة للمنتج   ".$myprodactdata->productName;
      $smarty->assign('message',$message);
      $storedetailData=showByProductName();
      }
      elseif(isset($storeId) && $storeId != "-1" && isset($productCatId) && $productCatId != '-1')
      {
      $myProductCatData=$productCatDAO->load($productCatId);
      $mystordata=$myStoreRecord->load($storeId);

      $message="تقرير بضاعة أول مدة لتصنيف المنتج  ".$myProductCatData->productCatName ." والمخزن ".$mystordata->storeName."";
      $smarty->assign('message',$message);

      $storedetailData=showByProductCatNameAndStoreId();
      }
      elseif(isset($storeId) && $storeId != '-1' &&  $productCatId == '-1')
      {
      $mystordata=$myStoreRecord->load($storeId);
      $message="تقرير بضاعة أول مدة  لمخزن   ".$mystordata->storeName;
      $smarty->assign('message',$message);

      $storedetailData=showBystoreName();
      } */
    if (isset($productId) && $productId != "-1" && $productId != "" || isset($storeId) && $storeId != "-1" || isset($productCatId) && $productCatId != "-1") {
        $storedetailData = show();
    } else {

    }
    $smarty->assign('storedetailData', $storedetailData[0]);


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


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

    include_once("../public/authentication.php");
    $productId = $_REQUEST['productId'];
    $storeId = $_REQUEST['storeId'];

    //$productCatId = $_REQUEST['productCatId'];
    $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));
    }

    $order = $_REQUEST["order"];

    $selectall = $_REQUEST["selectall"];
    $productSellUnitPrice = $_REQUEST["productSellUnitPrice"];
    $productBuyPrice = $_REQUEST["productBuyPrice"];
    $lastbuyprice = $_REQUEST["lastbuyprice"];
    $lastbuyprice_withDiscount = $_REQUEST["lastbuyprice_withDiscount"];
    $meanbuyprice = $_REQUEST["meanbuyprice"];
    $meanbuyprice_withDiscount = $_REQUEST["meanbuyprice_withDiscount"];
    $productSellAllPrice = $_REQUEST["productSellAllPrice"];
    $productSellHalfPrice = $_REQUEST["productSellHalfPrice"];
    $storename = $_REQUEST['storename'];
    $amount = $_REQUEST['amount'];
    $lastProcessDate = $_REQUEST['lastProcessDate'];
    $selldiscount = $_REQUEST['selldiscount'];
    $image = $_REQUEST['image'];
    $hideZeroQuantity = (int) $_REQUEST['hideZeroQuantity'];
    $quantityGreaterThan = $_REQUEST['quantityGreaterThan'];
    $quantityLessThan = $_REQUEST['quantityLessThan'];
    $description = $_REQUEST['description'];
    $parcodaz = $_REQUEST['parcodaz'];
    $dasta = $_REQUEST['dasta'];
    $ro3dasta = $_REQUEST['ro3dasta'];

    // Checked

    $che = array(
        'productSellUnitPrice' => $productSellUnitPrice,
        'productBuyPrice' => $productBuyPrice,
        'lastbuyprice' => $lastbuyprice,
        'lastbuyprice_withDiscount' => $lastbuyprice_withDiscount,
        'meanbuyprice' => $meanbuyprice,
        'meanbuyprice_withDiscount' => $meanbuyprice_withDiscount,
        'productSellAllPrice' => $productSellAllPrice,
        'productSellHalfPrice' => $productSellHalfPrice,
        'storename' => $storename,
        'amount' => $amount,
        'lastProcessDate' => $lastProcessDate,
        'selldiscount' => $selldiscount,
        'image' => $image,
        'hideZeroQuantity' => $hideZeroQuantity,
        'description' => $description,
        'parcodaz' => $parcodaz,
        'dasta' => $dasta,
        'ro3dasta' => $ro3dasta
    );
    $cheak = json_encode($che);
    $smarty->assign("array", $cheak);

    $str2 = '';

    if (isset($selectall) && $selectall == '1') {
        $smarty->assign("selectall", 1);
    }

    if (isset($description) && $description == '1') {
        $smarty->assign("description", 1);
    }

    if (isset($parcodaz) && $parcodaz == '1') {
        $smarty->assign("parcodaz", 1);
    }

    if (isset($dasta) && $dasta == '1') {
        $smarty->assign("dasta", 1);
    }

    if (isset($ro3dasta) && $ro3dasta == '1') {
        $smarty->assign("ro3dasta", 1);
    }

    if (isset($productSellUnitPrice) && $productSellUnitPrice == '1') {
        $str2 .= ',product.productSellUnitPrice';
    }
    $smarty->assign("productSellUnitPrice", $productSellUnitPrice);


    if (isset($productBuyPrice) && $productBuyPrice == '1') {
        $str2 .= ',product.productBuyPrice';
    }
    $smarty->assign("productBuyPrice", $productBuyPrice);

    if (isset($lastbuyprice) && $lastbuyprice == '1') {
        $str2 .= ',product.lastbuyprice';
    }
    $smarty->assign("lastbuyprice", $lastbuyprice);
    if (isset($lastbuyprice_withDiscount) && $lastbuyprice_withDiscount == '1') {
        $str2 .= ',product.lastbuyprice_withDiscount';
    }
    $smarty->assign("lastbuyprice_withDiscount", $lastbuyprice_withDiscount);
    if (isset($meanbuyprice) && $meanbuyprice == '1') {
        $str2 .= ',product.meanbuyprice';
    }
    $smarty->assign("meanbuyprice", $meanbuyprice);
    if (isset($meanbuyprice_withDiscount) && $meanbuyprice_withDiscount == '1') {
        $str2 .= ',product.meanbuyprice_withDiscount';
    }
    $smarty->assign("meanbuyprice_withDiscount", $meanbuyprice_withDiscount);


    if (isset($productSellHalfPrice) && $productSellHalfPrice == '1') {
        $str2 .= ',product.productSellHalfPrice';
    }
    $smarty->assign("productSellHalfPrice", $productSellHalfPrice);



    if (isset($productSellAllPrice) && $productSellAllPrice == '1') {
        $str2 .= ',product.productSellAllPrice';
    }

    $str2 .= ',product.logo';
    $smarty->assign("productSellAllPrice", $productSellAllPrice);



    if (isset($storename) && $storename == '1') {
        $smarty->assign("storename", 1);
    }
    $smarty->assign("storename", $storename);

    if (isset($amount) && $amount == '1') {
        $smarty->assign("amount", 1);
    }
    $smarty->assign("amount", $amount);

    if (isset($lastProcessDate) && $lastProcessDate == '1') {
        $smarty->assign("lastProcessDate", 1);
    }
    $smarty->assign("lastProcessDate", $lastProcessDate);

    if (isset($selldiscount) && $selldiscount == '1') {
        $smarty->assign("selldiscount", 1);
    }
    $smarty->assign("selldiscount", $selldiscount);

    if (isset($image) && $image == '1') {
        $smarty->assign("image", 1);
    }
    $smarty->assign("image", $image);

    if (isset($hideZeroQuantity) && $hideZeroQuantity == 1) {
        $smarty->assign("hideZeroQuantity", 1);
    }
    $smarty->assign("hideZeroQuantity", $hideZeroQuantity);

    $queryString = ' AND';
    $message = "تقرير  قائمة اسعار البضاعة : ";

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

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

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


        $queryString .= ' storedetail.productId = ' . $productId . ' AND';
    }
    if (isset($quantityGreaterThan) && $quantityGreaterThan != "") {
        $quantityGreaterThan = (float) $quantityGreaterThan;
        $queryString .= ' storedetail.productquantity >= ' . $quantityGreaterThan . ' AND';
    }
    if (isset($quantityLessThan) && $quantityLessThan != "") {
        $quantityLessThan = (float) $quantityLessThan;
        $queryString .= ' storedetail.productquantity <= ' . $quantityLessThan . ' AND';
    }

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

    if (isset($productCatId) && $productCatId != '-1') {
        $queryString .= '  product.productCatId = ' . $productCatId . ' AND';
        $myProductCatData = $productCatDAO->load($productCatId);


        $message = $message . $myProductCatData->productCatName . " والمخزن " . $mystordata->storeName . "";
    }
    if (isset($hideZeroQuantity) && $hideZeroQuantity == 1) {
        $queryString .= '  productquantity != 0 AND';
    }


    $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: ".$queryString."<br>");
    }

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

    $countproduct = count($storedetailData);
    $smarty->assign('countproduct', $countproduct);

    $smarty->assign('message', $message);
    $sumValue = 0;
    $Programsettingdata = $ProgramsettingDAO->load(1);
    foreach ($storedetailData as $storedetail) {

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

            $storedetail->productBuyPrice = $myproduct->lastbuyprice;
            /* $buylastprice = $buyBillDetailDAO->queryByBuybilldetailproductid($storedetail->productid);

              if (count($buylastprice) != "0") {

              $storedetail->productBuyPrice = $buylastprice[0]->buybilldetailprice;
              } */
        } else {
            $storedetail->productBuyPrice = $myproduct->meanbuyprice;
        }

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


        $productBuyPrice = $pro_price;
//        $productBuyPrice = $storedetail->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 = $storedetail->productName . '/' . $pathArr;
        } else {

            $storedetail->productName = $storedetail->productName;
        }
        //selldiscount
        if ($selldiscount == 1 && $storedetail->selldiscount > 0) {//want to make discount and discount value >0
            if ($storedetail->discounttype == 0) {//direct discount
                $storedetail->productSellAllPrice -= $storedetail->selldiscount;
                $storedetail->productSellHalfPrice -= $storedetail->selldiscount;
                $storedetail->productSellUnitPrice -= $storedetail->selldiscount;
            } elseif ($storedetail->discounttype == 1) {//percentage disount
                $storedetail->productSellAllPrice -= $storedetail->productSellAllPrice * ($storedetail->selldiscount / 100);
                $storedetail->productSellHalfPrice -= $storedetail->productSellHalfPrice * ($storedetail->selldiscount / 100);
                $storedetail->productSellUnitPrice -= $storedetail->productSellUnitPrice * ($storedetail->selldiscount / 100);
                //
                $storedetail->productSellAllPrice = round($storedetail->productSellAllPrice, 2);
                $storedetail->productSellHalfPrice = round($storedetail->productSellHalfPrice, 2);
                $storedetail->productSellUnitPrice = round($storedetail->productSellUnitPrice, 2);
            }
        }

// وصف المنتج
        if ($myproduct->productDescription !== null && $myproduct->productDescription !== "") {
            $storedetail->productDescription = $myproduct->productDescription;
        } else {
            $storedetail->productDescription = "لايوجد";
        }
        // نهايه وصف المنتج
        // وصف المنتج
        if ($Programsettingdata->usedParcode == 1) {//parcode is id
            $storedetail->parcode = "i" . addPreDigitsToNum($myproduct->productId);
        } else {
            $storedetail->parcode = $myproduct->parcode;
        }
        // نهايه وصف المنتج
    }
    return array($storedetailData, $sumValue);
}

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

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

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

    $sumValue = 0;
    $Programsettingdata = $ProgramsettingDAO->load(1);
    foreach ($storedetailData as $storedetail) {
        $myproduct = $myProductRecord->load($storedetail->productid);
        if ($Programsettingdata->lastprice == "0") {
            $storedetail->productBuyPrice = $myproduct->lastbuyprice;
            /* $buylastprice = $buyBillDetailDAO->queryByBuybilldetailproductid($storedetail->productid);
              if (count($buylastprice) != "0") {
              $storedetail->productBuyPrice = $buylastprice[0]->buybilldetailprice;
              } */
        } else {
            $storedetail->productBuyPrice = $myproduct->meanbuyprice;
        }


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


        $productBuyPrice = $pro_price;


//        $productBuyPrice = $storedetail->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;




    $storeId = $_REQUEST['storeId'];

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


    $sumValue = 0;
    $Programsettingdata = $ProgramsettingDAO->load(1);
    foreach ($storedetailData as $storedetail) {
        $myproduct = $myProductRecord->load($storedetail->productid);
        if ($Programsettingdata->lastprice == "0") {
            $storedetail->productBuyPrice = $myproduct->lastbuyprice;
            /* $buylastprice = $buyBillDetailDAO->queryByBuybilldetailproductid($storedetail->productid);
              if (count($buylastprice) != "0") {
              $storedetail->productBuyPrice = $buylastprice[0]->buybilldetailprice;
              } */
        } else {
            $storedetail->productBuyPrice = $myproduct->meanbuyprice;
        }

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


        $productBuyPrice = $pro_price;

//        $productBuyPrice = $storedetail->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;

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

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

        $sumValue = 0;
        $Programsettingdata = $ProgramsettingDAO->load(1);
        foreach ($storedetailData as $storedetail) {
            $myproduct = $myProductRecord->load($storedetail->productid);
            if ($Programsettingdata->lastprice == "0") {
                $storedetail->productBuyPrice = $myproduct->lastbuyprice;
                /* $buylastprice = $buyBillDetailDAO->queryByBuybilldetailproductid($storedetail->productid);
                  if (count($buylastprice) != "0") {
                  $storedetail->productBuyPrice = $buylastprice[0]->buybilldetailprice;
                  } */
            } else {
                $storedetail->productBuyPrice = $myproduct->meanbuyprice;
            }


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


            $productBuyPrice = $pro_price;

//            $productBuyPrice = $storedetail->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 $myProductRecord;


    $storedetailData = $myStoredetailEx->queryWithOrder();

    $sumValue = 0;
    $Programsettingdata = $ProgramsettingDAO->load(1);
    if (count($storedetailData) > 0) {
        foreach ($storedetailData as $storedetail) {
            $myproduct = $myProductRecord->load($storedetail->productid);

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


            $productBuyPrice = $pro_price;


            //إجمالي سعر المنتجات
//            $productBuyPrice = $storedetail->productBuyPrice;
            $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 . '/';
        $newParentId = $catData->productCatParent;

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

function addPreDigitsToNum($num) {
    global $Programsettingdata;
    if (!isset($Programsettingdata->parcodeDigits) || empty($Programsettingdata->parcodeDigits)) {
        $Programsettingdata->parcodeDigits = 5;
    }
    $length = $Programsettingdata->parcodeDigits;


    $preDigits = '';
    if (strlen($num) != $length) {
        $noDigitsLeft = $length - strlen($num);
        for ($j = 0; $j < $noDigitsLeft; $j++) {
            $preDigits .= '0';
        }
    }
    return $preDigits . $num;
}

function getCategoryChilds($parentid = 0) {
    global $productCatExt;
    global $productCatDAO;
    //load cat
    $parentobject = $productCatDAO->load($parentid);
    $childsArray = $productCatExt->getChilds($parentid);

    return array($parentobject, $childsArray);
}

?>