<?php

///***************************** إعادة الجرد ********************///
//the global file operation
session_start();
ob_start();

//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');
//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');
//Storereport
require_once('../models/dao/StorereportDAO.class.php');
require_once('../models/dto/Storereport.class.php');
require_once('../models/mysql/StorereportMySqlDAO.class.php');
require_once('../models/mysql/ext/StorereportMySqlExtDAO.class.php');

//
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');
//Productserial
require_once('../models/dao/ProductserialDAO.class.php');
require_once('../models/dto/Productserial.class.php');
require_once('../models/mysql/ProductserialMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductserialMySqlExtDAO.class.php');


//get the do the action
$do = $_GET['do'];
$parcode = $_GET['parcode'];

//here goes the instances and general variables
//Storedetail
$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailExt = new StoredetailMySqlExtDAO();
//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();
//Storereport
$storeReportDAO = new StorereportMySqlDAO();
$storeReportExt = new StorereportMySqlExtDAO();

$myProductEx = new ProductMySqlExtDAO();
//
$sizeColorStoreDetail = new Sizecolorstoredetail();
$sizeColorStoreDetailDAO = new SizecolorstoredetailMySqlDAO();
$sizeColorStoreDetailEX = new SizecolorstoredetailMySqlExtDAO();
//Productserial
$Productserial = new Productserial();
$ProductserialDAO = new ProductserialMySqlDAO();
$ProductserialEX = new ProductserialMySqlExtDAO();

$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

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

//check and use the condition that suite this action
if (empty($do) || $do == "expirationInv") {
    $storeId = $_GET['storeid'];
    $productId = $_GET['productid'];
    $catId = (int) $_GET['catid'];
    $lastInventoryDate = $_GET['lastInventoryDate'];
    $smarty->assign("lastInventoryDate", $lastInventoryDate);
    $beforeAfter = $_GET['beforeAfter'];
    $zeros = $_GET['zeros'];
    $smarty->assign("beforeAfter", $beforeAfter);
    $showMore = (int) $_GET['showMore'];
    $lastItr = (int) $_GET['lastItr'];
    $pageNo = (int) $_GET['pageNo'];
    $showMoreSetting = (int) $_GET['showMoreSetting'];
    $smarty->assign("showMore", $showMore);
    $smarty->assign("lastItr", $lastItr);
    $smarty->assign("showMoreSetting", $showMoreSetting);


    $queryString = ' WHERE 1 ';
    $queryStringSizeColor = ' WHERE 1 ';

    if (isset($storeId) && !empty($storeId) && $storeId != '-1') {
        //get product in this store
        $queryString .= ' and storedetail.storeId = ' . $storeId;
        $queryStringSizeColor .= ' and sizecolorstoredetail.storeid = ' . $storeId;
        $store = 'storeid = ' . $storeId . ' ';
        //$queryString .= ' if(sizecolorstoredetail.id is null , storedetail.storeid=' . $storeId . ' ,sizecolorstoredetail.storeid=' . $storeId . ') AND';
    } else if ($_SESSION['searchinonestore'] == 0) {
        if ($_SESSION['storeids'] != 0) {
            $queryString .= ' and storedetail.storeId in (' . $_SESSION['storeids'] . ') ';
            $queryStringSizeColor .= ' and sizecolorstoredetail.storeid in (' . $_SESSION['storeids'] . ') ';
            $store = 'storeid in (' . $_SESSION['storeids'] . ') ';
        }
    } else {
        $queryString .= ' and storedetail.storeId = ' . $_SESSION['storeid'] . ' ';
        $queryStringSizeColor .= ' and sizecolorstoredetail.storeid = ' . $_SESSION['storeid'] . ' ';
        $store = 'storeid = ' . $_SESSION['storeid'] . ' ';
        $storeId = $_SESSION['storeid'];
    }

    if ($zeros == 2) {
        //get product in this store
        $queryString .= ' and storedetail.productquantity > 0 ';
        $queryStringSizeColor .= ' and sizecolorstoredetail.quantity > 0 ';
    }


    if (isset($catId) && !empty($catId) && $catId != '-1') {
        //get products in this category
        // or statment is for optic product that has size or color
        $queryString .= ' and (product.productCatId = ' . $catId . ' || product.productCatId in (select productCatId from productcat where productCatParent = ' . $catId . ')) ';
        $queryStringSizeColor .= ' and (product.productCatId = ' . $catId . ' || product.productCatId in (select productCatId from productcat where productCatParent = ' . $catId . ')) ';
    }
    if (isset($productId) && !empty($productId) && $productId != '-1') {
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productIdTemp = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
            // $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productIdTemp, $storeId, $sizeId, $colorId);
            $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEXNew($productIdTemp, $store, $sizeId, $colorId);

            $queryStringSizeColor .= ' and sizecolorstoredetail.id = ' . (int) $sizeColorStoreDetailId . ' ';
            $queryString .= ' and 1 = 0 '; // make sure to cancel all normal products , as we are searching for a single product that has size and color
        } else {
            //get product by id
            $queryString .= ' and product.productId = ' . $productId . ' ';
            //here iam choosing normal "not sizecolor" product // so make sure not to get sizecolor product with this condition
            $queryStringSizeColor .= ' and product.productId = ' . $productId . ' and sizeid = 0 and colorid = 0 ';
        }
    }


    //here the smarty templates
    if ($do == "expirationInv") {
        $productData = getInventoryProductsExpiration($queryString, $queryStringSizeColor);
        $smarty->assign("productData", $productData);
        $smarty->display("inventoryexpirationview/products.html");
    } else {
        $productData = getInventoryProducts($queryString, $queryStringSizeColor);
        $smarty->assign("productData", $productData);
        $smarty->display("inventoryview/products.html");
    }
} elseif ($do == "storehousing") {
    $storeId = $_GET['storeid'];
    $productId = $_GET['productid'];
    $catId = (int) $_GET['catid'];
    $zeros = (int) $_GET['zeros'];

    $queryString = ' WHERE';
    $queryStringSizeColor = ' WHERE';

    if (isset($storeId) && !empty($storeId) && $storeId != '-1') {
        //get product in this store
        $queryString .= ' storedetail.storeId = ' . $storeId . ' AND';
        $queryStringSizeColor .= ' sizecolorstoredetail.storeid = ' . $storeId . ' AND';
        //$queryString .= ' if(sizecolorstoredetail.id is null , storedetail.storeid=' . $storeId . ' ,sizecolorstoredetail.storeid=' . $storeId . ') AND';
    } else if ($_SESSION['searchinonestore'] == 0) {
        if ($_SESSION['storeids'] != 0) {
            $queryString .= ' storedetail.storeId in (' . $_SESSION['storeids'] . ') AND';
            $queryStringSizeColor .= ' sizecolorstoredetail.storeid in (' . $_SESSION['storeids'] . ') AND';
            $store = 'storeid in (' . $_SESSION['storeids'] . ') ';
        }
    } else {
        $queryString .= ' storedetail.storeId = ' . $_SESSION['storeid'] . ' AND';
        $queryStringSizeColor .= ' sizecolorstoredetail.storeid = ' . $_SESSION['storeid'] . ' AND';
        $store = 'storeid = ' . $_SESSION['storeid'] . ' ';
        $storeId = $_SESSION['storeid'];
    }

    if ($zeros == 2) {
        //get product in this store
        $queryString .= ' storedetail.productquantity > 0 AND';
        $queryStringSizeColor .= ' sizecolorstoredetail.quantity > 0 AND';
    }



    if (isset($catId) && !empty($catId) && $catId != '-1') {
        //get products in this category
        // or statment is for optic product that has size or color
        $queryString .= ' (product.productCatId = ' . $catId . ' || product.productCatId in (select productCatId from productcat where productCatParent = ' . $catId . ')) AND';
        $queryStringSizeColor .= ' (product.productCatId = ' . $catId . ' || product.productCatId in (select productCatId from productcat where productCatParent = ' . $catId . ')) AND';
    }
    if (isset($productId) && !empty($productId) && $productId != '-1') {
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productIdTemp = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
            $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEXNew($productIdTemp, $store, $sizeId, $colorId);
            $queryStringSizeColor .= ' sizecolorstoredetail.id = ' . (int) $sizeColorStoreDetailId . ' AND';
        } else {
            //get product by id
            $queryString .= ' product.productId = ' . $productId . ' AND';
        }
    }

    //explode string on space character to remove last AND occurence
    $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);
        } else if ($lastWord == 'WHERE') { //remove it
            array_pop($arr);
            $queryString = ' ';
        }
        //print("<br>".$queryString."<br>");
    }
    //explode string on space character to remove last AND occurence
    $arr = explode(' ', $queryStringSizeColor);
    //print_r($arr);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') { //remove it
            array_pop($arr);
            //form the string again
            $queryStringSizeColor = implode(' ', $arr);
        } else if ($lastWord == 'WHERE') { //remove it
            array_pop($arr);
            $queryStringSizeColor = ' ';
        }
        //print("<br>".$queryString."<br>");
    }

    //here the smarty templates

    $productData = getStoreHousingProducts($queryString, $queryStringSizeColor);
    foreach ($productData as $value) {
        $storehousingproduct = R::findOne('storehousingproduct', 'productid = ? ', [$value->productid]);
        if ($storehousingproduct) {
            $value->storehousingproductid = $storehousingproduct->id;
            $value->producttext1 = $storehousingproduct->producttext1;
            $value->producttext2 = $storehousingproduct->producttext2;
            $value->producttext3 = $storehousingproduct->producttext3;
        } else {
            $tables = R::dispense('storehousingproduct');
            $tables->productid = $value->productid;
            $tables->producttext1 = '';
            $tables->producttext2 = '';
            $tables->producttext3 = '';
            $storehousingproductid = R::store($tables);
            $value->storehousingproductid = $storehousingproductid;
            $value->producttext1 = '';
            $value->producttext2 = '';
            $value->producttext3 = '';
        }
    }
    $smarty->assign("productData", $productData);
    $smarty->display("storehousingview/products.html");
} elseif ($do == "autostorehousing") {
    $name = filter_input(INPUT_POST, 'name');
    $id = filter_input(INPUT_POST, 'id');
    $values = filter_input(INPUT_POST, 'values');
    R::exec("UPDATE `storehousingproduct` SET $name = $values WHERE id = '" . $id . "' ");
} elseif ($do == "getproductNamebyOnlyParcode" && isset($parcode) && $parcode != "") {
    loadProductByParcodeAndDonExt($parcode);
} elseif ($do == "addManyParcodesTest") {
    $storeId = (int) $_POST['storeid'];
    $catId = (int) $_POST['manyParcodesproductCatId'];

    $manyParcodes = $_POST['manyParcodes'];
    if ($Programsettingdata->usedParcode == 1) { //we use i to say that what is after itis product id
        $manyParcodes = str_replace('ه', 'i', $manyParcodes);
        $manyParcodes = str_replace('÷', 'i', $manyParcodes);
        $manyParcodes = str_replace('/', 'i', $manyParcodes);
        $manyParcodes = str_replace('I', 'i', $manyParcodes);
    } elseif ($Programsettingdata->usedParcode == 0) { //what is coming is parcode even if it starts with i
    }

    if ($manyParcodes == "") {
        //no parcodes or ids passed
        header("location:inventoryController.php");
        exit();
    }
    //1-remove enter from string
    $manyParcodes = str_replace("\n", ",", $manyParcodes);
    $manyParcodes = rtrim($manyParcodes, ',');
    ##also clean by allow only 0-9, i , ','
    $manyParcodes = preg_replace('/[^0-9,i]+/', '', $manyParcodes);
    //2-remove mess come with enter
    $temp = '';
    $idsStringDistinct = '';
    if ($Programsettingdata->usedParcode == 1) { //we use i to say that what is after itis product id
        foreach (explode(',', $manyParcodes) as $value) {
            $value = trim($value); //trim is a must for enter separated
            if ($value[0] == 'i') {
                $value = 'i' . (int) str_replace('i', '', $value);
                $idsStringDistinct .= str_replace('i', '', $value) . ',';
            }
            $temp .= $value . ',';
        }
    } elseif ($Programsettingdata->usedParcode == 0) { //what is coming is parcode even if it starts with i
        foreach (explode(',', $manyParcodes) as $value) {
            $value = trim($value); //trim is a must for enter separated
            $temp .= $value . ',';
        }
    }
    $manyParcodes = rtrim($temp, ',');
    //get distinct parcodes only"not ids" out of recieved string
    $manyParcodesArranged = array_count_values(explode(',', $manyParcodes));
    $parcodesString = '';
    if ($Programsettingdata->usedParcode == 1) { //we use i to say that what is after itis product id
        foreach ($manyParcodesArranged as $key => $value) {
            if ($key[0] != 'i') {
                $parcodesString .= $key . ',';
            }
        }
    } elseif ($Programsettingdata->usedParcode == 0) { //what is coming is parcode even if it starts with i
        foreach ($manyParcodesArranged as $key => $value) {
            $parcodesString .= '"' . $key . '",';
        }
    }
    $parcodesString = rtrim($parcodesString, ',');
    // ====================================================================
    $lastInventoryDate = $_POST['lastInventoryDate'];
    $smarty->assign("lastInventoryDate", $lastInventoryDate);
    $beforeAfter = $_POST['beforeAfter'];
    $smarty->assign("beforeAfter", $beforeAfter);


    $queryString = ' WHERE';
    $queryStringSizeColor = ' WHERE';
    if ($parcodesString != '') {
        $queryString .= ' product. parcode in (' . $parcodesString . ') AND';
    }
    if (isset($storeId) && !empty($storeId) && $storeId != '-1') {
        //get product in this store
        $queryString .= ' storedetail.storeId = ' . $storeId . ' AND';
        $queryStringSizeColor .= ' sizecolorstoredetail.storeid = ' . $storeId . ' AND';
        //$queryString .= ' if(sizecolorstoredetail.id is null , storedetail.storeid=' . $storeId . ' ,sizecolorstoredetail.storeid=' . $storeId . ') AND';
    }
    if (isset($catId) && !empty($catId) && $catId != '-1') {
        //get products in this category
        // or statment is for optic product that has size or color
        $queryString .= ' (product.productCatId = ' . $catId . ' || product.productCatId in (select productCatId from productcat where productCatParent = ' . $catId . ')) AND';
        $queryStringSizeColor .= ' (product.productCatId = ' . $catId . ' || product.productCatId in (select productCatId from productcat where productCatParent = ' . $catId . ')) AND';
    }
    if (isset($productId) && !empty($productId) && $productId != '-1') {
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productIdTemp = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
            $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productIdTemp, $storeId, $sizeId, $colorId);
            $queryStringSizeColor .= ' sizecolorstoredetail.id = ' . (int) $sizeColorStoreDetailId . ' AND';
        } else {
            //get product by id
            $queryString .= ' product.productId = ' . $productId . ' AND';
            //here iam choosing normal "not sizecolor" product // so make sure not to get sizecolor product with this condition
            $queryStringSizeColor .= ' product.productId = ' . $productId . ' and sizeid = 0 and colorid = 0  AND';
        }
    }

    //explode string on space character to remove last AND occurence
    $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);
        } else if ($lastWord == 'WHERE') { //remove it
            array_pop($arr);
            $queryString = ' ';
        }
        //print("<br>".$queryString."<br>");
    }
    //explode string on space character to remove last AND occurence
    $arr = explode(' ', $queryStringSizeColor);
    //print_r($arr);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') { //remove it
            array_pop($arr);
            //form the string again
            $queryStringSizeColor = implode(' ', $arr);
        } else if ($lastWord == 'WHERE') { //remove it
            array_pop($arr);
            $queryStringSizeColor = ' ';
        }
        //print("<br>".$queryString."<br>");
    }

    //here the smarty templates
    if ($do == "expirationInv") {
        $productData = getInventoryProductsExpiration($queryString, $queryStringSizeColor);
        $smarty->assign("productData", $productData);
        $smarty->display("inventoryexpirationview/products.html");
    } else {
        $productData = getInventoryProducts($queryString, $queryStringSizeColor);
        $smarty->assign("productData", $productData);
        $smarty->display("inventoryview/products.html");
    }
} elseif ($do == "addManyParcodes") {
    //here the permission check
    //include_once("../public/authentication.php");
    $manyParcodes = $_POST['manyParcodes'];
    if ($Programsettingdata->usedParcode == 1) { //we use i to say that what is after itis product id
        $manyParcodes = str_replace('ه', 'i', $manyParcodes);
        $manyParcodes = str_replace('÷', 'i', $manyParcodes);
        $manyParcodes = str_replace('/', 'i', $manyParcodes);
        $manyParcodes = str_replace('I', 'i', $manyParcodes);
    } elseif ($Programsettingdata->usedParcode == 0) { //what is coming is parcode even if it starts with i
    }
    $storeId = (int) $_POST['storeid'];
    $smarty->assign("manyParcodes", 1);
    $smarty->assign("storeid", $storeId);
    if ($manyParcodes == "") {
        //no parcodes or ids passed
        header("location:inventoryController.php");
        exit();
    }
    //1-remove enter from string
    $manyParcodes = str_replace("\n", ",", $manyParcodes);
    $manyParcodes = rtrim($manyParcodes, ',');
    ##also clean by allow only 0-9, i , ','
    $manyParcodes = preg_replace('/[^0-9,i]+/', '', $manyParcodes);
    //2-remove mess come with enter
    $temp = '';
    $idsStringDistinct = '';
    if ($Programsettingdata->usedParcode == 1) { //we use i to say that what is after itis product id
        foreach (explode(',', $manyParcodes) as $value) {
            $value = trim($value); //trim is a must for enter separated
            if ($value[0] == 'i') {
                $value = 'i' . (int) str_replace('i', '', $value);
                $idsStringDistinct .= str_replace('i', '', $value) . ',';
            }
            $temp .= $value . ',';
        }
    } elseif ($Programsettingdata->usedParcode == 0) { //what is coming is parcode even if it starts with i
        foreach (explode(',', $manyParcodes) as $value) {
            $value = trim($value); //trim is a must for enter separated
            $temp .= $value . ',';
        }
    }
    $manyParcodes = rtrim($temp, ',');
    //get distinct parcodes only"not ids" out of recieved string
    $manyParcodesArranged = array_count_values(explode(',', $manyParcodes));
    $parcodesString = '';
    if ($Programsettingdata->usedParcode == 1) { //we use i to say that what is after itis product id
        foreach ($manyParcodesArranged as $key => $value) {
            if ($key[0] != 'i') {
                $parcodesString .= $key . ',';
            }
        }
    } elseif ($Programsettingdata->usedParcode == 0) { //what is coming is parcode even if it starts with i
        foreach ($manyParcodesArranged as $key => $value) {
            $parcodesString .= '"' . $key . '",';
        }
    }
    $parcodesString = rtrim($parcodesString, ',');
    //replace parcodes with ids
    if ($parcodesString != '') {
        $productsData = $myProductEx->getProductIdByParcode($parcodesString);
        $productsDataSizeColor = $sizeColorStoreDetailEX->queryByParcodeInSimple($parcodesString);

        //if i have 2 parcodes same and after each other ex",00003,00003," str replace will replace first occurance only
        $manyParcodes = str_replace(',', ',,', $manyParcodes);
        $manyParcodes = ',' . $manyParcodes . ',';

        foreach ($productsData as $value) {
            $idsStringDistinct .= $value->productId . ",";
            $manyParcodes = str_replace(',' . $value->parcode . ',', ',i' . $value->productId . ',', $manyParcodes);
        }

        $manyParcodesSizeColor = '';
        $manyParcodesSizeColorDistinct = '';
        foreach ($productsDataSizeColor as $value) {
            $manyParcodes = str_replace(',' . $value->parcode . ',', ',,', $manyParcodes);
            $manyParcodesSizeColorDistinct .= "'" . $value->parcode . "',";
            for ($i = 0; $i < $manyParcodesArranged["$value->parcode"]; $i++) {
                $manyParcodesSizeColor .= $value->parcode . ",";
            }
        }
        $manyParcodes = rtrim(ltrim($manyParcodes, ","), ","); //remove first and last comma s
        $manyParcodes = str_replace(',,', ',', $manyParcodes);
        $manyParcodesSizeColor = rtrim(ltrim($manyParcodesSizeColor, ","), ","); //remove first and last comma s
    }
    $manyParcodes = str_replace('i', '', $manyParcodes);
    $idsStringDistinct = rtrim($idsStringDistinct, ',');
    $manyParcodesSizeColorDistinct = rtrim($manyParcodesSizeColorDistinct, ',');
    //count repeats of each value
    $allparcodes = $manyParcodes . ',' . $manyParcodesSizeColor;

    $manyParcodesArranged = array_count_values(explode(',', $allparcodes));
    if (empty($idsStringDistinct))
        $idsStringDistinct = 0;
    if (empty($manyParcodesSizeColorDistinct))
        $manyParcodesSizeColorDistinct = "'-1-1'";
    //get  sell bill detales data
    //$mysellbildetales = $mySellbilldetailEx->queryWithSellBillId($sellbillid);
    $products = $myProductEx->queryAllDistinctWithQueryStringUnion(" and productId in ($idsStringDistinct) ", " and sizecolorstoredetail.parcode in ($manyParcodesSizeColorDistinct) ");
    $i = 1;
    $products_ordered = array();
    foreach ($manyParcodesArranged as $key => $value) {
        foreach ($products as $pro) {
            if (!empty($key) && ((int) $pro->productId === $key || $pro->sizeColorParcode == $key)) {
                if ((int) $pro->sizeid > 0 && (int) $pro->colorid > 0) {
                    $pro->parcode = $pro->sizeColorParcode;
                    $pro->productId = "hasSizeColor$pro->productId-$pro->sizeid-$pro->colorid";
                }
                ##########
                //new product name with all path
                $parentId = $pro->productCatId;
                //names of product's parents
                $pathArr = getProductPath_recursive($parentId, $categories);
                $pro->productName = $pro->productName . '/' . $pathArr;
                if (!is_null($pro->sizeName) && !empty($pro->sizeName) && (int) $pro->sizeid > 0) {
                    $pro->productName .= '/' . $pro->sizeName;
                }
                if (!is_null($pro->colorName) && !empty($pro->colorName) && (int) $pro->colorid > 0) {
                    $pro->productName .= '/' . $pro->colorName;
                }
                $pro->quantityMovement = $manyParcodesArranged[$key]; //use no of repeats of productId
                // here the function that do the action
                $pro->productquantity = (float) getProductAmountInStore($storeId, $pro->productId);
                #######
                $pro->choosenPrice = 0;
                switch ($manyParcodeswhatPrice) {
                    case 'hide':
                        $pro->choosenPrice = 0;
                        break;
                    case 'productBuyPrice':
                        $pro->choosenPrice = $pro->productBuyPrice;
                        break;
                    case 'productSellAllPrice':
                        $pro->choosenPrice = $pro->productSellAllPrice;
                        break;
                    case 'productSellHalfPrice':
                        $pro->choosenPrice = $pro->productSellUnitPrice;
                        break;
                    case 'productSellUnitPrice':
                        $pro->choosenPrice = $pro->productSellHalfPrice;
                        break;
                    default:
                        break;
                }
                $i++;
                array_push($products_ordered, $pro);
            }
        }
    }
    // $smarty->assign("products_ordered", $products_ordered);
    $smarty->assign("productData", $products_ordered);
    return $smarty->display("inventoryview/products.html");
}
/* ===============================
  function in this CONTROLLER
  ================================ */

function loadProductByParcodeAndDonExt($parcode) {
    global $storeDetailExt;
    global $myProductEx;
    //    global $myBillnameRecord;
    //    global $myBillsettingEx;
    //    global $BillpropertyDAO;
    ##check if parcode scale is used
    $WeightPricePart;
    $posType;
    $useParcodeBalance = 0;
    //get prop id
    /* $Billproperty = $BillpropertyDAO->queryByBillpropertyname('تفعيل ميزان الباركود');
      if (count($Billproperty) > 0) {
      $Billproperty = $Billproperty[0];
      //get setting
      $billsettingsData = $myBillsettingEx->queryByBillidAndBillpropertyid($billnameid, $Billproperty->billpropertyid);
      $billsettingsData = $billsettingsData[0];
      if ($billsettingsData->billsettingsvalue == 0) {
      //load parcode scale data
      $myBillname = $myBillnameRecord->load($billnameid);
      if (strpos($parcode, $myBillname->posFlag) === 0 && $myBillname->checkDigit == substr($parcode, strlen($myBillname->checkDigit) * -1)) {
      //condition 1 ---- parcode start with the posFlag  and end with checkDigit
      $requiredParcodeLength = strlen($myBillname->posFlag) + $myBillname->posCode + $myBillname->posWeightPrice + strlen($myBillname->checkDigit);
      $givenParcodeLen = strlen($parcode);
      if ($requiredParcodeLength == $givenParcodeLen) {
      //condition 2 ---- required length is ok
      // -- now start chopping parcode ---- //
      //-remove posFlag
      $parcode = substr($parcode, strlen($myBillname->posFlag));
      //-remove checkDigit
      $formattedParcode = substr($parcode, 0, (strlen($myBillname->checkDigit) * -1));
      //get product parcode
      $parcode = substr($formattedParcode, 0, $myBillname->posCode);
      //get product weigt or price part
      $WeightPricePart = (float) substr($formattedParcode, ($myBillname->posWeightPrice * -1));
      $posType = $myBillname->posType;
      $useParcodeBalance = 1;
      }
      }
      }
      } */
    $arr = array();
    $categories;
    // select all data from product tbl
    $productData = $myProductEx->queryWithSerialnumberAndAvailable($parcode);

    if (count($productData) <= 0) {
        $productData = $myProductEx->queryWithParcode($parcode);

        $arr['id'] = $productData->productId;
        //names of product's parents
        $parentId = $productData->productCatId;
        $pathArr = fetch_recursive($parentId, $categories);
        //
        $arr['text'] = $productData->productName . '/' . $pathArr;
        $arr['parcodeType'] = "parcode";
        $arr['productserailid'] = 0;
        $arr['productQty'] = 'undefined';

        $arr['useParcodeBalance'] = $useParcodeBalance;
        $arr['WeightPricePart'] = $WeightPricePart;
        $arr['posType'] = $posType;
    } else {
        $arr['id'] = $productData->productId;
        //names of product's parents
        $parentId = $productData->productCatId;
        $pathArr = fetch_recursive($parentId, $categories);
        //
        $arr['text'] = $productData->productName . '/' . $pathArr;
        $arr['parcodeType'] = "serialnumber";
        $arr['productserailid'] = $productData->productserailid;

        $arr['productQty'] = $productData->don;

        $arr['useParcodeBalance'] = $useParcodeBalance;
        $arr['WeightPricePart'] = $WeightPricePart;
        $arr['posType'] = $posType;
    }
    //get quantity in stores
    $queryString = '';
    if (isset($_GET["ids"]) && !empty($_GET["ids"]) && $_GET["ids"] != "all") {
        $ids = $_GET["ids"];
        $queryString = " and storeid in($ids) ";
    }
    $quantityInStores = $storeDetailExt->getProductQuantityInAllStoresSimple($arr['id'], $queryString);
    $quantityArr = array();
    foreach ($quantityInStores as $value) {
        $quantityArr[$value->storeid] = $value->productquantity . "*" . $value->storedetailid;
    }
    $arr['quantityInStores'] = $quantityArr;
    echo json_encode($arr);
}

function getStoreHousingProducts($queryString, $queryStringSizeColor) {
    global $storeDetailExt;
    global $storeReportExt;

    $productData = $storeDetailExt->queryProductsInInventoryExt2NoServiceWithUnion($queryString, $queryStringSizeColor);
    if (count($productData) > 0) {
        foreach ($productData as $pro) {

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

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


            $queryStringSizeColor = '';
            if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
                $queryStringSizeColor = ' AND sizeid = ' . $pro->sizeid . ' And colorid = ' . $pro->colorid . ' ';
            }


            ///////////تاريخ آخر عملية إعادة جرد
            $lastDate = $storeReportExt->getLastInventoryDateByProductIdAndStoreId($pro->productid, $_REQUEST['storeid'], $queryStringSizeColor);
            $pro->lastInventoryDate = $lastDate;


            //////////تلوين المنتجات اللي اتعملها إعادة جرد في خلال 10 أيام سابقة.
            $today = date("Y-m-d");
            $date = date("Y-m-d", strtotime('-10 day' . $today));
            $storeReportData = $storeReportExt->getlatestInventoryProductsWithStoreId($pro->productid, $_REQUEST['storeid'], $date, $today, $queryStringSizeColor);
            if (count($storeReportData) > 0) {
                $pro->status = 1;
            } else {
                $pro->status = 0;
            }

            if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
                $pro->productid = "hasSizeColor" . $pro->productid . "-" . $pro->sizeid . "-" . $pro->colorid;
            }
            //$row_array['sizecolorstoredetailid'] = $pro->sizecolorstoredetailid;
            if (!is_null($pro->sizeName) && !empty($pro->sizeName)) {
                $pro->productName .= '/' . $pro->sizeName;
            }
            if (!is_null($pro->colorName) && !empty($pro->colorName)) {
                $pro->productName .= '/' . $pro->colorName;
            }
        }
    }
    return $productData;
}

function getInventoryProducts($queryString, $queryStringSizeColor) {
    global $storeDetailExt;
    global $storeReportExt;
    global $Programsettingdata;
    global $pageNo;
    global $showMoreSetting;

    $limitQs = '';
    if ($showMoreSetting == 0) {
        $limit = $Programsettingdata->searchlimit; //(int)$_GET['page_limit'];
        if (empty($limit)) {
            $limit = 30;
        }
        $pageNo = $pageNo * $limit;
        $limitQs = " limit $pageNo,$limit ";
    }
    $productData = $storeDetailExt->queryProductsInInventoryExt2NoServiceWithUnion($queryString, $queryStringSizeColor, $limitQs);
    if (count($productData) > 0) {
        foreach ($productData as $pro) {
            ///////////To show product category name (the product whole path)
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

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


            $queryStringSizeColor = '';
            if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
                $queryStringSizeColor = ' AND sizeid = ' . $pro->sizeid . ' And colorid = ' . $pro->colorid . ' ';
            }


            ///////////تاريخ آخر عملية إعادة جرد
            $lastDate = $storeReportExt->getLastInventoryDateByProductIdAndStoreId($pro->productid, $_REQUEST['storeid'], $queryStringSizeColor);
            $pro->lastInventoryDate = $lastDate;


            //////////تلوين المنتجات اللي اتعملها إعادة جرد في خلال 10 أيام سابقة.
            $today = date("Y-m-d");
            $date = date("Y-m-d", strtotime('-10 day' . $today));
            $storeReportData = $storeReportExt->getlatestInventoryProductsWithStoreId($pro->productid, $_REQUEST['storeid'], $date, $today, $queryStringSizeColor);
            if (count($storeReportData) > 0) {
                $pro->status = 1;
            } else {
                $pro->status = 0;
            }

            if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
                $pro->productid = "hasSizeColor" . $pro->productid . "-" . $pro->sizeid . "-" . $pro->colorid;
            }
            //$row_array['sizecolorstoredetailid'] = $pro->sizecolorstoredetailid;
            if (!is_null($pro->sizeName) && !empty($pro->sizeName)) {
                $pro->productName .= '/' . $pro->sizeName;
            }
            if (!is_null($pro->colorName) && !empty($pro->colorName)) {
                $pro->productName .= '/' . $pro->colorName;
            }
        }
    }
    return $productData;
}

function getInventoryProductsExpiration($queryString, $queryStringSizeColor) {
    global $storeDetailExt;
    global $storeReportExt;
    global $ProductserialEX;

    $productData = $storeDetailExt->queryProductsInInventoryExt2NoServiceWithUnion($queryString, $queryStringSizeColor);
    if (count($productData) > 0) {
        foreach ($productData as $pro) {
            ///////////To show product category name (the product whole path)
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

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



            $queryStringSizeColor = '';
            if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
                $queryStringSizeColor = ' AND sizeid = ' . $pro->sizeid . ' And colorid = ' . $pro->colorid . ' ';
            }
            $queryStringSerial = " and productid =$pro->productid  and sizeid =$pro->sizeid and colorid =$pro->colorid and storeid=$pro->storeid and del= 0 ";
            $pro->serialData = $ProductserialEX->queryAllByQueryString($queryStringSerial);

            //            ///////////تاريخ آخر عملية إعادة جرد
            //            $lastDate = $storeReportExt->getLastInventoryDateByProductIdAndStoreId($pro->productid, $_REQUEST['storeid'], $queryStringSizeColor);
            //            $pro->lastInventoryDate = $lastDate;
            //
            //            //////////تلوين المنتجات اللي اتعملها إعادة جرد في خلال 10 أيام سابقة.
            //            $today = date("Y-m-d");
            //            $date = date("Y-m-d", strtotime('-10 day' . $today));
            //            $storeReportData = $storeReportExt->getlatestInventoryProductsWithStoreId($pro->productid, $_REQUEST['storeid'], $date, $today, $queryStringSizeColor);
            //            if (count($storeReportData) > 0) {
            //                $pro->status = 1;
            //            } else {
            //                $pro->status = 0;
            //            }

            if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
                $pro->productid = "hasSizeColor" . $pro->productid . "-" . $pro->sizeid . "-" . $pro->colorid;
            }
            //$row_array['sizecolorstoredetailid'] = $pro->sizecolorstoredetailid;
            if (!is_null($pro->sizeName) && !empty($pro->sizeName)) {
                $pro->productName .= '/' . $pro->sizeName;
            }
            if (!is_null($pro->colorName) && !empty($pro->colorName)) {
                $pro->productName .= '/' . $pro->colorName;
            }
        }
    }
    return $productData;
}

function getProductInStore($storeId) {
    global $storeDetailExt;
    global $storeReportExt;

    $productData = $storeDetailExt->queryWithStoreIdExt($storeId);
    if (count($productData) > 0) {
        foreach ($productData as $pro) {
            ///////////To show product category name (the product whole path)
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

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

            ///////////تاريخ آخر عملية إعادة جرد
            $lastDate = $storeReportExt->getLastInventoryDateByProductId($pro->productid);
            $pro->lastInventoryDate = $lastDate;

            //////////تلوين المنتجات اللي اتعملها إعادة جرد في خلال 10 أيام سابقة.
            $today = date("Y-m-d");
            $date = date("Y-m-d", strtotime('-10 day' . $today));
            $storeReportData = $storeReportExt->getlatestInventoryProducts($pro->productid, $date, $today);
            if (count($storeReportData) > 0) {
                $pro->status = 1;
            } else {
                $pro->status = 0;
            }
        }
    }
    return $productData;
}

function getProductInCategory($catId) {
    global $storeDetailExt;
    global $storeReportExt;

    $productData = $storeDetailExt->queryByProductQtyByCatId($catId);
    if (count($productData) > 0) {
        foreach ($productData as $pro) {
            ///////////تاريخ آخر عملية إعادة جرد
            $lastDate = $storeReportExt->getLastInventoryDateByProductId($pro->productid);
            $pro->lastInventoryDate = $lastDate;

            //////////تلوين المنتجات اللي اتعملها إعادة جرد في خلال 10 أيام سابقة.
            $today = date("Y-m-d");
            $date = date("Y-m-d", strtotime('-10 day' . $today));
            $storeReportData = $storeReportExt->getlatestInventoryProducts($pro->productid, $date, $today);
            if (count($storeReportData) > 0) {
                $pro->status = 1;
            } else {
                $pro->status = 0;
            }
        }
    }
    return $productData;
}

function getProduct($productId) {
    global $storeDetailExt;
    global $storeReportExt;

    $productData = $storeDetailExt->queryWithProductIdExt($productId);
    if (count($productData) > 0) {
        foreach ($productData as $pro) {
            ///////////تاريخ آخر عملية إعادة جرد
            $lastDate = $storeReportExt->getLastInventoryDateByProductId($pro->productid);
            $pro->lastInventoryDate = $lastDate;

            //////////تلوين المنتجات اللي اتعملها إعادة جرد في خلال 10 أيام سابقة.
            $today = date("Y-m-d");
            $date = date("Y-m-d", strtotime('-10 day' . $today));
            $storeReportData = $storeReportExt->getlatestInventoryProducts($pro->productid, $date, $today);
            if (count($storeReportData) > 0) {
                $pro->status = 1;
            } else {
                $pro->status = 0;
            }
        }
    }
    return $productData;
}

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

    if ((int) $parentid > 0)
        $catData = $productCatExt->getCategoryAndParentByCatId($parentid);

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

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

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

// get productquantity from storedetail tbl
function getProductAmountInStore($storeid, $productId) {

    //to use the variable out side the funcion
    global $storeDetailExt;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
        $sizeId = $productIdComplex[1];
        $colorId = $productIdComplex[2];
        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeid, $sizeId, $colorId);
    }

    if (isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) { //sizecolor product
        $storedetailData = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);
        $storedetailId = $storedetailData->id;
        $productquantityBefore = $storedetailData->quantity;
    } else {
        //select data from storerawmaterialdetails by storeid and rawmaterialid
        $storedetailData = $storeDetailExt->queryWithStoreAndProduct($productId, $storeid);

        $productquantityBefore = $storedetailData->productquantity;
    }

    return $productquantityBefore;
}
