<?php

$do = isset($_GET['do']) ? $_GET['do'] : '';
//Transaction
include_once("../models/sql/Transaction.class.php");
//the global file operation
if ($do != "editorder")
    include("../public/impOpreation.php");

//global varable
global $showoutside;

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


//here the db files that include in the file
// GOES HERE ....................
include("../public/include_dao.php");
include_once("dailyentryfun.php");

//Storemovement
require_once('../models/dao/StoremovementDAO.class.php');
require_once('../models/dto/Storemovement.class.php');
require_once('../models/mysql/StoremovementMySqlDAO.class.php');
require_once('../models/mysql/ext/StoremovementMySqlExtDAO.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');

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

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


//user
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.class.php');



//Otherstoremovement
require_once('../models/dao/OtherstoremovementDAO.class.php');
require_once('../models/dto/Otherstoremovement.class.php');
require_once('../models/mysql/OtherstoremovementMySqlDAO.class.php');
require_once('../models/mysql/ext/OtherstoremovementMySqlExtDAO.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');

//
require_once('../models/dao/BuypriceshistorybookDAO.class.php');
require_once('../models/dto/Buypriceshistorybook.class.php');
require_once('../models/mysql/BuypriceshistorybookMySqlDAO.class.php');
require_once('../models/mysql/ext/BuypriceshistorybookMySqlExtDAO.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');


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

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

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

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

  Controller Name :- storemovementCTRL التحويل بين المخازن

  OPERTATION in Controller

  1-display add form
  2- add in Save tbl
  3-insert into savedaily tbl
  4-display sucess or error
  5-display show form
  6-edit in Save data

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


//here the global templates
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} else {
    if ($do != "editorder")
        $smarty->display("header.html");
}


//here goes the instances and general variables

$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$programSettingEX = new ProgramsettingsMySqlExtDAO();
//Storemovement
$myStoremovement = new Storemovement();
$myStoremovementRecord = new StoremovementMySqlDAO();
$myStoremovementEx = new StoremovementMySqlExtDAO();

//Storereport
$myStorereport = new Storereport();
$myStorereportRecord = new StorereportMySqlDAO();
$myStorereportEx = new StorereportMySqlExtDAO();

//Storedetail
$myStoredetailEx = new StoredetailMySqlExtDAO();
$myStoredetailRecord = new StoredetailMySqlDAO();
$Storedetail = new Storedetail();
//Store
$myStoreRecord = new StoreMySqlDAO();
$myStoreEx = new StoreMySqlExtDAO();


//Product
$myProductRecord = $productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();

//user
$user = new User();
$userDAO = new UserMySqlDAO();
$userEX = new UserMySqlExtDAO();


//Otherstoremovement
$Otherstoremovement = new Otherstoremovement();
$OtherstoremovementDAO = new OtherstoremovementMySqlDAO();
$OtherstoremovementEX = new OtherstoremovementMySqlExtDAO();

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

//Buypriceshistorybook
$buyPricesHistoryBook = new Buypriceshistorybook();
$buyPricesHistoryBookDAO = new BuypriceshistorybookMySqlDAO();
$buyPricesHistoryBookEX = new BuypriceshistorybookMySqlExtDAO();
//Productserial
$myProductserial = new Productserial();
$myProductserialDAO = new ProductserialMySqlDAO();
$myProductserialEx = new ProductserialMySqlExtDAO();


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

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

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

$usergroupdata = $myUserGroupRecord->load($_SESSION['usergroupid']);
$smarty->assign("usergroupdata", $usergroupdata);

$userData = $userDAO->load($_SESSION['userid']);
$userData->storeSupervisorStores = explode(',', $userData->storeSupervisorStores);
$smarty->assign("userData", $userData);
//Decide operation add,del do
$operationFlag = -1;
$addArr = array('add', 'addAllStoreProducts', 'returndelete', 'returndelete2', 'recieveproduct');
$delArr = array('tempdelete', 'tempdelete2');
$operationType = $_POST['operation'];
if (in_array($do, $addArr) || $operationType == "2") {
    $operationFlag = 0; //means add , decrease store from & increase store to
} elseif (in_array($do, $delArr) || $operationType == "1") {
    $operationFlag = 1; //means del, decrease store to & increase store from
}



##for daily entry
$mainData = new stdClass();
$detailArr = array();
//check and use the condetion that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");

    // here the function that do the action

    $userDefStore = $userDAO->load($_SESSION['userid'])->userstoreidDef;
    $smarty->assign('userDefStore', $userDefStore);

    $smarty->assign("searchinonestore", $_SESSION['searchinonestore']);
    if ($_SESSION['searchinonestore'] == 0) {
        if ($_SESSION['storeids'] == 0) {
            $stores = $myStoreEx->queryByConditions();
        } else {
            $stores = $myStoreEx->queryByConditions(' and store.storeId in (' . $_SESSION['storeids'] . ')');
        }


        $smarty->assign("stores", $stores);
        $store = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("store", $store);
        $smarty->assign("manyParcodesstoreidfrom", $_SESSION['storeid']);
    } else {
        $store = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("store", $store);
        $smarty->assign("manyParcodesstoreidfrom", $_SESSION['storeid']);
    }



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


    //السائقين
    $drivers = $userEX->queryWithGroupName("سائقين");
    $smarty->assign("drivers", $drivers);


    $smarty->assign("storenegative", $_SESSION['storenegative']);

    ##get client serial
    $DBName = ConnectionProperty::getDatabase();
    if ($_SESSION['dbname'] != "" && isset($_SESSION['dbname'])) {
        $DBName = $_SESSION['dbname'];
    }
    // $nextId = $myStoremovementEx->getAutoIncrementValue($DBName);
    $nextId = $myStoremovementEx->queryAlloperationnum();
    $last_val = $nextId[0];

    $last = $last_val->operationnum + 1;

    $smarty->assign("nextId", $last);

    //here the smarty templates
    $smarty->display("storemovementview/add.html");

    $smarty->assign("customStoremovement", 1);
} ##
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
    }
    $manyParcodesstoreidfrom = (int) $_POST['manyParcodesstoreidfrom'];
    $manyParcodesstoreidto = $_POST['manyParcodesstoreidto'];
    $manyParcodeswhatPrice = $_POST['manyParcodeswhatPrice'];
    $smarty->assign("manyParcodes", 1);
    $smarty->assign("manyParcodesstoreidfrom", $manyParcodesstoreidfrom);
    $smarty->assign("manyParcodesstoreidto", $manyParcodesstoreidto);
    $smarty->assign("manyParcodeswhatPrice", $manyParcodeswhatPrice);
    if ($manyParcodes == "") {
        //no parcodes or ids passed
        header("location:storemovementController.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 = $productExt->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 = $productExt->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->currentQuantity = (float) getProductAmountInStore($manyParcodesstoreidfrom, $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("searchinonestore", $_SESSION['searchinonestore']);
    if ($_SESSION['searchinonestore'] == 0) {
        if ($_SESSION['storeids'] == 0) {
            $stores = $myStoreEx->queryByConditions();
        } else {
            $stores = $myStoreEx->queryByConditions(' and store.storeId in (' . $_SESSION['storeids'] . ')');
        }
        $smarty->assign("stores", $stores);
        $store = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("store", $store);
        $smarty->assign("manyParcodesstoreidfrom", $_SESSION['storeid']);
    } else {
        $store = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("store", $store);
        $smarty->assign("manyParcodesstoreidfrom", $_SESSION['storeid']);
    }





    // here the function that do the action
    $storeData = loadStore();
    $smarty->assign("storeData", $storeData);


    //السائقين
    $drivers = $userEX->queryWithGroupName("سائقين");
    $smarty->assign("drivers", $drivers);


    $smarty->assign("storenegative", $_SESSION['storenegative']);

    ##get client serial
    $DBName = ConnectionProperty::getDatabase();
    if ($_SESSION['dbname'] != "" && isset($_SESSION['dbname'])) {
        $DBName = $_SESSION['dbname'];
    }
    // $nextId = $myStoremovementEx->getAutoIncrementValue($DBName);
    $nextId = $myStoremovementEx->queryAlloperationnum();
    $last_val = $nextId[0];

    $last = $last_val->operationnum + 1;

    $smarty->assign("nextId", $last);

    //here the smarty templates
    $smarty->display("storemovementview/add.html");

    $smarty->assign("customStoremovement", 1);
}
##
elseif ($do == "add") {

    //here the permssion check
    include_once("../public/authentication.php");

    // here the function that do the action
    if ($Programsettingdata->workerbetweenstores == 0 || (int) $_POST['recieveType'] == 1) {
        $productsAfterValid = addDealWithStoreFromOnly();
        makeStoreMovementDailyEntry($mainData, $detailArr, 1);
        if ($productsAfterValid[0] === "error") { //coming from rollback
            header("location:?do=error");
        } else {
            header("location:?do=sucess");
        }
    } else {

        $productsAfterValid = add();
        $operationNo = $productsAfterValid[2];
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            if ($productsAfterValid[0] === "error") { //coming from rollback
                $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            } else {//if ($productsAfterValid[1] == '0') {
                makeStoreMovementDailyEntry($mainData, $detailArr, 0);
                $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success', 'id' => $mainData->operationnum);
            }

            echo json_encode($data);
            exit();
        } else {

            if ($productsAfterValid[0] === "error") { //coming from rollback
                header("location:?do=error");
            } elseif ($productsAfterValid[1] == '0') {
                makeStoreMovementDailyEntry($mainData, $detailArr, 0);
                header("location:?do=sucess");
            } else {
                makeStoreMovementDailyEntry($mainData, $detailArr, 0);
                if ($productsAfterValid[1] == '1') {
                    header('Location: storemovementController.php?do=editorder&on=' . $operationNo . '');
                } else {
                    header('Location: storemovementController.php?do=editshow&operationnum=' . $operationNo . '');
                }
            }
        }
    }
    //    if ($productsAfterValid == 1) {
    //
    //
    //          header("location:?do=sucess");
    //    } else {
    //        $url = "storemovementController.php?do=show";
    //        $smarty->assign('urldirect', $url);
    //        $note = "لا يوجد بالمخزن الكمية الكافية لتحويل المنتجات";
    //
    //        $smarty->assign('msgnote', $note);
    //         $smarty->display("notes.html");
    //    }
} elseif ($do == "addAllStoreProducts") {

    //here the permssion check
    //include_once("../public/authentication.php");

    $productsAfterValid = addAllStoreProducts();
    $operationNo = $productsAfterValid[2];
    if ($productsAfterValid[0] === "error") { //coming from rollback
        header("location:?do=error");
    } else if ($productsAfterValid[1] == '0') {
        makeStoreMovementDailyEntry($mainData, $detailArr, 0);
        header("location:?do=sucess");
    } else {
        makeStoreMovementDailyEntry($mainData, $detailArr, 0);
        if ($productsAfterValid[1] == '1') {
            header('Location: storemovementController.php?do=editorder&on=' . $operationNo . '');
        } else {
            header('Location: storemovementController.php?do=editshow&operationnum=' . $operationNo . '');
        }
    }
} elseif ($do == "show") {

    //here the permssion check
    include_once("../public/authentication.php");
    // $qsOpNum = 'and conditions != 2';
    // $alloperationnum = $myStoremovementEx->queryAlloperationnum($qsOpNum);
    // $smarty->assign('alloperationnum', $alloperationnum);

    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $operationnum = $_REQUEST["operationnum"];
    $storeId = $_POST["storeId"];

    if (isset($operationnum) && $operationnum != -1 && $operationnum != '') {
        $message = " عرض تحويلات المخازن لرقم الايصال: " . $operationnum . "";
        $smarty->assign('message', $message);
        showByoperationnum2($operationnum);
        //} elseif (isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "" && $operationnum == -1) {
    } elseif (isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "") {

        $message = " عرض تحويلات المخازن من تاريخ: " . $startDate . "الى تاريخ:" . $endDate;
        $smarty->assign('message', $message);
        showByDate2($startDate, $endDate, $storeId);
    } else {
        $message = " عرض تحويلات المخازن من تاريخ: " . date("Y-m-d") . " الى تاريخ: " . date("Y-m-d");
        $smarty->assign('message', $message);
        showByDate2(date("Y-m-d"), date("Y-m-d"), $storeId);
    }


    $smarty->assign("searchinonestore", $_SESSION['searchinonestore']);
    if ($_SESSION['searchinonestore'] == 0) {
        if ($_SESSION['storeids'] == 0) {
            $stores = $myStoreEx->queryByConditions();
        } else {
            $stores = $myStoreEx->queryByConditions(' and store.storeId in (' . $_SESSION['storeids'] . ')');
        }
        $smarty->assign("storeData", $stores);
        $store = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("store", $store);
        $smarty->assign("manyParcodesstoreidfrom", $_SESSION['storeid']);
    } else {
        $store = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("store", $store);
        $smarty->assign("manyParcodesstoreidfrom", $_SESSION['storeid']);
    }







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

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

    $smarty->display("storemovementview/show.html");


    $smarty->assign("customCheck", 1);
} elseif ($do == "showdetails") {

    //here the permssion check
    include_once("../public/authentication.php");

    // here the function that do the action
    $smarty->assign("searchinonestore", $_SESSION['searchinonestore']);
    if ($_SESSION['searchinonestore'] == 0) {
        if ($_SESSION['storeids'] == 0) {
            $stores = $myStoreEx->queryByConditions();
        } else {
            $stores = $myStoreEx->queryByConditions(' and store.storeId in (' . $_SESSION['storeids'] . ')');
        }
        $smarty->assign("storeData", $stores);
        $store = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("store", $store);
        $smarty->assign("manyParcodesstoreidfrom", $_SESSION['storeid']);
    } else {
        $store = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("store", $store);
        $smarty->assign("manyParcodesstoreidfrom", $_SESSION['storeid']);
    }




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

    $alloperationnum = $myStoremovementEx->queryAlloperationnum();
    $smarty->assign('alloperationnum', $alloperationnum);

    //    $userData = $userDAO->load($_SESSION['userid']);
    //    $smarty->assign('userData', $userData);

    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $operationnum = $_POST["operationnum"];
    $storeId = $_POST["storeId"];

    if (isset($operationnum) && $operationnum != -1) {
        $message = " عرض تحويلات المخازن لرقم الايصال: " . $operationnum . "";
        $smarty->assign('message', $message);
        showByoperationnum($operationnum);
    } elseif (isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "" && $operationnum == -1) {

        $message = " عرض تحويلات المخازن من تاريخ: " . $startDate . "الى تاريخ:" . $endDate;
        $smarty->assign('message', $message);
        showByDate($startDate, $endDate, $storeId);
    } else {
        $message = " عرض تحويلات المخازن من تاريخ: " . date("Y-m-d") . " الى تاريخ: " . date("Y-m-d");
        $smarty->assign('message', $message);
        showByDate(date("Y-m-d"), date("Y-m-d"), $storeId);
    }


    $smarty->display("storemovementview/showdetails.html");


    $smarty->assign("customCheck", 1);
}
if ($do == 'addprocat') {
    //here the permssion check
    include_once("../public/authentication.php");

    // here the function that do the action



    $smarty->assign("searchinonestore", $_SESSION['searchinonestore']);
    if ($_SESSION['searchinonestore'] == 0) {
        if ($_SESSION['storeids'] == 0) {
            $stores = $myStoreEx->queryByConditions();
        } else {
            $stores = $myStoreEx->queryByConditions(' and store.storeId in (' . $_SESSION['storeids'] . ')');
        }
        $smarty->assign("stores", $stores);
        $store = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("store", $store);
        $smarty->assign("manyParcodesstoreidfrom", $_SESSION['storeid']);
    } else {
        $store = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("store", $store);
        $smarty->assign("manyParcodesstoreidfrom", $_SESSION['storeid']);
    }





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


    //السائقين
    $drivers = $userEX->queryWithGroupName("سائقين");
    $smarty->assign("drivers", $drivers);


    $smarty->assign("storenegative", $_SESSION['storenegative']);

    ##get client serial
    $DBName = ConnectionProperty::getDatabase();
    if ($_SESSION['dbname'] != "" && isset($_SESSION['dbname'])) {
        $DBName = $_SESSION['dbname'];
    }
    // $nextId = $myStoremovementEx->getAutoIncrementValue($DBName);
    $nextId = $myStoremovementEx->queryAlloperationnum();
    $last_val = $nextId[0];

    $last = $last_val->operationnum + 1;

    $smarty->assign("nextId", $last);

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

    //here the smarty templates
    $smarty->display("storemovementview/addprocat.html");

    $smarty->assign("customStoremovement", 1);
}
//returndelete
elseif ($do == "returndelete") {
    include_once("../public/authentication.php");

    $transferproductId = $_GET['transferproductid'];

    $operationnum = $_GET['operationnum'];

    // here the function that do the action
    $productsAfterValid = returndelete($transferproductId); //$operationnum
    if ($productsAfterValid[1] == 1) {


        header("location:?do=sucess");
    } elseif ($productsAfterValid[1] == 2) {

        $url = "storemovementController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لقد حدث خطأ اثناء اجراء العملية";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    } else {
        $url = "storemovementController.php?do=";
        $smarty->assign('urldirect', $url);
        $note = "لا يوجد بالمخزن الكمية الكافية لتحويل المنتجات";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    }
} elseif ($do == "returndelete2") {
    include_once("../public/authentication.php");

    //$transferproductId = $_GET['transferproductid'];

    $operationnum = $_GET['operationnum'];

    // here the function that do the action
    $productsAfterValid = returndelete2($operationnum);
    if ($productsAfterValid[1] == 1) {
        makeStoreMovementDailyEntry($mainData, $detailArr, 3);


        header("location:?do=sucess");
    } elseif ($productsAfterValid[1] == 2) {

        $url = "storemovementController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لقد حدث خطأ اثناء اجراء العملية";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    } else {
        makeStoreMovementDailyEntry($mainData, $detailArr, 0);

        $url = "storemovementController.php?do=";
        $smarty->assign('urldirect', $url);
        $note = "لا يوجد بالمخزن الكمية الكافية لتحويل المنتجات";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    }
}
//tempdelete
elseif ($do == "tempdelete") {
    include_once("../public/authentication.php");

    $transferproductId = $_GET['transferproductid'];
    // here the function that do the action

    $productsAfterValid = tempdelete($transferproductId);
    if ($productsAfterValid[1] == 1) {
        header("location:?do=sucess");
    } elseif ($productsAfterValid[1] == 2) {
        $url = "storemovementController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لقد حدث خطأ اثناء اجراء العملية";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    } else {
        $url = "storemovementController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لا يوجد بالمخزن الكمية الكافية لتحويل المنتجات";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    }
} elseif ($do == "tempdelete2") {
    include_once("../public/authentication.php");

    // $transferproductId = $_GET['transferproductid'];
    // here the function that do the action
    $operationnum = $_GET['operationnum'];

    $productsAfterValid = tempdelete2($operationnum);
    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
        if ($productsAfterValid[1] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
        } elseif ($productsAfterValid[1] == 2) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
        } else {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success', 'note' => 'لا يوجد بالمخزن الكمية الكافية لتحويل المنتجات');
        }
        echo json_encode($data);
        exit();
    } else {
        if ($productsAfterValid[1] == 1) {
            header("location:?do=sucess");
        } elseif ($productsAfterValid[1] == 2) {
            $url = "storemovementController.php?do=show";
            $smarty->assign('urldirect', $url);
            $note = "لقد حدث خطأ اثناء اجراء العملية";

            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            $url = "storemovementController.php?do=show";
            $smarty->assign('urldirect', $url);
            $note = "لا يوجد بالمخزن الكمية الكافية لتحويل المنتجات";

            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        }
    }
}
//edit  transfer
elseif ($do == "editprint") {

    //here the permssion check
    include_once("../public/authentication.php");

    $loadData = editprint();
    $smarty->assign("loadData", $loadData);



    $smarty->display("storemovementview/editprint.html");


    $smarty->assign("customPrint", 1);
}
//edit  transfer
elseif ($do == "edit") {
    //here the permssion check
    include_once("../public/authentication.php");
    $_GET['operationnum'] = $_GET['id'];
    $loadData = editshow();
    foreach ($loadData[1] as $data) {
        $data->productquantity = getProductAmountInStore($data->storeidfrom, $data->productid);
    }
    $smarty->assign("operationdata", $loadData[0]);
    $smarty->assign("loadData", $loadData[1]);
    $smarty->assign("oldperationdata", $loadData[2]);
    $smarty->assign("oldloadData", $loadData[3]);

    $smarty->display("storemovementview/edit.html");
} elseif ($do == "update") {

    //here the permssion check
    include_once("../public/authentication.php");
    //delete first
    $operationnum = $_GET['operationnum'];
    $productsAfterValid = tempdelete2($operationnum);

    //then add new
    // here the function that do the action
    if ($Programsettingdata->workerbetweenstores == 0 || (int) $_POST['recieveType'] == 1) {
        $productsAfterValid = addDealWithStoreFromOnly();
        makeStoreMovementDailyEntry($mainData, $detailArr, 1);
        if ($productsAfterValid[0] === "error") { //coming from rollback
            header("location:?do=error");
        } else {
            header("location:?do=sucess");
        }
    } else {

        $productsAfterValid = add();
        $operationNo = $productsAfterValid[2];
        if ($productsAfterValid[0] === "error") { //coming from rollback
            header("location:?do=error");
        } elseif ($productsAfterValid[1] == '0') {
            makeStoreMovementDailyEntry($mainData, $detailArr, 0);
            header("location:?do=sucess");
        } else {
            makeStoreMovementDailyEntry($mainData, $detailArr, 0);
            if ($productsAfterValid[1] == '1') {
                header('Location: storemovementController.php?do=editorder&on=' . $operationNo . '');
            } else {
                header('Location: storemovementController.php?do=editshow&operationnum=' . $operationNo . '');
            }
        }
    }
} elseif ($do == "editorder") {
    //here the permssion check
    //    include_once("../public/authentication.php");

    $loadData = editorder();
    $smarty->assign("loadData", $loadData);

    if ($loadData[0]->storetype == 0) {
        $type = ' اذن تحويل بين المخازن';
        $smarty->assign("type", $type);
    } elseif ($loadData[0]->storetype == 1) {
        $type = ' اذن تحميل بين المخازن';
        $smarty->assign("type", $type);
    } elseif ($loadData[0]->storetype == 2) {
        $type = ' اذن ارتجاع بين المخازن';
        $smarty->assign("type", $type);
    }
    $UserId = $_SESSION['userid'];
    $userData = $userDAO->load($UserId);

    $smarty->assign("username", $userData->username);
    $smarty->display("storemovementview/editorder.html");
}
//recieve
elseif ($do == "recieve") {
    //here the permssion check
    include_once("../public/authentication.php");

    $loadData = edit();
    $smarty->assign("loadData", $loadData);

    //عامل التوصيل
    $deliveryWorkers = $userEX->queryWithGroupId(6);
    $smarty->assign("deliveryWorkers", $deliveryWorkers);

    $smarty->display("storemovementview/recieve.html");
} elseif ($do == "prepare") {
    try {
        $orderno = $_GET['operationnum'];
        $myStoremovementEx->markMoveAsPreparedByoperationnum($_SESSION['userid'], $orderno);

        header("location:?do=sucess");
    } catch (Exception $exc) {
        header("location:?do=error");
    }
}
//
elseif ($do == "recieveproduct") {
    //Transaction
    $mytransactions2 = new Transaction();
    try {
        $id = (int) $_REQUEST["id"];
        $record = $myStoremovementRecord->load($id);
        if ($record->recieveType == 1) { //user @recieveUserid مشرف المخزن
            $record->recieveUserid = $_SESSION['userid'];
            $record->recieveTime = date('Y-m-d H:i:s');
        } else { //$delivererid
            $delivererid = $_POST["delivererid"];
            $record->delivererid = $delivererid;
            $record->deliverdate = date('Y-m-d H:i:s');
        }

        $myStoremovementRecord->update($record);
        addDealWithStoreToOnly($record);
        $mytransactions2->commit();
        makeStoreMovementDailyEntry($mainData, $detailArr, 2);
        header("location:?do=sucess");
    } catch (Exception $e) {
        $mytransactions2->rollback();
        header("location:?do=error");
    }
}
//edit  update
elseif ($do == "recieveAllproducts") {
    //Transaction
    $mytransactions2 = new Transaction();
    try {
        $operationnum = $_GET['operationnum'];
        $Storemovement_data = $myStoremovementEx->operationData2($operationnum);
        foreach ($Storemovement_data as $record) {
            if ($record->recieveType == 1) { //user @recieveUserid مشرف المخزن
                $record->recieveUserid = $_SESSION['userid'];
                $record->recieveTime = date('Y-m-d H:i:s');
            } else { //$delivererid
                $delivererid = $_POST["delivererid"];
                $record->delivererid = $delivererid;
                $record->deliverdate = date('Y-m-d H:i:s');
            }

            $myStoremovementRecord->update($record);
            addDealWithStoreToOnly($record);
        }
        makeStoreMovementDailyEntry($mainData, $detailArr, 2);
        $mytransactions2->commit();
        header("location:?do=sucess");
    } catch (Exception $e) {
        $mytransactions2->rollback();
        header("location:?do=error");
    }
}
//edit  update
elseif ($do == "executeOperation") {
    //here the permssion check
    include_once("../public/authentication.php");

    // here the function that do the action
    executeOperation();

    $message = " عرض تحويلات المخازن من تاريخ: " . date("Y-m-d") . " الى تاريخ: " . date("Y-m-d");
    $smarty->assign('message', $message);
    showByDate(date("Y-m-d"), date("Y-m-d"));

    $smarty->display("storemovementview/show.html");

    $smarty->assign("customCheck", 1);
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
}
///////////////eman/////////////////
//edit  transfer
elseif ($do == "editshow") {
    //here the permssion check
    include_once("../public/authentication.php");
    $loadData = editshow();
    $smarty->assign("perationdata", $loadData[0]);
    $smarty->assign("loadData", $loadData[1]);
    $smarty->assign("oldperationdata", $loadData[2]);
    $smarty->assign("oldloadData", $loadData[3]);


    $smarty->display("storemovementview/editshow.html");
} elseif ($do == "editshowstyle2") {
    //here the permssion check
    include_once("../public/authentication.php");

    $loadData = editshow();


    $smarty->assign("perationdata", $loadData[0]);
    $smarty->assign("loadData", $loadData[1]);


    $smarty->assign("oldperationdata", $loadData[2]);


    $smarty->assign("oldloadData", $loadData[3]);


    $smarty->display("otherstoremovementview/editshow.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}
$smarty->assign("customStoremovement", 1);

$smarty->assign('customValidation', 1);
//here the global templates
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} else {
    if ($do != "editorder")
        $smarty->display("footer.html");
}

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

//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 getCategoryChilds($parentid = 0) {
    global $productCatExt;
    global $productCatDAO;
    //load cat
    $parentobject = $productCatDAO->load($parentid);
    $childsArray = $productCatExt->getChilds($parentid);

    return array($parentobject, $childsArray);
}

// add in storemovement tbl
function add() {
    //to use the variable out side the funcion
    global $myStoremovement;
    global $myStoremovementRecord;
    global $myStoremovementEx;

    global $myStoredetailRecord;
    global $Storedetail;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    ##for daily entry
    global $mainData;
    global $detailArr;

    //Transaction
    $mytransactions = new Transaction();
    $storeDetailIds = $sizeColrDetailIds = [];
    try {
        $storeidfrom = $_POST['storeidfrom'];
        $storeidto = $_POST['storeidto'];

        $productItr = $_POST['productitr'];
        $operationnum = $_POST['operationnum'];
        if (isset($_POST['edit']) && $_POST['edit'] == 1) {
            $oldopNum = $operationnum;
        }
        $driverid = $_POST['driver'];
        $drivertimeout = $_POST['drivertimeout'];
        $whatPrice = $_POST['whatPrice'];
        //print_r("productItr".$productItr."<br>");

        $h = 1;
        for ($h = 1; $h <= $productItr; $h++) {
            $productId = $_POST['product' . $h . ''];
            $transferproductAmount = $_POST['productamount' . $h . ''];

            if (isset($productId) && !empty($productId) && $productId != '-1' && $productId != '') {
                //get storefrom productquantity before change
                //print_r("storeidfrom".$storeidfrom."<br>");
                //print_r("productId".$productId."<br>");
                $sizeId = 0;
                $colorId = 0;
                $sizeColorStoreDetailId = 0;
                if (strpos($productId, "hasSizeColor") !== false) {
                    $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                    $productId = $productIdComplex[0];
                    $sizeId = $productIdComplex[1];
                    $colorId = $productIdComplex[2];
                    $theStoreId = $storeidfrom;
                    $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $theStoreId, $sizeId, $colorId);
                }

                $storedetailFromData = getStoredetailData($storeidfrom, $productId, $sizeColorStoreDetailId, $sizeId, $colorId);

                $allStoredetailFromData = $storedetailFromData[0];
                $storedetailFromId = $storedetailFromData[1];
                $productquantityFromBefore = $storedetailFromData[2];



                if ($storedetailFromId < 1) {

                    $Storedetail->productid = $productId;
                    $Storedetail->productquantity = 0;
                    $Storedetail->storedetaildate = $today;
                    $Storedetail->storeid = $storeidfrom;
                    $Storedetail->userid = $_SESSION['userid'];


                    //print_r($Storedetail);
                    $myStoredetailRecord->insert($Storedetail);

                    if ($sizeId > 0 && $colorId > 0) { //size and color product add it also to sizeColorStoreDetail table
                        //try to copy from existing data in store 1
                        $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, 1, $sizeId, $colorId);
                        $sizeColorStoreDetailIdCheck = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidfrom, $sizeId, $colorId);
                        if (!isset($sizeColorStoreDetailIdCheck) || empty($sizeColorStoreDetailIdCheck)) {
                            $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

                            $sizeColorStoreDetail->storeid = $storeidfrom;
                            $sizeColorStoreDetail->quantity = 0;
                            $sizeColorStoreDetail->userid = $_SESSION['userid'];
                            $sizeColorStoreDetail->sysdate = date("Y-m-d H:i:s");

                            $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
                        }
                    }


                    $storedetailFromData = getStoredetailData($storeidfrom, $productId, $sizeColorStoreDetailId, $sizeId, $colorId);

                    $allStoredetailFromData = $storedetailFromData[0];
                    $storedetailFromId = $storedetailFromData[1];
                    $productquantityFromBefore = $storedetailFromData[2];
                }



                //check if productquantityFromBefore greater than 0 or not
                $productsBeforeValid = 1;
                if ($productquantityFromBefore > 0 && count($allStoredetailFromData) > 0) {
                    $productsAfterValid = $productquantityFromBefore - $transferproductAmount;

                    if ($productsAfterValid >= 0) {

                        $productsBeforeValid = 1;
                    } else {

                        $productsBeforeValid = 0;
                        //return $productsBeforeValid;
                    }
                } else {

                    $productsBeforeValid = 0;
                    //return $productsBeforeValid;
                }
            }
        }


        $h;
        $i = 1;
        for ($h = 1; $h <= $productItr; $h++) {
            $productId = $_POST['product' . $h . ''];
            $transferproductAmount = $_POST['productamount' . $h . ''];
            $price = $_POST['price' . $h . ''];
            //$currentquantity = $_POST['currentquantity' . $h . ''];
            $expireDate = $_POST['proSerials' . $h . ''];
            $comment = $_POST['comment' . $h . ''];
            $sizeId = 0;
            $colorId = 0;
            $sizeColorStoreDetailId = 0;
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
                $theStoreId = $storeidfrom;
                $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $theStoreId, $sizeId, $colorId);
            }

            if (isset($productId) && !empty($productId) && $productId != '-1' && $productId != '') {
                //add in storemovement tbl
                $myStoremovement->conditions = 0;
                $myStoremovement->storeidfrom = $storeidfrom;
                $myStoremovement->storeidto = $storeidto;
                $myStoremovement->transferproductdate = date("Y-m-d");
                $myStoremovement->userid = $_SESSION["userid"];
                $myStoremovement->productid = $productId;
                $myStoremovement->transferproductamount = $transferproductAmount;
                $myStoremovement->operationnum = $operationnum;
                $myStoremovement->storetype = 0; //#تحويل بين المخازن
                $myStoremovement->priceType = $whatPrice; //#تحويل بين المخازن
                $myStoremovement->price = $price; //#تحويل بين المخازن
                //لو تعديل
                if (isset($oldopNum))
                    $myStoremovement->deloperationnum = $oldopNum;


                $myStoremovement->sizeid = $sizeId;
                $myStoremovement->colorid = $colorId;
                $myStoremovement->expireDate = $expireDate;
                $myStoremovement->comment = $comment;
                $myStoremovement->maincomment = $_POST['comment'];
                $myStoremovement->recieveType = $_POST['recieveType'];

                if ($Programsettingdata->workerbetweenstores == 0) {
                    $myStoremovement->driverid = $driverid;
                    $myStoremovement->drivertimeout = $drivertimeout;
                    $myStoremovement->driverdate = date("Y-m-d H:i:s");
                }
                if (isset($productId) && $productId != '-1') {


                    //insert data in stormovement
                    if ($i == 1) {
                        $spData = $myStoremovementEx->callInsertUniqueOptNumSP($myStoremovement);

                        $transferproductId = $spData->id;
                        $operationnum = $spData->optnum;


                        $myStoremovement->operationnum = $operationnum;

                        //update price
                        if (isset($price) && $price > 0) {
                            $myStoremovementEx->updateFirstPrice($price, $transferproductId);
                        }

                        $mainData = $myStoremovement;
                        $i++;
                    } else {
                        $transferproductId = $myStoremovementRecord->insert($myStoremovement);
                    }
                    $myStoremovement->transferproductid = $transferproductId;

                    //////////////**Store From**///////////////////////////
                    //get storefrom productquantity before change
                    $storedetailFromData = getStoredetailData($storeidfrom, $productId, $sizeColorStoreDetailId, $sizeId, $colorId);

                    $allStoredetailFromData = $storedetailFromData[0];
                    $storedetailFromId = $storedetailFromData[1];
                    $productquantityFromBefore = $storedetailFromData[2];

                    //update productquantity in storedetail
                    $productquantityFromAfter = decreaseProductQuantity($storedetailFromId, $productquantityFromBefore, $transferproductAmount, $sizeColorStoreDetailId, $sizeId, $colorId, $myStoremovement);


                    //insert in storereport
                    insertStorereport($productId, $storeidfrom, $transferproductAmount, $productquantityFromBefore, $productquantityFromAfter, 1, $transferproductId, "تحويل منتجات من المخزن", "storemovementController.php", $sizeId, $colorId);



                    //////////////**Store To**///////////////////////////
                    //get storeto productquantity before change
                    $sizeColorStoreDetailIdTo = 0;
                    if ($sizeId > 0 && $colorId > 0) { //size and color product add it also to sizeColorStoreDetail table
                        //try to copy from existing data in store 1
                        $sizeColorStoreDetailIdTo = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidto, $sizeId, $colorId);
                    }
                    $storedetailToData = getStoredetailData($storeidto, $productId, $sizeColorStoreDetailIdTo, $sizeId, $colorId);

                    $allStoredetailToData = $storedetailToData[0];
                    $storedetailToId = $storedetailToData[1];
                    $productquantityToBefore = $storedetailToData[2];

                    if (count($allStoredetailToData) > 0) {

                        //update productquantity in storedetail
                        $productquantityToAfter = increaseProductQuantity($storedetailToId, $productquantityToBefore, $transferproductAmount, $sizeColorStoreDetailIdTo, $sizeId, $colorId, $myStoremovement);


                        //insert in storereport
                        insertStorereport($productId, $storeidto, $transferproductAmount, $productquantityToBefore, $productquantityToAfter, 0, $transferproductId, "تحويل منتجات إلى المخزن", "storemovementController.php", $sizeId, $colorId);
                    } else {
                        //insert in storedetail tbl
                        insertStoredetail($storeidto, $productId, $transferproductAmount, $sizeColorStoreDetailIdTo, $sizeId, $colorId);
                        increaseHandleBuyPricesHistoryBook($myStoremovement);
                        increaseProductParcodeSerialQuantity($myStoremovement, $storeidto);

                        //insert in storereport
                        insertStorereport($productId, $storeidto, $transferproductAmount, 0, $transferproductAmount, 0, $transferproductId, "تحويل منتجات إلى المخزن", "storemovementController.php", $sizeId, $colorId);
                    }
                    //
                    $obj = new stdClass();
                    $obj->productid = $productId;
                    $obj->amount = $transferproductAmount;
                    array_push($detailArr, $obj);
                }

                if ($sizeId == 0 && $colorId == 0)
                {
                    $storeDetailIds[] = $storedetailFromId;
                    $storeDetailIds[] = $storedetailToId;
                }
                else{
                    $sizeColrDetailIds[] = $sizeColorStoreDetailId;
                    $sizeColrDetailIds[] = $sizeColorStoreDetailIdTo;
                }   
            }
        }

        $add_print = $_POST['add_print'];
        $product_arr = array($productsBeforeValid, $add_print, $operationnum);
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $product_arr = array('error');
        //        echo $ex;
    }
    markStoreDetailNotInUse($storeDetailIds, $sizeColrDetailIds);
    return $product_arr;
}

function addAllStoreProducts() {
    //to use the variable out side the funcion
    global $myStoremovement;
    global $myStoremovementRecord;
    global $myStoremovementEx;

    global $myStoredetailRecord;
    global $Storedetail;

    global $productExt;
    global $sizeColorStoreDetailEX;

    ##for daily entry
    global $mainData;
    global $detailArr;

    //Transaction
    $mytransactions = new Transaction();
    try {
        $storeidfrom = (int) $_POST['storeidfrom'];
        $storeidto = (int) $_POST['storeidto'];

        $operationnum = $_POST['operationnum'];

        $driverid = $_POST['driver'];
        $drivertimeout = $_POST['drivertimeout'];
        //print_r("productItr".$productItr."<br>");


        $count = 0;
        $start = 0;
        $limit = 30;
        $end = $start + $limit;
        $all_products_count = $productExt->getProductsCount();
        ####
        //check if productquantityFromBefore greater than 0 or not
        $productsBeforeValid = 1;
        for ($i = $start; $i <= $all_products_count->productId; $i += $limit) {
            $allproduct = $productExt->queryAllOrderedLimitedSimpleInStore($storeidfrom, $start, $limit);
            foreach ($allproduct as $value) {
                $productId = $value->productId;
                $transferproductAmount = $value->productquantity;
                $sizeId = (int) $value->sizeid;
                $colorId = (int) $value->colorid;

                #############################################################
                //add in storemovement tbl
                $myStoremovement->conditions = 0;
                $myStoremovement->storeidfrom = $storeidfrom;
                $myStoremovement->storeidto = $storeidto;
                $myStoremovement->transferproductdate = date("Y-m-d");
                $myStoremovement->userid = $_SESSION["userid"];
                $myStoremovement->productid = $productId;
                $myStoremovement->transferproductamount = $transferproductAmount;
                $myStoremovement->operationnum = $operationnum;
                $myStoremovement->storetype = 0; //#تحويل بين المخازن
                $myStoremovement->sizeid = $sizeId;
                $myStoremovement->colorid = $colorId;

                if ($Programsettingdata->workerbetweenstores == 0) {
                    $myStoremovement->driverid = $driverid;
                    $myStoremovement->drivertimeout = $drivertimeout;
                    $myStoremovement->driverdate = date("Y-m-d H:i:s");
                }
                if (isset($productId) && $productId != '-1') {


                    //insert data in stormovement
                    if ($i == 1) {
                        $spData = $myStoremovementEx->callInsertUniqueOptNumSP($myStoremovement);

                        $transferproductId = $spData->id;
                        $operationnum = $spData->optnum;

                        $myStoremovement->operationnum = $operationnum;
                        $mainData = $myStoremovement;
                        $i++;
                    } else {
                        $transferproductId = $myStoremovementRecord->insert($myStoremovement);
                    }
                    $myStoremovement->transferproductid = $transferproductId;

                    //////////////**Store From**///////////////////////////
                    //get storefrom productquantity before change
                    $sizeColorStoreDetailIdFrom = 0;
                    if ($sizeId > 0 && $colorId > 0) {
                        $sizeColorStoreDetailIdFrom = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidfrom, $sizeId, $colorId);
                    }
                    $storedetailFromData = getStoredetailData2NoConditions($storeidfrom, $productId, $sizeColorStoreDetailIdFrom, $sizeId, $colorId);

                    $allStoredetailFromData = $storedetailFromData[0];
                    $storedetailFromId = $storedetailFromData[1];
                    $productquantityFromBefore = $storedetailFromData[2];



                    if ($storedetailFromId < 1) {

                        $Storedetail->productid = $productId;
                        $Storedetail->productquantity = 0;
                        $Storedetail->storedetaildate = $today;
                        $Storedetail->storeid = $storeidfrom;
                        $Storedetail->userid = $_SESSION['userid'];


                        //print_r($Storedetail);
                        $myStoredetailRecord->insert($Storedetail);

                        if ($sizeId > 0 && $colorId > 0) { //size and color product add it also to sizeColorStoreDetail table
                            //try to copy from existing data in store 1
                            $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, 1, $sizeId, $colorId);
                            $sizeColorStoreDetailIdCheck = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidfrom, $sizeId, $colorId);
                            if (!isset($sizeColorStoreDetailIdCheck) || empty($sizeColorStoreDetailIdCheck)) {
                                $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

                                $sizeColorStoreDetail->storeid = $storeidfrom;
                                $sizeColorStoreDetail->quantity = 0;
                                $sizeColorStoreDetail->userid = $_SESSION['userid'];
                                $sizeColorStoreDetail->sysdate = date("Y-m-d H:i:s");

                                $sizeColorStoreDetailIdFrom = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
                            }
                        }

                        $storedetailFromData = getStoredetailData2NoConditions($storeidfrom, $productId, $sizeColorStoreDetailIdFrom, $sizeId, $colorId);

                        $allStoredetailFromData = $storedetailFromData[0];
                        $storedetailFromId = $storedetailFromData[1];
                        $productquantityFromBefore = $storedetailFromData[2];
                    }
                    //check if productquantityFromBefore greater than 0 or not
                    if ($productquantityFromBefore > 0 && count($allStoredetailFromData) > 0) {
                        $productsAfterValid = $productquantityFromBefore - $transferproductAmount;

                        if ($productsAfterValid >= 0) {

                            $productsBeforeValid = 1;
                        } else {

                            $productsBeforeValid = 0;
                            //return $productsBeforeValid;
                        }
                    } else {

                        $productsBeforeValid = 0;
                        //return $productsBeforeValid;
                    }
                    //update productquantity in storedetail
                    $productquantityFromAfter = decreaseProductQuantity($storedetailFromId, $productquantityFromBefore, $transferproductAmount, $sizeColorStoreDetailIdFrom, $sizeId, $colorId, $myStoremovement);


                    //insert in storereport
                    insertStorereport($productId, $storeidfrom, $transferproductAmount, $productquantityFromBefore, $productquantityFromAfter, 1, $transferproductId, "تحويل منتجات من المخزن", "storemovementController.php", $sizeId, $colorId);



                    //////////////**Store To**///////////////////////////
                    //get storeto productquantity before change
                    $sizeColorStoreDetailIdTo = 0;
                    if ($sizeId > 0 && $colorId > 0) {
                        $sizeColorStoreDetailIdTo = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidto, $sizeId, $colorId);
                    }
                    $storedetailToData = getStoredetailData2NoConditions($storeidto, $productId, $sizeColorStoreDetailIdTo, $sizeId, $colorId);

                    $allStoredetailToData = $storedetailToData[0];
                    $storedetailToId = $storedetailToData[1];
                    $productquantityToBefore = $storedetailToData[2];

                    if (count($allStoredetailToData) > 0) {

                        //update productquantity in storedetail
                        $productquantityToAfter = increaseProductQuantity($storedetailToId, $productquantityToBefore, $transferproductAmount, $sizeColorStoreDetailIdTo, $sizeId, $colorId, $myStoremovement);


                        //insert in storereport
                        insertStorereport($productId, $storeidto, $transferproductAmount, $productquantityToBefore, $productquantityToAfter, 0, $transferproductId, "تحويل منتجات إلى المخزن", "storemovementController.php", $sizeId, $colorId);
                    } else {
                        //insert in storedetail tbl
                        insertStoredetail($storeidto, $productId, $transferproductAmount, $sizeColorStoreDetailIdTo, $sizeId, $colorId);
                        increaseHandleBuyPricesHistoryBook($myStoremovement);
                        increaseProductParcodeSerialQuantity($myStoremovement, $storeidto);

                        //insert in storereport
                        insertStorereport($productId, $storeidto, $transferproductAmount, 0, $transferproductAmount, 0, $transferproductId, "تحويل منتجات إلى المخزن", "storemovementController.php", $sizeId, $colorId);
                    }
                    //
                    $obj = new stdClass();
                    $obj->productid = $productId;
                    $obj->amount = $transferproductAmount;
                    array_push($detailArr, $obj);
                }
            }
            //
            $start += $limit;
            $end += $limit;
        }


        $add_print = $_POST['add_print'];
        $product_arr = array($productsBeforeValid, $add_print, $operationnum);
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $product_arr = array('error');
    }
    return $product_arr;
}

// add in storemovement tbl
function addDealWithStoreFromOnly() {
    //to use the variable out side the funcion
    global $myStoremovement;
    global $myStoremovementRecord;
    global $myStoremovementEx;

    global $myStoredetailRecord;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;
    global $Storedetail;

    ##for daily entry
    global $mainData;
    global $detailArr;

    //Transaction
    $mytransactions = new Transaction();
    try {
        $storeidfrom = $_POST['storeidfrom'];
        $storeidto = $_POST['storeidto'];

        $productItr = $_POST['productitr'];
        $operationnum = $_POST['operationnum'];

        $driverid = $_POST['driver'];
        $drivertimeout = $_POST['drivertimeout'];
        $drivertimeout = $_POST['drivertimeout'];
        //print_r("productItr".$productItr."<br>");

        $h = 1;
        for ($h = 1; $h <= $productItr; $h++) {
            $productId = $_POST['product' . $h . ''];
            $transferproductAmount = $_POST['productamount' . $h . ''];

            if (isset($productId) && !empty($productId) && $productId != '-1' && $productId != '') {
                //get storefrom productquantity before change
                //print_r("storeidfrom".$storeidfrom."<br>");
                //print_r("productId".$productId."<br>");
                $sizeId = 0;
                $colorId = 0;
                $sizeColorStoreDetailId = 0;
                if (strpos($productId, "hasSizeColor") !== false) {
                    $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                    $productId = $productIdComplex[0];
                    $sizeId = $productIdComplex[1];
                    $colorId = $productIdComplex[2];
                    $theStoreId = $storeidfrom;
                    $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $theStoreId, $sizeId, $colorId);
                }

                $storedetailFromData = getStoredetailData($storeidfrom, $productId, $sizeColorStoreDetailId, $sizeId, $colorId);

                $allStoredetailFromData = $storedetailFromData[0];
                $storedetailFromId = $storedetailFromData[1];
                $productquantityFromBefore = $storedetailFromData[2];



                if ($storedetailFromId < 1) {

                    $Storedetail->productid = $productId;
                    $Storedetail->productquantity = 0;
                    $Storedetail->storedetaildate = $today;
                    $Storedetail->storeid = $storeidfrom;
                    $Storedetail->userid = $_SESSION['userid'];


                    //print_r($Storedetail);
                    $myStoredetailRecord->insert($Storedetail);
                    if ($sizeId > 0 && $colorId > 0) { //size and color product add it also to sizeColorStoreDetail table
                        //try to copy from existing data in store 1
                        $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, 1, $sizeId, $colorId);
                        $sizeColorStoreDetailIdCheck = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidfrom, $sizeId, $colorId);
                        if (!isset($sizeColorStoreDetailIdCheck) || empty($sizeColorStoreDetailIdCheck)) {
                            $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

                            $sizeColorStoreDetail->storeid = $storeidfrom;
                            $sizeColorStoreDetail->quantity = 0;
                            $sizeColorStoreDetail->userid = $_SESSION['userid'];
                            $sizeColorStoreDetail->sysdate = date("Y-m-d H:i:s");

                            $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
                        }
                    }


                    $storedetailFromData = getStoredetailData($storeidfrom, $productId, $sizeColorStoreDetailId, $sizeId, $colorId);

                    $allStoredetailFromData = $storedetailFromData[0];
                    $storedetailFromId = $storedetailFromData[1];
                    $productquantityFromBefore = $storedetailFromData[2];
                }



                //check if productquantityFromBefore greater than 0 or not
                $productsBeforeValid = 1;
                if ($productquantityFromBefore > 0 && count($allStoredetailFromData) > 0) {
                    $productsAfterValid = $productquantityFromBefore - $transferproductAmount;

                    if ($productsAfterValid >= 0) {

                        $productsBeforeValid = 1;
                    } else {

                        $productsBeforeValid = 0;
                        //return $productsBeforeValid;
                    }
                } else {

                    $productsBeforeValid = 0;
                    //return $productsBeforeValid;
                }
            }
        }

        $h;
        $i = 1;
        for ($h = 1; $h <= $productItr; $h++) {
            $productId = $_POST['product' . $h . ''];
            $transferproductAmount = $_POST['productamount' . $h . ''];
            //$currentquantity = $_POST['currentquantity' . $h . ''];
            $expireDate = $_POST['proSerials' . $h . ''];
            $comment = $_POST['comment' . $h . ''];

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

                //add in storemovement tbl
                $myStoremovement->conditions = 0;
                $myStoremovement->storeidfrom = $storeidfrom;
                $myStoremovement->storeidto = $storeidto;
                $myStoremovement->transferproductdate = date("Y-m-d");
                $myStoremovement->userid = $_SESSION["userid"];
                $myStoremovement->productid = $productId;
                $myStoremovement->transferproductamount = $transferproductAmount;
                $myStoremovement->operationnum = $operationnum;
                $myStoremovement->driverid = $driverid;
                $myStoremovement->drivertimeout = $drivertimeout;
                $myStoremovement->driverdate = date("Y-m-d H:i:s");
                $myStoremovement->storetype = 0; //#تحويل بين المخازن
                $myStoremovement->sizeid = $sizeId;
                $myStoremovement->colorid = $colorId;
                $myStoremovement->expireDate = $expireDate;
                $myStoremovement->comment = $comment;
                $myStoremovement->maincomment = $_POST['comment'];
                $myStoremovement->recieveType = $_POST['recieveType'];

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


                    //insert data in stormovement
                    if ($i == 1) {
                        $spData = $myStoremovementEx->callInsertUniqueOptNumSP($myStoremovement);

                        $transferproductId = $spData->id;
                        $operationnum = $spData->optnum;
                        #
                        $myStoremovement->transferproductid = $transferproductId;
                        $mainData = $myStoremovement;
                        $i++;
                    } else {
                        $transferproductId = $myStoremovementRecord->insert($myStoremovement);
                    }
                    $myStoremovement->transferproductid = $transferproductId;

                    //////////////**Store From**///////////////////////////
                    //get storefrom productquantity before change
                    $storedetailFromData = getStoredetailData($storeidfrom, $productId, $sizeColorStoreDetailId, $sizeId, $colorId);

                    $allStoredetailFromData = $storedetailFromData[0];
                    $storedetailFromId = $storedetailFromData[1];
                    $productquantityFromBefore = $storedetailFromData[2];

                    //update productquantity in storedetail
                    $productquantityFromAfter = decreaseProductQuantity($storedetailFromId, $productquantityFromBefore, $transferproductAmount, $sizeColorStoreDetailId, $sizeId, $colorId, $myStoremovement);


                    //insert in storereport
                    insertStorereport($productId, $storeidfrom, $transferproductAmount, $productquantityFromBefore, $productquantityFromAfter, 1, $transferproductId, "تحويل منتجات من المخزن", "storemovementController.php", $sizeId, $colorId);
                    //
                    $obj = new stdClass();
                    $obj->productid = $productId;
                    $obj->amount = $transferproductAmount;
                    array_push($detailArr, $obj);
                }
            }
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $productsBeforeValid = array('error');
    }
    return $productsBeforeValid;
}

// add in storemovement tbl
function addDealWithStoreToOnly($storeMovementObject) {
    //to use the variable out side the funcion
    global $myStoremovement;
    global $myStoremovementRecord;

    global $myStoredetailRecord;
    global $Storedetail;
    global $sizeColorStoreDetailEX;

    ##for daily entry
    global $mainData;
    global $detailArr;

    //Transaction
    if ($_GET['do'] != "recieveproduct")
        $mytransactions = new Transaction();

    try {
        $storeidto = $storeMovementObject->storeidto;
        $productId = $storeMovementObject->productid;

        $mainData = $storeMovementObject;


        $sizeId = $storeMovementObject->sizeid;
        $colorId = $storeMovementObject->colorid;
        $transferproductAmount = $storeMovementObject->transferproductamount;
        $transferproductId = $storeMovementObject->transferproductid;

        if (isset($productId) && !empty($productId) && $productId != '-1' && $productId != '') {
            if (isset($productId) && $productId != '-1') {
                //////////////**Store To**///////////////////////////
                //get storeto productquantity before change
                $sizeColorStoreDetailIdTo = 0;
                if ($sizeId > 0 && $colorId > 0) { //size and color product add it also to sizeColorStoreDetail table
                    //try to copy from existing data in store 1
                    $sizeColorStoreDetailIdTo = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidto, $sizeId, $colorId);
                }
                $storedetailToData = getStoredetailData($storeidto, $productId, $sizeColorStoreDetailIdTo, $sizeId, $colorId);

                $allStoredetailToData = $storedetailToData[0];
                $storedetailToId = $storedetailToData[1];
                $productquantityToBefore = $storedetailToData[2];

                if (count($allStoredetailToData) > 0) {

                    //update productquantity in storedetail
                    $productquantityToAfter = increaseProductQuantity($storedetailToId, $productquantityToBefore, $transferproductAmount, $sizeColorStoreDetailIdTo, $sizeId, $colorId, $storeMovementObject);


                    //insert in storereport
                    insertStorereport($productId, $storeidto, $transferproductAmount, $productquantityToBefore, $productquantityToAfter, 0, $transferproductId, "تحويل منتجات إلى المخزن", "storemovementController.php", $sizeId, $colorId);
                } else {
                    //insert in storedetail tbl
                    insertStoredetail($storeidto, $productId, $transferproductAmount, $sizeColorStoreDetailIdTo, $sizeId, $colorId);
                    increaseHandleBuyPricesHistoryBook($storeMovementObject);
                    increaseProductParcodeSerialQuantity($storeMovementObject, $storeidto);

                    //insert in storereport
                    insertStorereport($productId, $storeidto, $transferproductAmount, 0, $transferproductAmount, 0, $transferproductId, "تحويل منتجات إلى المخزن", "storemovementController.php", $sizeId, $colorId);
                }
                //
                $obj = new stdClass();
                $obj->productid = $productId;
                $obj->amount = $transferproductAmount;
                array_push($detailArr, $obj);
            }
        }


        //
        if ($_GET['do'] != "recieveproduct")
            $mytransactions->commit();
    } catch (Exception $ex) {
        //
        if ($_GET['do'] != "recieveproduct")
            $mytransactions->rollback();
    }
}

//show
function showAll() {
    //to use the variable out side the funcion
    global $myStoremovementEx;
    global $smarty;

    // get the all colums number
    $storemovementData = $myStoremovementEx->queryWithOrder();

    // assign your db results to the template
    $smarty->assign('storemovementData', $storemovementData);
}

//show
function showByDate($startDate, $endDate, $storeId = "") {
    //to use the variable out side the funcion
    global $myStoremovementEx;
    global $smarty;
    global $Programsettingdata;
    global $userDAO;
    $queryString = "";
    if ($Programsettingdata->workerbetweenstores == 0) {
        //getall
        //$queryString = " and driverid > 0";
    } elseif ($Programsettingdata->workerbetweenstores == 1) {
        $queryString .= " and (driverid is null or driverid=0) ";
    }
    $storeQuery = '';
    if ($storeId != '-1' && $storeId != '') {
        $queryString .= ' and  ( storemovement.storeidfrom  = ' . $storeId . '  or storemovement.storeidto = ' . $storeId . ' )';
    } else if ($_SESSION['searchinonestore'] == 0) {
        if ($_SESSION['storeids'] != 0) {
            $queryString .= ' and  ( storemovement.storeidfrom  in (' . $_SESSION['storeids'] . ')  or storemovement.storeidto in (' . $_SESSION['storeids'] . ') ) ';
        }
    } else {
        $queryString .= ' and  ( storemovement.storeidfrom  = ' . $_SESSION['storeid'] . '  or storemovement.storeidto = ' . $_SESSION['storeid'] . ' ) ';
    }
    // get the all colums number
    $storemovementData = $myStoremovementEx->queryWithDate($startDate, $endDate, $queryString, 0, $storeQuery);
    //
    $storeTotalsArr = array();
    foreach ($storemovementData as $mystoremovementData) {
        if ($Programsettingdata->workerbetweenstores == 0) {

            if ($mystoremovementData->driverid > 0) {
                if ($mystoremovementData->deliverdate == NULL || $mystoremovementData->deliverdate == "0000-00-00 00:00:00") {
                    $mystoremovementData->deliverdate = date("Y-m-d H:i:s");
                }
                $hours = dateTimeDiff($mystoremovementData->driverdate, $mystoremovementData->deliverdate);
                if ($hours > $mystoremovementData->drivertimeout) {
                    $hours = $hours - $mystoremovementData->drivertimeout;
                } else {
                    $hours = 0;
                }
                $mystoremovementData->lateHours = $hours;
            }

            if ($mystoremovementData->driverid != NULL && $mystoremovementData->driverid > 0) {
                $userdata = $userDAO->load($mystoremovementData->driverid);
                $mystoremovementData->driverName = $userdata->employeename;
            } else {
                //$mystoremovementData->driverid = "لا يوجد";
            }

            if ($mystoremovementData->delivererid != NULL && $mystoremovementData->delivererid > 0) {
                $userdata = $userDAO->load($mystoremovementData->delivererid);
                $mystoremovementData->deliverername = $userdata->employeename;
            } else {
                $mystoremovementData->deliverername = "لا يوجد";
            }
        }
        if ($mystoremovementData->recieveUserid != NULL && $mystoremovementData->recieveUserid > 0) {
            $userdata = $userDAO->load($mystoremovementData->recieveUserid);
            $mystoremovementData->recieveUserName = $userdata->employeename;
        }

        $currentoperationnum = $mystoremovementData->operationnum;
        $deleteoperationnum = $mystoremovementData->deloperationnum;

        $deloperationnum = $mystoremovementData->deloperationnum;

        if ($currentoperationnum > 0) { // معناه ان الوصل ده تعديل لوصل قديم
            if ($deloperationnum != 0 && $mystoremovementData->conditions <> 1) {


                $mystoremovementData->userid = -1;
            }


            //
            if ($mystoremovementData->currentoperationnum <> '-1') {

                if (count($myStoremovementEx->loadBydeloperationnum($currentoperationnum)) > 0) {
                    // عشان اخفى الصف اللى اتعمل عليه تعديل قبل كدا
                    //print_r("<br>2222222222222222222222222<br>");
                    $mystoremovementData->userid = -2;
                }
            }
        }

        //storeTotals
        //1- frommmmmmmmmm
        ##check if store is here
        if (isset($storeTotalsArr[$mystoremovementData->storeidfrom])) {
            ##store exists
            $storeTotalsObj = $storeTotalsArr[$mystoremovementData->storeidfrom];
            $storeTotalsObj->totalQuantityFrom += $mystoremovementData->transferproductamount;
            $storeTotalsArr[$mystoremovementData->storeidfrom] = $storeTotalsObj;
        } else {
            ##store new
            $storeTotalsObj = new storeTotals();
            $storeTotalsObj->storeName = $mystoremovementData->storefromName;
            $storeTotalsObj->totalQuantityFrom += $mystoremovementData->transferproductamount;
            $storeTotalsArr[$mystoremovementData->storeidfrom] = $storeTotalsObj;
        }
        //2- toooooooooooooo
        ##check if store is here
        if (isset($storeTotalsArr[$mystoremovementData->storeidto])) {
            ##store exists
            $storeTotalsObj = $storeTotalsArr[$mystoremovementData->storeidto];
            $storeTotalsObj->totalQuantityTo += $mystoremovementData->transferproductamount;
            $storeTotalsArr[$mystoremovementData->storeidto] = $storeTotalsObj;
        } else {
            ##store new
            $storeTotalsObj = new storeTotals();
            $storeTotalsObj->storeName = $mystoremovementData->storetoName;
            $storeTotalsObj->totalQuantityTo += $mystoremovementData->transferproductamount;
            $storeTotalsArr[$mystoremovementData->storeidto] = $storeTotalsObj;
        }
    }


    // assign your db results to the template
    $smarty->assign('storemovementData', $storemovementData);
    $smarty->assign('storeTotalsArr', $storeTotalsArr);
}

function showByDate2($startDate, $endDate, $storeId) {
    //to use the variable out side the funcion
    global $myStoremovementEx;
    global $smarty;
    global $Programsettingdata;
    global $userDAO;
    $queryString = "";
    if ($Programsettingdata->workerbetweenstores == 0) {
        //getall
        //$queryString = " and driverid > 0";
    } elseif ($Programsettingdata->workerbetweenstores == 1) {
        $queryString .= " and (driverid is null or driverid=0) ";
    }
    $storeQuery = '';
    if ($storeId != '-1' && $storeId != '') {
        $queryString .= ' and  ( storemovement.storeidfrom  = ' . $storeId . '  or storemovement.storeidto = ' . $storeId . ' )';
    } else if ($_SESSION['searchinonestore'] == 0) {
        if ($_SESSION['storeids'] != 0) {
            $queryString .= ' and  ( storemovement.storeidfrom  in (' . $_SESSION['storeids'] . ')  or storemovement.storeidto in (' . $_SESSION['storeids'] . ') ) ';
        }
    } else {
        $queryString .= ' and  ( storemovement.storeidfrom  = ' . $_SESSION['storeid'] . '  or storemovement.storeidto = ' . $_SESSION['storeid'] . ' )';
    }

    $queryString .= ' and storemovement.conditions != 2';

    // get the all colums number
    $storemovementData = $myStoremovementEx->queryWithDate2($startDate, $endDate, $queryString, 0, $storeQuery);

    foreach ($storemovementData as $mystoremovementData) {
        $mystoremovementData->driverdate = R::getCell('select driverdate from storemovement where operationnum = ' . $mystoremovementData->operationnum);
        if ($Programsettingdata->workerbetweenstores == 0) {

            if ($mystoremovementData->driverid > 0) {
                if ($mystoremovementData->deliverdate == NULL || $mystoremovementData->deliverdate == "0000-00-00 00:00:00") {
                    $mystoremovementData->deliverdate = date("Y-m-d H:i:s");
                }
                $hours = dateTimeDiff($mystoremovementData->driverdate, $mystoremovementData->deliverdate);
                if ($hours > $mystoremovementData->drivertimeout) {
                    $hours = $hours - $mystoremovementData->drivertimeout;
                } else {
                    $hours = 0;
                }
                $mystoremovementData->lateHours = $hours;
            }

            if ($mystoremovementData->driverid != NULL && $mystoremovementData->driverid > 0) {
                $userdata = $userDAO->load($mystoremovementData->driverid);
                $mystoremovementData->driverName = $userdata->employeename;
            } else {
                //$mystoremovementData->driverid = "لا يوجد";
            }

            if ($mystoremovementData->delivererid != NULL && $mystoremovementData->delivererid > 0) {
                $userdata = $userDAO->load($mystoremovementData->delivererid);
                $mystoremovementData->deliverername = $userdata->employeename;
            } else {
                $mystoremovementData->deliverername = "لا يوجد";
            }
        }
        if ($mystoremovementData->recieveUserid != NULL && $mystoremovementData->recieveUserid > 0) {
            $userdata = $userDAO->load($mystoremovementData->recieveUserid);
            $mystoremovementData->recieveUserName = $userdata->employeename;
        }

        $currentoperationnum = $mystoremovementData->operationnum;
        $deleteoperationnum = $mystoremovementData->deloperationnum;

        $deloperationnum = $mystoremovementData->deloperationnum;

        if ($currentoperationnum > 0) { // معناه ان الوصل ده تعديل لوصل قديم
            if ($deloperationnum != 0 && $mystoremovementData->conditions <> 1) {


                $mystoremovementData->userid = -1;
            }


            //
            if ($mystoremovementData->currentoperationnum <> '-1') {

                // if (count($myStoremovementEx->loadBydeloperationnum($currentoperationnum)) > 0) {
                $counter = R::getCol('SELECT count(transferproductid) FROM storemovement where storemovement.deloperationnum =' . $currentoperationnum);
                if ($counter > 0) {
                    // عشان اخفى الصف اللى اتعمل عليه تعديل قبل كدا
                    //print_r("<br>2222222222222222222222222<br>");
                    $mystoremovementData->userid = -2;
                }
            }
        }
    }

    //    print_r('<pre>');
    //        print_r('<pre>');
    //    print_r('<pre>');
    // assign your db results to the template
    $smarty->assign('storemovementData', $storemovementData);
}

function showByoperationnum($operationnum) {
    //to use the variable out side the funcion
    global $myStoremovementEx;
    global $smarty;
    global $Programsettingdata;
    global $userDAO;
    $queryString = "";
    if ($Programsettingdata->workerbetweenstores == 0) {
        //getall
        //$queryString = " and driverid > 0";
    } elseif ($Programsettingdata->workerbetweenstores == 1) {
        $queryString .= " and (driverid is null or driverid=0) ";
    }


    if ($_SESSION['searchinonestore'] == 0) {
        if ($_SESSION['storeids'] != 0) {
            $queryString .= ' and  ( storemovement.storeidfrom  in (' . $_SESSION['storeids'] . ')  or storemovement.storeidto in (' . $_SESSION['storeids'] . ') ) ';
        }
    } else {
        $queryString .= ' and  ( storemovement.storeidfrom  = ' . $_SESSION['storeid'] . '  or storemovement.storeidto = ' . $_SESSION['storeid'] . ' )';
    }

    // get the all colums number
    $storemovementData = $myStoremovementEx->querybyoperationnumsearch2($operationnum, 'deloperationnum', $queryString, 0);
    if (count($storemovementData) == 0) {

        $storemovementData = $myStoremovementEx->querybyoperationnumsearch2($operationnum, 'operationnum', '', 0);
    }
    //
    $storeTotalsArr = array();
    foreach ($storemovementData as $mystoremovementData) {
        if ($Programsettingdata->workerbetweenstores == 0) {
            if ($mystoremovementData->driverid > 0) {
                if ($mystoremovementData->deliverdate == NULL || $mystoremovementData->deliverdate == "0000-00-00 00:00:00") {
                    $mystoremovementData->deliverdate = date("Y-m-d H:i:s");
                }
                $hours = dateTimeDiff($mystoremovementData->driverdate, $mystoremovementData->deliverdate);
                if ($hours > $mystoremovementData->drivertimeout) {
                    $hours = $hours - $mystoremovementData->drivertimeout;
                } else {
                    $hours = 0;
                }
                $mystoremovementData->lateHours = $hours;
            }

            if ($mystoremovementData->driverid != NULL && $mystoremovementData->driverid > 0) {
                $userdata = $userDAO->load($mystoremovementData->driverid);
                $mystoremovementData->driverName = $userdata->employeename;
            } else {
                //$mystoremovementData->driverid = "لا يوجد";
            }
            if ($mystoremovementData->delivererid != NULL && $mystoremovementData->delivererid > 0) {
                $userdata = $userDAO->load($mystoremovementData->delivererid);
                $mystoremovementData->deliverername = $userdata->employeename;
            } else {
                $mystoremovementData->deliverername = "لا يوجد";
            }
        }
        if ($mystoremovementData->recieveUserid != NULL && $mystoremovementData->recieveUserid > 0) {
            $userdata = $userDAO->load($mystoremovementData->recieveUserid);
            $mystoremovementData->recieveUserName = $userdata->employeename;
        }

        $currentoperationnum = $mystoremovementData->operationnum;
        $deleteoperationnum = $mystoremovementData->deloperationnum;

        $deloperationnum = $mystoremovementData->deloperationnum;

        // معناه ان الوصل ده تعديل لوصل قديم
        if ($deloperationnum != 0 && $mystoremovementData->conditions <> 1) {
            $mystoremovementData->userid = -1;
        }


        //
        if ($mystoremovementData->currentoperationnum <> '-1') {
            // if (count($myStoremovementEx->loadBydeloperationnum($currentoperationnum)) > 0) {
            $counter = R::getCol('SELECT count(transferproductid) FROM storemovement where storemovement.deloperationnum =' . $currentoperationnum . ' group by operationnum');
            if ($counter > 0) {
                // عشان اخفى الصف اللى اتعمل عليه تعديل قبل كدا
                //print_r("<br>2222222222222222222222222<br>");
                $mystoremovementData->userid = -2;
            }
        }
        //storeTotals
        //1- frommmmmmmmmm
        ##check if store is here
        if (isset($storeTotalsArr[$mystoremovementData->storeidfrom])) {
            ##store exists
            $storeTotalsObj = $storeTotalsArr[$mystoremovementData->storeidfrom];
            $storeTotalsObj->totalQuantityFrom += $mystoremovementData->transferproductamount;
            $storeTotalsArr[$mystoremovementData->storeidfrom] = $storeTotalsObj;
        } else {
            ##store new
            $storeTotalsObj = new storeTotals();
            $storeTotalsObj->storeName = $mystoremovementData->storefromName;
            $storeTotalsObj->totalQuantityFrom += $mystoremovementData->transferproductamount;
            $storeTotalsArr[$mystoremovementData->storeidfrom] = $storeTotalsObj;
        }
        //2- toooooooooooooo
        ##check if store is here
        if (isset($storeTotalsArr[$mystoremovementData->storeidto])) {
            ##store exists
            $storeTotalsObj = $storeTotalsArr[$mystoremovementData->storeidto];
            $storeTotalsObj->totalQuantityTo += $mystoremovementData->transferproductamount;
            $storeTotalsArr[$mystoremovementData->storeidto] = $storeTotalsObj;
        } else {
            ##store new
            $storeTotalsObj = new storeTotals();
            $storeTotalsObj->storeName = $mystoremovementData->storetoName;
            $storeTotalsObj->totalQuantityTo += $mystoremovementData->transferproductamount;
            $storeTotalsArr[$mystoremovementData->storeidto] = $storeTotalsObj;
        }
    }
    // assign your db results to the template
    $smarty->assign('storemovementData', $storemovementData);
    $smarty->assign('storeTotalsArr', $storeTotalsArr);
}

function showByoperationnum2($operationnum) {
    //to use the variable out side the funcion
    global $myStoremovementEx;
    global $smarty;
    global $Programsettingdata;
    global $userDAO;
    $queryString = "";
    if ($Programsettingdata->workerbetweenstores == 0) {
        //getall
        //$queryString = " and driverid > 0";
    } elseif ($Programsettingdata->workerbetweenstores == 1) {
        $queryString .= " and (driverid is null or driverid=0) ";
    }

    $queryString2 = '';
    if ($_SESSION['searchinonestore'] == 0) {
        if ($_SESSION['storeids'] != 0) {
            $queryString2 .= ' and  ( storemovement.storeidfrom  in (' . $_SESSION['storeids'] . ')  or storemovement.storeidto in (' . $_SESSION['storeids'] . ') ) ';
        }
    } else {
        $queryString2 .= ' and  ( storemovement.storeidfrom  = ' . $_SESSION['storeid'] . '  or storemovement.storeidto = ' . $_SESSION['storeid'] . ' )';
    }



    // get the all colums number
    $storemovementData = $myStoremovementEx->querybyoperationnumsearch3($operationnum, 'deloperationnum', $queryString . $queryString2, 0);
    if (count($storemovementData) == 0) {

        $storemovementData = $myStoremovementEx->querybyoperationnumsearch3($operationnum, 'operationnum', $queryString2, 0);
    }

    foreach ($storemovementData as $mystoremovementData) {
        $mystoremovementData->driverdate = R::getCell('select driverdate from storemovement where operationnum = ' . $mystoremovementData->operationnum);
        if ($Programsettingdata->workerbetweenstores == 0) {
            if ($mystoremovementData->driverid > 0) {
                if ($mystoremovementData->deliverdate == NULL || $mystoremovementData->deliverdate == "0000-00-00 00:00:00") {
                    $mystoremovementData->deliverdate = date("Y-m-d H:i:s");
                }
                $hours = dateTimeDiff($mystoremovementData->driverdate, $mystoremovementData->deliverdate);
                if ($hours > $mystoremovementData->drivertimeout) {
                    $hours = $hours - $mystoremovementData->drivertimeout;
                } else {
                    $hours = 0;
                }
                $mystoremovementData->lateHours = $hours;
            }

            if ($mystoremovementData->driverid != NULL && $mystoremovementData->driverid > 0) {
                $userdata = $userDAO->load($mystoremovementData->driverid);
                $mystoremovementData->driverName = $userdata->employeename;
            } else {
                //$mystoremovementData->driverid = "لا يوجد";
            }
            if ($mystoremovementData->delivererid != NULL && $mystoremovementData->delivererid > 0) {
                $userdata = $userDAO->load($mystoremovementData->delivererid);
                $mystoremovementData->deliverername = $userdata->employeename;
            } else {
                $mystoremovementData->deliverername = "لا يوجد";
            }
        }
        if ($mystoremovementData->recieveUserid != NULL && $mystoremovementData->recieveUserid > 0) {
            $userdata = $userDAO->load($mystoremovementData->recieveUserid);
            $mystoremovementData->recieveUserName = $userdata->employeename;
        }

        $currentoperationnum = $mystoremovementData->operationnum;
        $deleteoperationnum = $mystoremovementData->deloperationnum;

        $deloperationnum = $mystoremovementData->deloperationnum;

        // معناه ان الوصل ده تعديل لوصل قديم
        if ($deloperationnum != 0 && $mystoremovementData->conditions <> 1) {
            $mystoremovementData->userid = -1;
        }


        //
        if ($mystoremovementData->currentoperationnum <> '-1') {
            // if (count($myStoremovementEx->loadBydeloperationnum($currentoperationnum)) > 0) {
            $counter = R::getCol('SELECT count(transferproductid) FROM storemovement where storemovement.deloperationnum =' . $currentoperationnum);
            if ($counter > 0) {
                // عشان اخفى الصف اللى اتعمل عليه تعديل قبل كدا
                //print_r("<br>2222222222222222222222222<br>");
                $mystoremovementData->userid = -2;
            }
        }
    }
    // assign your db results to the template
    $smarty->assign('storemovementData', $storemovementData);
}

function tempdelete($transferproductId) {
    //to use the variable out side the funcion
    global $myStoremovement;
    global $myStoremovementRecord;
    global $myStoremovementEx;
    global $sizeColorStoreDetailEX;

    if (isset($transferproductId)) {
        //Transaction
        $mytransactions = new Transaction();

        $singleStoremovement = $myStoremovementEx->loadStoremovementById($transferproductId);

        try {
            if ($singleStoremovement->conditions == 0) {
                //get transferproductamount by transfermoneyid
                $storemovementData = $myStoremovementRecord->load($transferproductId);
                $transferproductAmount = $storemovementData->transferproductamount;
                $storeidfrom = $storemovementData->storeidfrom;
                $storeidto = $storemovementData->storeidto;
                $productId = $storemovementData->productid;
                $sizeId = $storemovementData->sizeid;
                $colorId = $storemovementData->colorid;
                $transferproductId = $storemovementData->transferproductid;


                //get storefrom productquantity before change
                $sizeColorStoreDetailIdTo = 0;
                if ($sizeId > 0 && $colorId > 0) { //size and color product add it also to sizeColorStoreDetail table
                    //try to copy from existing data in store 1
                    $sizeColorStoreDetailIdTo = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidto, $sizeId, $colorId);
                }
                $storedetailToData = getStoredetailData($storeidto, $productId, $sizeColorStoreDetailIdTo, $sizeId, $colorId);

                $allStoredetailToData = $storedetailToData[0];
                $storedetailToId = $storedetailToData[1];
                $productquantityToBefore = $storedetailToData[2];


                //check if productquantityFromBefore greater than 0 or not
                $productsBeforeValid = 1;
                if ($productquantityToBefore > 0 && count($allStoredetailToData) > 0) {
                    $productsAfterValid = $productquantityToBefore - $transferproductAmount;

                    if ($productsAfterValid >= 0) {
                        $productsBeforeValid = 1;

                        $note = "success";
                    } else {
                        $note = "لا يوجد بالمخزن" . $singleStoremovement->storetoName . " الكمية الكافية لحذف تحويل  " . $singleStoremovement->transferproductamount . "من" . $singleStoremovement->storefromName . "إلى" . $singleStoremovement->storetoName . "";

                        $productsBeforeValid = 0;
                        //return array($note,$productsBeforeValid);
                    }
                } else {
                    $note = "لا يوجد بالمخزن" . $singleStoremovement->storetoName . " الكمية الكافية لحذف تحويل  " . $singleStoremovement->transferproductamount . "من" . $singleStoremovement->storefromName . "إلى" . $singleStoremovement->storetoName . "";

                    $productsBeforeValid = 0;
                    //return array($note,$productsBeforeValid);
                }




                //update data in storemovement tbl
                $myStoremovement->conditions = 1;
                $myStoremovement->transferproductdate = date("Y-m-d");
                ;
                $myStoremovement->userid = $_SESSION["userid"];
                $myStoremovement->transferproductid = $transferproductId;

                $myStoremovementEx->updateConditions($myStoremovement);


                //////////////**Store To**///////////////////////////
                //get storefrom productquantity before change
                $sizeColorStoreDetailIdTo = 0;
                if ($sizeId > 0 && $colorId > 0) { //size and color product add it also to sizeColorStoreDetail table
                    //try to copy from existing data in store 1
                    $sizeColorStoreDetailIdTo = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidto, $sizeId, $colorId);
                }
                $storedetailToData = getStoredetailData($storeidto, $productId, $sizeColorStoreDetailIdTo, $sizeId, $colorId);

                $allStoredetailToData = $storedetailToData[0];
                $storedetailToId = $storedetailToData[1];
                $productquantityToBefore = $storedetailToData[2];

                //update productquantity in storedetail
                $productquantityToAfter = decreaseProductQuantity($storedetailToId, $productquantityToBefore, $transferproductAmount, $sizeColorStoreDetailIdTo, $sizeId, $colorId, $storemovementData);


                //insert in storereport
                insertStorereport($productId, $storeidto, $transferproductAmount, $productquantityToBefore, $productquantityToAfter, 1, $transferproductId, "حذف تحويل منتجات إلى المخزن", "storemovementController.php", $sizeId, $colorId);



                //////////////**Store from**///////////////////////////
                //get storeto productquantity before change
                $sizeColorStoreDetailIdFrom = 0;
                if ($sizeId > 0 && $colorId > 0) {
                    $sizeColorStoreDetailIdFrom = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidfrom, $sizeId, $colorId);
                }
                $storedetailFromData = getStoredetailData($storeidfrom, $productId, $sizeColorStoreDetailIdFrom, $sizeId, $colorId);

                $allStoredetailFromData = $storedetailFromData[0];
                $storedetailFromId = $storedetailFromData[1];
                $productquantityFromBefore = $storedetailFromData[2];



                //update productquantity in storedetail
                $productquantityFromAfter = increaseProductQuantity($storedetailFromId, $productquantityFromBefore, $transferproductAmount, $sizeColorStoreDetailIdFrom, $sizeId, $colorId, $storemovementData);


                //insert in storereport
                insertStorereport($productId, $storeidfrom, $transferproductAmount, $productquantityFromBefore, $productquantityFromAfter, 0, $transferproductId, "حذف تحويل منتجات من المخزن", "storemovementController.php", $sizeId, $colorId);
            }
            $mytransactions->commit();
        } catch (Exception $e) {
            $mytransactions->rollback();
            $note = "حدث خطأ أثناء حذف التحويل";
            $productsBeforeValid = 2;
        }
        return array($note, $productsBeforeValid);
    }
}

function tempdelete2($operationnum) {
    //to use the variable out side the funcion
    global $myStoremovement;
    global $myStoremovementRecord;
    global $myStoremovementEx;
    global $sizeColorStoreDetailEX;

    if (isset($operationnum)) {
        //Transaction
        $mytransactions = new Transaction();
        try {

            $Storemovement_data = $myStoremovementEx->operationData2($operationnum);

            $dailyentryIdArr = array();
            foreach ($Storemovement_data as $oper_data) {

                $transferproductId = $oper_data->transferproductid;
                $singleStoremovement = $myStoremovementEx->loadStoremovementById($transferproductId);

                try {
                    //notdeleted , direct or withbetween store but not recieved
                    if ($singleStoremovement->conditions == 0 && ($singleStoremovement->recieveType == 0 || ($singleStoremovement->recieveType == 1 && $singleStoremovement->recieveUserid == 0))) {
                        //get transferproductamount by transfermoneyid
                        $storemovementData = $myStoremovementRecord->load($transferproductId);
                        $transferproductAmount = $storemovementData->transferproductamount;
                        $storeidfrom = $storemovementData->storeidfrom;
                        $storeidto = $storemovementData->storeidto;
                        $productId = $storemovementData->productid;
                        $transferproductId = $storemovementData->transferproductid;
                        $sizeId = $storemovementData->sizeid;
                        $colorId = $storemovementData->colorid;
                        $dailyentryIdArr[] = $storemovementData->dailyentryid;

                        $sizeColorStoreDetailIdTo = 0;
                        if ($sizeId > 0 && $colorId > 0) {
                            $sizeColorStoreDetailIdTo = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidto, $sizeId, $colorId);
                        }
                        //get storefrom productquantity before change
                        $storedetailToData = getStoredetailData($storeidto, $productId, $sizeColorStoreDetailIdTo, $sizeId, $colorId);

                        $allStoredetailToData = $storedetailToData[0];
                        $storedetailToId = $storedetailToData[1];
                        $productquantityToBefore = $storedetailToData[2];


                        //check if productquantityFromBefore greater than 0 or not
                        $productsBeforeValid = 1;
                        if ($productquantityToBefore > 0 && count($allStoredetailToData) > 0) {
                            $productsAfterValid = $productquantityToBefore - $transferproductAmount;

                            if ($productsAfterValid >= 0) {
                                $productsBeforeValid = 1;

                                $note = "success";
                            } else {
                                $note = "لا يوجد بالمخزن" . $singleStoremovement->storetoName . " الكمية الكافية لحذف تحويل  " . $singleStoremovement->transferproductamount . "من" . $singleStoremovement->storefromName . "إلى" . $singleStoremovement->storetoName . "";

                                $productsBeforeValid = 0;
                                //return array($note,$productsBeforeValid);
                            }
                        } else {
                            $note = "لا يوجد بالمخزن" . $singleStoremovement->storetoName . " الكمية الكافية لحذف تحويل  " . $singleStoremovement->transferproductamount . "من" . $singleStoremovement->storefromName . "إلى" . $singleStoremovement->storetoName . "";

                            $productsBeforeValid = 0;
                            //return array($note,$productsBeforeValid);
                        }



                        //update data in storemovement tbl
                        if (isset($_POST['edit']) && $_POST['edit'] == 1)
                            $myStoremovement->conditions = 2;
                        else
                            $myStoremovement->conditions = 1;
                        $myStoremovement->userid = $_SESSION["userid"];
                        $myStoremovement->transferproductdate = date("Y-m-d");
                        ;
                        $myStoremovement->transferproductid = $transferproductId;

                        $myStoremovementEx->updateConditions($myStoremovement);


                        //////////////**Store To**///////////////////////////
                        //get storefrom productquantity before change
                        $storedetailToData = getStoredetailData($storeidto, $productId, $sizeColorStoreDetailIdTo, $sizeId, $colorId);

                        $allStoredetailToData = $storedetailToData[0];
                        $storedetailToId = $storedetailToData[1];
                        $productquantityToBefore = $storedetailToData[2];

                        //update productquantity in storedetail
                        $productquantityToAfter = decreaseProductQuantity($storedetailToId, $productquantityToBefore, $transferproductAmount, $sizeColorStoreDetailIdTo, $sizeId, $colorId, $storemovementData);


                        //insert in storereport
                        insertStorereport($productId, $storeidto, $transferproductAmount, $productquantityToBefore, $productquantityToAfter, 1, $transferproductId, "حذف تحويل منتجات إلى المخزن", "storemovementController.php", $sizeId, $colorId);



                        //////////////**Store from**///////////////////////////
                        //get storeto productquantity before change
                        $sizeColorStoreDetailIdFrom = 0;
                        if ($sizeId > 0 && $colorId > 0) {
                            $sizeColorStoreDetailIdFrom = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidfrom, $sizeId, $colorId);
                        }
                        $storedetailFromData = getStoredetailData($storeidfrom, $productId, $sizeColorStoreDetailIdFrom, $sizeId, $colorId);

                        $allStoredetailFromData = $storedetailFromData[0];
                        $storedetailFromId = $storedetailFromData[1];
                        $productquantityFromBefore = $storedetailFromData[2];



                        //update productquantity in storedetail
                        $productquantityFromAfter = increaseProductQuantity($storedetailFromId, $productquantityFromBefore, $transferproductAmount, $sizeColorStoreDetailIdFrom, $sizeId, $colorId, $storemovementData);


                        //insert in storereport
                        insertStorereport($productId, $storeidfrom, $transferproductAmount, $productquantityFromBefore, $productquantityFromAfter, 0, $transferproductId, "حذف تحويل منتجات من المخزن", "storemovementController.php", $sizeId, $colorId);
                    }
                } catch (Exception $e) {
                    $note = "حدث خطأ أثناء حذف التحويل";
                    $productsBeforeValid = 2;
                }
            }
            //قيود اليومية
            $dailyentryIdArr = !empty($dailyentryIdArr) ? array_unique($dailyentryIdArr) : [0];
            foreach ($dailyentryIdArr as $entryid) {
                reverseEntryWithItsID($entryid, 1);
            }
            $mytransactions->commit();
        } catch (Exception $ex) {
            $mytransactions->rollback();
        }
        return array($note, $productsBeforeValid);
    }
}

function returndelete($transferproductId) {
    global $myStoremovement;
    global $myStoremovementRecord;
    global $myStoremovementEx;
    global $sizeColorStoreDetailEX;

    if (isset($transferproductId)) {

        $singleStoremovement = $myStoremovementEx->loadStoremovementById($transferproductId);
        //Transaction
        $mytransactions = new Transaction();
        try {
            if ($singleStoremovement->conditions == 1) {
                //get transferproductamount by transfermoneyid
                $storemovementData = $myStoremovementRecord->load($transferproductId);
                $transferproductAmount = $storemovementData->transferproductamount;
                $storeidfrom = $storemovementData->storeidfrom;
                $storeidto = $storemovementData->storeidto;
                $productId = $storemovementData->productid;
                $sizeId = $storemovementData->sizeid;
                $colorId = $storemovementData->colorid;
                $transferproductId = $storemovementData->transferproductid;


                //get storefrom productquantity before change
                $sizeColorStoreDetailIdFrom = 0;
                if ($sizeId > 0 && $colorId > 0) {
                    $sizeColorStoreDetailIdFrom = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidfrom, $sizeId, $colorId);
                }
                $storedetailFromData = getStoredetailData($storeidfrom, $productId, $sizeColorStoreDetailIdFrom, $sizeId, $colorId);

                $allStoredetailFromData = $storedetailFromData[0];
                $storedetailFromId = $storedetailFromData[1];
                $productquantityFromBefore = $storedetailFromData[2];

                //check if productquantityFromBefore greater than 0 or not
                $productsBeforeValid = 1;
                if ($productquantityFromBefore > 0 && count($allStoredetailFromData) > 0) {
                    $productsAfterValid = $productquantityFromBefore - $transferproductAmount;

                    if ($productsAfterValid >= 0) {
                        $productsBeforeValid = 1;
                        $note = "success";
                    } else {
                        $note = "لا يوجد بالمخزن" . $singleStoremovement->storefromName . " الكمية الكافية لاعادة حذف تحويل  " . $singleStoremovement->transferproductamount . "من" . $singleStoremovement->storefromName . "إلى" . $singleStoremovement->storetoName . "";

                        $productsBeforeValid = 0;
                        //return array($note,$productsBeforeValid);
                    }
                } else {
                    $note = "لا يوجد بالمخزن" . $singleStoremovement->storefromName . " الكمية الكافية لاعادة حذف تحويل  " . $singleStoremovement->transferproductamount . "من" . $singleStoremovement->storefromName . "إلى" . $singleStoremovement->storetoName . "";

                    $productsBeforeValid = 0;
                    //return array($note,$productsBeforeValid);
                }



                //update data in storemovement tbl
                $myStoremovement->conditions = 0;
                $myStoremovement->transferproductdate = date("Y-m-d");
                $myStoremovement->userid = $_SESSION["userid"];
                $myStoremovement->transferproductid = $transferproductId;

                $myStoremovementEx->updateConditions($myStoremovement);


                //////////////**Store From**///////////////////////////
                //get storefrom productquantity before change
                $sizeColorStoreDetailIdFrom = 0;
                if ($sizeId > 0 && $colorId > 0) {
                    $sizeColorStoreDetailIdFrom = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidfrom, $sizeId, $colorId);
                }
                $storedetailFromData = getStoredetailData($storeidfrom, $productId, $sizeColorStoreDetailIdFrom, $sizeId, $colorId);

                $allStoredetailFromData = $storedetailFromData[0];
                $storedetailFromId = $storedetailFromData[1];
                $productquantityFromBefore = $storedetailFromData[2];

                //update productquantity in storedetail
                $productquantityFromAfter = decreaseProductQuantity($storedetailFromId, $productquantityFromBefore, $transferproductAmount, $sizeColorStoreDetailIdFrom, $sizeId, $colorId, $storemovementData);


                //insert in storereport
                insertStorereport($productId, $storeidfrom, $transferproductAmount, $productquantityFromBefore, $productquantityFromAfter, 1, $transferproductId, "تحويل منتجات من المخزن", "storemovementController.php", $sizeId, $colorId);



                //////////////**Store To**///////////////////////////
                //get storeto productquantity before change
                $sizeColorStoreDetailIdTo = 0;
                if ($sizeId > 0 && $colorId > 0) { //size and color product add it also to sizeColorStoreDetail table
                    //try to copy from existing data in store 1
                    $sizeColorStoreDetailIdTo = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidto, $sizeId, $colorId);
                }
                $storedetailToData = getStoredetailData($storeidto, $productId, $sizeColorStoreDetailIdTo, $sizeId, $colorId);

                $allStoredetailToData = $storedetailToData[0];
                $storedetailToId = $storedetailToData[1];
                $productquantityToBefore = $storedetailToData[2];



                //update productquantity in storedetail
                $productquantityToAfter = increaseProductQuantity($storedetailToId, $productquantityToBefore, $transferproductAmount, $sizeColorStoreDetailIdTo, $sizeId, $colorId, $storemovementData);

                //insert in storereport
                insertStorereport($productId, $storeidto, $transferproductAmount, $productquantityToBefore, $productquantityToAfter, 0, $transferproductId, "تحويل منتجات إلى المخزن", "storemovementController.php", $sizeId, $colorId);
            }
            $mytransactions->commit();
        } catch (Exception $e) {
            $mytransactions->rollback();
            $note = "حدث خطأ أثناء اعادة حذف التحويل";
            $productsBeforeValid = 2;
        }

        return array($note, $productsBeforeValid);
    }
}

function returndelete2($operationnum) {
    global $myStoremovement;
    global $myStoremovementRecord;
    global $myStoremovementEx;
    global $sizeColorStoreDetailEX;

    ##for daily entry
    global $mainData;
    global $detailArr;

    if (isset($operationnum)) {
        //Transaction
        $mytransactions = new Transaction();
        try {
            $Storemovement_data = $myStoremovementEx->operationData2($operationnum);


            foreach ($Storemovement_data as $oper_data) {
                $transferproductId = $oper_data->transferproductid;
                $singleStoremovement = $myStoremovementEx->loadStoremovementById($transferproductId);

                try {
                    if ($singleStoremovement->conditions == 1) {
                        //get transferproductamount by transfermoneyid
                        $storemovementData = $myStoremovementRecord->load($transferproductId);
                        $transferproductAmount = $storemovementData->transferproductamount;
                        $storeidfrom = $storemovementData->storeidfrom;
                        $storeidto = $storemovementData->storeidto;
                        $productId = $storemovementData->productid;
                        $transferproductId = $storemovementData->transferproductid;
                        $sizeId = $storemovementData->sizeid;
                        $colorId = $storemovementData->colorid;

                        $mainData = $storemovementData;

                        $sizeColorStoreDetailIdFrom = 0;
                        if ($sizeId > 0 && $colorId > 0) {
                            $sizeColorStoreDetailIdFrom = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidfrom, $sizeId, $colorId);
                        }

                        //get storefrom productquantity before change
                        $storedetailFromData = getStoredetailData($storeidfrom, $productId, $sizeColorStoreDetailIdFrom, $sizeId, $colorId);

                        $allStoredetailFromData = $storedetailFromData[0];
                        $storedetailFromId = $storedetailFromData[1];
                        $productquantityFromBefore = $storedetailFromData[2];


                        //check if productquantityFromBefore greater than 0 or not
                        $productsBeforeValid = 1;
                        if ($productquantityFromBefore > 0 && count($allStoredetailFromData) > 0) {
                            $productsAfterValid = $productquantityFromBefore - $transferproductAmount;

                            if ($productsAfterValid >= 0) {
                                $productsBeforeValid = 1;
                                $note = "success";
                            } else {
                                $note = "لا يوجد بالمخزن" . $singleStoremovement->storefromName . " الكمية الكافية لاعادة حذف تحويل  " . $singleStoremovement->transferproductamount . "من" . $singleStoremovement->storefromName . "إلى" . $singleStoremovement->storetoName . "";

                                $productsBeforeValid = 0;
                                //return array($note,$productsBeforeValid);
                            }
                        } else {
                            $note = "لا يوجد بالمخزن" . $singleStoremovement->storefromName . " الكمية الكافية لاعادة حذف تحويل  " . $singleStoremovement->transferproductamount . "من" . $singleStoremovement->storefromName . "إلى" . $singleStoremovement->storetoName . "";

                            $productsBeforeValid = 0;
                            //return array($note,$productsBeforeValid);
                        }



                        //update data in storemovement tbl
                        $myStoremovement->conditions = 0;
                        $myStoremovement->transferproductdate = date("Y-m-d");
                        $myStoremovement->userid = $_SESSION["userid"];
                        $myStoremovement->transferproductid = $transferproductId;

                        $myStoremovementEx->updateConditions($myStoremovement);


                        //////////////**Store From**///////////////////////////
                        //get storefrom productquantity before change
                        $storedetailFromData = getStoredetailData($storeidfrom, $productId, $sizeColorStoreDetailIdFrom, $sizeId, $colorId);

                        $allStoredetailFromData = $storedetailFromData[0];
                        $storedetailFromId = $storedetailFromData[1];
                        $productquantityFromBefore = $storedetailFromData[2];

                        //update productquantity in storedetail
                        $productquantityFromAfter = decreaseProductQuantity($storedetailFromId, $productquantityFromBefore, $transferproductAmount, $sizeColorStoreDetailIdFrom, $sizeId, $colorId, $singleStoremovement);


                        //insert in storereport
                        insertStorereport($productId, $storeidfrom, $transferproductAmount, $productquantityFromBefore, $productquantityFromAfter, 1, $transferproductId, "تحويل منتجات من المخزن", "storemovementController.php", $sizeId, $colorId);



                        //////////////**Store To**///////////////////////////
                        //get storeto productquantity before change
                        $sizeColorStoreDetailIdTo = 0;
                        if ($sizeId > 0 && $colorId > 0) { //size and color product add it also to sizeColorStoreDetail table
                            //try to copy from existing data in store 1
                            $sizeColorStoreDetailIdTo = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeidto, $sizeId, $colorId);
                        }
                        $storedetailToData = getStoredetailData($storeidto, $productId, $sizeColorStoreDetailIdTo, $sizeId, $colorId);

                        $allStoredetailToData = $storedetailToData[0];
                        $storedetailToId = $storedetailToData[1];
                        $productquantityToBefore = $storedetailToData[2];



                        //update productquantity in storedetail
                        $productquantityToAfter = increaseProductQuantity($storedetailToId, $productquantityToBefore, $transferproductAmount, $sizeColorStoreDetailIdTo, $sizeId, $colorId, $singleStoremovement);

                        //insert in storereport
                        insertStorereport($productId, $storeidto, $transferproductAmount, $productquantityToBefore, $productquantityToAfter, 0, $transferproductId, "تحويل منتجات إلى المخزن", "storemovementController.php", $sizeId, $colorId);
                        //
                        $obj = new stdClass();
                        $obj->productid = $productId;
                        $obj->amount = $transferproductAmount;
                        array_push($detailArr, $obj);
                    }
                } catch (Exception $e) {
                    $note = "حدث خطأ أثناء اعادة حذف التحويل";
                    $productsBeforeValid = 2;
                }
            }
            $mytransactions->commit();
        } catch (Exception $ex) {
            $mytransactions->rollback();
        }

        return array($note, $productsBeforeValid);
    }
}

//edit from transfer tbl
function editprint() {
    global $myStoremovementEx;

    $transferproductId = $_GET['id'];

    $loadData = $myStoremovementEx->loadStoremovementById($transferproductId);
    return $loadData;
}

//edit from transfer tbl
function edit() {
    //to use the variable out side the funcion
    global $myStoremovementEx;

    $transferproductId = $_GET['id'];

    $loadData = $myStoremovementEx->loadStoremovementById($transferproductId);
    return $loadData;
}

//edit from transfer tbl
function editorder() {
    //to use the variable out side the funcion
    global $myStoremovementEx;
    global $sizeColorStoreDetailEX;
    global $userDAO;

    $orderno = $_GET['on'];

    $loadData = $myStoremovementEx->queryStoremovementByoperationnumCatname($orderno, 0);
    foreach ($loadData as $mystoremovementData) {
        if ($mystoremovementData->driverid != NULL && $mystoremovementData->driverid > 0) {
            $userdata = $userDAO->load($mystoremovementData->driverid);
            $mystoremovementData->driverName = $userdata->employeename;
        } else {
            $mystoremovementData->driverName = "لا يوجد";
        }

        if ($mystoremovementData->delivererid != NULL && $mystoremovementData->delivererid > 0) {
            $userdata = $userDAO->load($mystoremovementData->delivererid);
            $mystoremovementData->deliverername = $userdata->employeename;
        } else {
            $mystoremovementData->deliverername = "لا يوجد";
        }

        if ($mystoremovementData->recieveUserid != NULL && $mystoremovementData->recieveUserid > 0) {
            $userdata = $userDAO->load($mystoremovementData->recieveUserid);
            $mystoremovementData->recieveUserName = $userdata->employeename;
        }

        if ($mystoremovementData->sizeid > 0 && $mystoremovementData->colorid > 0) {
            $sizeColorStoreDetailData = $sizeColorStoreDetailEX->getParcodeByProductSizeAndColorEX($mystoremovementData->productid, $mystoremovementData->sizeid, $mystoremovementData->colorid);
            $mystoremovementData->parcode = $sizeColorStoreDetailData->parcode;
        }
    }
    return $loadData;
}

function executeOperation() {
    //to use the variable out side the funcion
    global $myStoremovementEx;
    global $smarty;

    $outputString = "";

    $operationType = $_POST['operation'];
    $smarty->assign("operationType", $operationType);

    $choosedItemArr = $_POST['choosedItem'];

    if (count($choosedItemArr) > 0) {
        foreach ($choosedItemArr as $transferproductId) {

            if ($operationType == '1') {
                //tempdelete
                $note = tempdelete($transferproductId);
                if ($note[0] != "success") {
                    $outputString .= $note[0] . "<br/>";
                } else {
                    $outputString .= "تمت العملية بنجاح <br/>";
                }
            } elseif ($operationType == "2") {
                //returndelete
                $note = returndelete($transferproductId);
                if ($note[0] != "success") {
                    $outputString .= $note[0] . "<br/>";
                } else {
                    $outputString .= "تمت العملية بنجاح <br/>";
                }
            }
        }
        $smarty->assign("outputString", $outputString);
    }
}

// get productquantity from storedetail tbl
function getStoredetailData($storeid, $productid, $sizeColorStoreDetailId, $sizeId, $colorId) {
    global $myStoredetailEx;
    global $sizeColorStoreDetailDAO;

    if ((isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) || ($sizeId > 0 && $colorId > 0)) { //sizecolor product
        if ((!isset($sizeColorStoreDetailId) || empty($sizeColorStoreDetailId)) && ($sizeId > 0 && $colorId > 0)) {
            $storedetailId = 0;
            $productquantityBefore = 0;
        } else {
            $storedetailData = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);
            $storedetailId = $storedetailData->id;
            $productquantityBefore = $storedetailData->quantity;
        }
    } else {
        //select data from storerawmaterialdetails by storeid and rawmaterialid
        $storedetailData = $myStoredetailEx->queryWithStoreAndProduct($productid, $storeid);

        $storedetailId = $storedetailData->storedetailid;
        $productquantityBefore = $storedetailData->productquantity;
    }

    return array($storedetailData, $storedetailId, $productquantityBefore);
}

// get productquantity from storedetail tbl
function getStoredetailData2NoConditions($storeid, $productid, $sizeColorStoreDetailId, $sizeId, $colorId) {
    global $myStoredetailEx;
    global $sizeColorStoreDetailDAO;

    if ((isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) || ($sizeId > 0 && $colorId > 0)) { //sizecolor product
        if ((!isset($sizeColorStoreDetailId) || empty($sizeColorStoreDetailId)) && ($sizeId > 0 && $colorId > 0)) {
            $storedetailId = 0;
            $productquantityBefore = 0;
        } else {
            $storedetailData = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);
            $storedetailId = $storedetailData->id;
            $productquantityBefore = $storedetailData->quantity;
        }
    } else {
        //select data from storerawmaterialdetails by storeid and rawmaterialid
        $storedetailData = $myStoredetailEx->queryWithStoreAndProduct2NoConditions($productid, $storeid);

        $storedetailId = $storedetailData->storedetailid;
        $productquantityBefore = $storedetailData->productquantity;
    }
    return array($storedetailData, $storedetailId, $productquantityBefore);
}

//update and increase productquantity in storedetail tbl
function increaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount, $sizeColorStoreDetailId, $sizeId, $colorId, $movementRow) {
    global $myStoredetail;
    global $myStoredetailRecord;
    global $myStoredetailEx;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    //increase productquantity
    $productquantityAfter = $productquantityBefore + $productChangeAmount;
    $myStoredetail = $myStoredetailRecord->load($storedetailId);
    $storeId = $myStoredetail->storeid;

    if (empty($sizeColorStoreDetailId) && $sizeId > 0 && $colorId > 0) {
        //try to copy from existing data in store 1
        $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($myStoredetail->productid, 1, $sizeId, $colorId);
        $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

        $sizeColorStoreDetail->storeid = $myStoredetail->storeid;
        $sizeColorStoreDetail->quantity = 0;
        $sizeColorStoreDetail->userid = $_SESSION['userid'];
        $sizeColorStoreDetail->sysdate = date("Y-m-d H:i:s");

        $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
    }


    if (isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) {
        $sizecolorstoredetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);

        $storeId = $sizecolorstoredetail->storeid;

        $sizecolorstoredetail->userid = $_SESSION['userid'];
        $sizecolorstoredetail->sysdate = date("Y-m-d H:i:s");
        $sizecolorstoredetail->quantity = $productquantityAfter;
        $sizeColorStoreDetailDAO->update($sizecolorstoredetail);
        onlineTempStoreDetailFunc($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $sizecolorstoredetail->sizeid, $sizecolorstoredetail->colorid, (abs($productChangeAmount) * -1), 1);
        //affect product to make it have total quantity
        $storeDetailData = $myStoredetailEx->queryWithStoreAndProductandunit($sizecolorstoredetail->productid, $sizecolorstoredetail->storeid, 0);
        if (!isset($storeDetailData) || empty($storeDetailData->storedetailid)) {
            insertStoredetail($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $productChangeAmount, 0, 0, 0);
        } else {
            //$myStoredetailEx->updateQuantityPlusEqualORMinusEqual($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), $productChangeAmount, 0, 1);
            $myStoredetailEx->updateQuantityWithSumChild($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $sizecolorstoredetail->storeid, $sizecolorstoredetail->productid);
        }
    } else {

        //update productquantity in storedetail tbl
        $myStoredetail->storedetailid = $storedetailId;
        $myStoredetail->userid = $_SESSION['userid'];
        $myStoredetail->storedetaildate = date("Y-m-d");
        $myStoredetail->productquantity = $productquantityAfter;

        $myStoredetailEx->updateProductquantity($myStoredetail);

        onlineTempStoreDetailFunc($myStoredetail->storeid, $myStoredetail->productid, 0, 0, abs($productChangeAmount), 1);
    }

    //
    increaseHandleBuyPricesHistoryBook($movementRow);
    increaseProductParcodeSerialQuantity($movementRow, $storeId);
    return $productquantityAfter;
}

//update and decrease Rawmaterialamount in storerawmaterialdetails tbl
function decreaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount, $sizeColorStoreDetailId, $sizeId, $colorId, $movementRow) {
    global $myStoredetail;
    global $myStoredetailRecord;
    global $myStoredetailEx;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    //increase productquantity
    $productquantityAfter = $productquantityBefore - $productChangeAmount;
    $myStoredetail = $myStoredetailRecord->load($storedetailId);
    $storeId = $myStoredetail->storeid;

    if (empty($sizeColorStoreDetailId) && $sizeId > 0 && $colorId > 0) {
        //try to copy from existing data in store 1
        $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($myStoredetail->productid, 1, $sizeId, $colorId);
        $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

        $sizeColorStoreDetail->storeid = $myStoredetail->storeid;
        $sizeColorStoreDetail->quantity = $productChangeAmount;
        $sizeColorStoreDetail->userid = $_SESSION['userid'];
        $sizeColorStoreDetail->sysdate = date("Y-m-d H:i:s");

        $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
    }

    if (isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) {
        $sizecolorstoredetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);

        $storeId = $sizecolorstoredetail->storeid;

        $sizecolorstoredetail->userid = $_SESSION['userid'];
        $sizecolorstoredetail->sysdate = date("Y-m-d H:i:s");
        $sizecolorstoredetail->quantity = $productquantityAfter;
        $sizeColorStoreDetailDAO->update($sizecolorstoredetail);
        onlineTempStoreDetailFunc($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $sizecolorstoredetail->sizeid, $sizecolorstoredetail->colorid, (abs($productChangeAmount) * -1), 1);
        //affect product to make it have total quantity
        $storeDetailData = $myStoredetailEx->queryWithStoreAndProductandunit($sizecolorstoredetail->productid, $sizecolorstoredetail->storeid, 0);
        if (!isset($storeDetailData) || empty($storeDetailData->storedetailid)) {
            insertStoredetail($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $productChangeAmount, 0, 0, 0);
        } else {
            //$myStoredetailEx->updateQuantityPlusEqualORMinusEqual($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), $productChangeAmount, 0, 1);
            $myStoredetailEx->updateQuantityWithSumChild($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $sizecolorstoredetail->storeid, $sizecolorstoredetail->productid);
        }
    } else {

        //update productquantity in storedetail tbl
        $myStoredetail->storedetailid = $storedetailId;
        $myStoredetail->userid = $_SESSION['userid'];
        $myStoredetail->storedetaildate = date("Y-m-d");
        $myStoredetail->productquantity = $productquantityAfter;

        $myStoredetailEx->updateProductquantity($myStoredetail);

        onlineTempStoreDetailFunc($myStoredetail->storeid, $myStoredetail->productid, 0, 0, (abs($productChangeAmount) * -1), 1);
    }

    //
    decreaseFromHandleBuyPricesHistoryBook($movementRow, $productChangeAmount);
    decreaseProductParcodeSerialQuantity($movementRow, $storeId);

    return $productquantityAfter;
}

//add in storerawmaterialdetails tbl
function insertStoredetail($storeid, $productid, $productChangeAmount, $sizeColorStoreDetailId, $sizeId, $colorId) {
    global $myStoredetail;
    global $myStoredetailRecord;
    global $myStoredetailEx;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    //increase productquantity
    if (empty($sizeColorStoreDetailId) && $sizeId > 0 && $colorId > 0) {
        //try to copy from existing data in store 1
        $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productid, 1, $sizeId, $colorId);
        $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

        $sizeColorStoreDetail->storeid = $storeid;
        $sizeColorStoreDetail->quantity = $productChangeAmount;
        $sizeColorStoreDetail->userid = $_SESSION['userid'];
        $sizeColorStoreDetail->sysdate = date("Y-m-d H:i:s");

        $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
    }
    $row = $myStoredetailEx->queryByStoreidAndProductid($productid, $storeid);
    if (!isset($row->storedetailid) || $row->storedetailid < 1) {
        $myStoredetail->userid = $_SESSION['userid'];
        $myStoredetail->storedetaildate = date("Y-m-d");
        $myStoredetail->productquantity = $productChangeAmount;
        $myStoredetail->storeid = $storeid;
        $myStoredetail->productid = $productid;

        $myStoredetailRecord->insert($myStoredetail);
    } else {
        $myStoredetailEx->updateQuantityWithSumChild($row->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $storeid, $productid);
    }
}

//add in Storemovement tbl
function insertStorereport($productid, $storeid, $productChangeAmount, $productbefore, $productafter, $storereporttype, $storereportmodelid, $processname, $tablename, $sizeId, $colorId) {
    global $myStorereport;
    global $myStorereportRecord;

    $myStorereport->processname = $processname;
    $myStorereport->productafter = $productafter;
    $myStorereport->productbefore = $productbefore;
    $myStorereport->productquantity = $productChangeAmount;
    $myStorereport->productid = $productid;
    $myStorereport->storeid = $storeid;
    $myStorereport->storereportdate = date("Y-m-d");
    $myStorereport->storereportmodelid = $storereportmodelid;
    $myStorereport->storereporttype = $storereporttype;
    $myStorereport->tablename = $tablename;
    $myStorereport->userid = $_SESSION['userid'];
    $myStorereport->sizeid = $sizeId;
    $myStorereport->colorid = $colorId;

    $id = $myStorereportRecord->insert($myStorereport);
    $myStorereport->storereportid = $id;
    onlineTempStoreReportFunc($myStorereport);
}

function decreaseFromHandleBuyPricesHistoryBook($storemovement, $soldQuantity) {
    global $buyPricesHistoryBookDAO;
    global $buyPricesHistoryBookEX;
    global $myStoremovementEx;
    global $myProductRecord;
    global $operationFlag;

    $storeId = $storemovement->storeidfrom;
    if ($operationFlag == 1) {
        $storeId = $storemovement->storeidto;
    }
    $productid = $storemovement->productid;
    $sizeid = $storemovement->sizeid;
    $colorid = $storemovement->colorid;

    $idQuantityString = '';
    $remainQuantity = $soldQuantity;
    do {
        $buyPriceFromHistoryBook = $buyPricesHistoryBookEX->getBuyPriceOfFirstAvailableSellQuantity($storeId, $productid, $sizeid, $colorid);
        if (isset($buyPriceFromHistoryBook->id) && $buyPriceFromHistoryBook->id > 0 && $remainQuantity > 0) {
            $availableBuyQuantity = $buyPriceFromHistoryBook->buyQuantity - $buyPriceFromHistoryBook->sellQuantity;
            $buyPriceFromHistoryBook->sysDate = date('Y-m-d H:i:s');
            if ($availableBuyQuantity >= $remainQuantity) {
                $buyPriceFromHistoryBook->buyQuantity = $remainQuantity;
                $buyPriceFromHistoryBook->sellQuantity = 0;
                $buyPricesHistoryBookEX->insertOrUpdateMinusEXBuyPriceNoUpdate($buyPriceFromHistoryBook);
                //
                $idQuantityString .= "$remainQuantity*$buyPriceFromHistoryBook->theDate*$buyPriceFromHistoryBook->buyprice,";
                //
                $remainQuantity -= $remainQuantity; //$remainQuantity = 0;
            } elseif ($remainQuantity > $availableBuyQuantity) {
                $buyPriceFromHistoryBook->buyQuantity = $availableBuyQuantity;
                $buyPriceFromHistoryBook->sellQuantity = 0;
                $buyPricesHistoryBookEX->insertOrUpdateMinusEXBuyPriceNoUpdate($buyPriceFromHistoryBook);
                //
                $idQuantityString .= "$availableBuyQuantity*$buyPriceFromHistoryBook->theDate*$buyPriceFromHistoryBook->buyprice,";
                //
                $remainQuantity -= $availableBuyQuantity;
            }
        }
    } while (isset($buyPriceFromHistoryBook->id) && $buyPriceFromHistoryBook->id > 0 && $remainQuantity > 0);

    if ($remainQuantity > 0) {
        //insert the remain in buyPriceFromHistoryBook with -ve quantity
        $productData = $myProductRecord->load($productid);
        $buyPriceHistoryBook->theDate = date("Y-m-d");
        $buyPriceHistoryBook->storeId = $storeId;
        $buyPriceHistoryBook->productid = $productid;
        $buyPriceHistoryBook->sizeid = $sizeid;
        $buyPriceHistoryBook->colorid = $colorid;
        $buyPriceHistoryBook->buyprice = $productData->lastbuyprice;
        $buyPriceHistoryBook->buyQuantity = $remainQuantity * -1;
        $buyPriceHistoryBook->sellQuantity = 0;
        $buyPriceHistoryBook->del = 0;
        $buyPriceHistoryBook->userid = $_SESSION['userid'];
        $buyPriceHistoryBook->sysDate = date("Y-m-d H:i:s");
        //need to decrase quantity if it is insert quqntity is -ve ok, if update  "insertOrUpdatePlusEX" with + sign and -ve of quantity it will decrease quantity
        $buyPricesHistoryBookEX->insertOrUpdatePlusEX($buyPriceHistoryBook);
        $idQuantityString .= "$remainQuantity*$buyPriceHistoryBook->theDate*$buyPriceHistoryBook->buyprice,";
    }

    //save buyPricesHistoryBookData in Storemovement row in db
    $myStoremovementEx->updateBuyPricesHistoryBookData($idQuantityString, $storemovement->transferproductid);
}

function increaseHandleBuyPricesHistoryBook($storemovement) {
    global $myStoremovementRecord;
    global $buyPricesHistoryBookDAO;
    global $buyPricesHistoryBookEX;
    global $operationFlag;


    if (empty($storemovement->buyPricesHistoryBookData)) {
        $storemovement = $myStoremovementRecord->load($storemovement->transferproductid);
    }


    foreach (explode(',', $storemovement->buyPricesHistoryBookData) as $row) { //$idQuantityString =$remainQuantity*$buyPriceFromHistoryBook->theDate*$buyPriceFromHistoryBook->buyprice,";
        $data = explode('*', $row);
        $quantity = $data[0];
        $date = $data[1];
        $buyPrice = $data[2];
        if (!empty($date) && !empty($quantity) && !empty($buyPrice)) {
            $obj = new stdClass();
            $obj->theDate = $date;
            $obj->storeId = $storemovement->storeidto;
            if ($operationFlag == 1) {
                $obj->storeId = $storemovement->storeidfrom;
            }
            $obj->productid = $storemovement->productid;
            $obj->sizeid = $storemovement->sizeid;
            $obj->colorid = $storemovement->colorid;
            $obj->buyprice = $buyPrice;
            $obj->buyQuantity = $quantity;
            $obj->sellQuantity = 0;
            $obj->del = 0;
            $obj->userid = $storemovement->userid;
            $obj->sysDate = date('Y-m-d H:i:s');
            $buyPricesHistoryBookEX->insertOrUpdatePlusEXBuyPriceNoUpdate($obj);
        }
    }
}

function dateTimeDiff($dateTime1, $dateTime2) {
    $dateTime1 = new DateTime($dateTime1);
    $dateTime2 = new DateTime($dateTime2);

    $diff = $dateTime2->diff($dateTime1);
    $hours = $diff->h;
    $hours = $hours + ($diff->days * 24);
    return $hours;
}

////////////////////eman/////////////
function editshow() {
    //to use the variable out side the funcion
    global $myStoremovementEx;
    global $Otherstoremovement;
    global $OtherstoremovementDAO;
    global $OtherstoremovementEX;

    $operationnum = $_GET['operationnum'];

    $myotherdata = $OtherstoremovementDAO->load($operationnum);
    $deloperation = $myotherdata->deloperation;



    $notdeletedData = $myStoremovementEx->queryStoremovementByoperationnumold22($operationnum, 0);
    //$mydata = $OtherstoremovementDAO->load($operationnum);
    $mydata = array('operationnum' => $notdeletedData[0]->operationnum, 'transferproductdate' => $notdeletedData[0]->transferproductdate);


    $deletedData = $myStoremovementEx->queryStoremovementByoperationnumold22($deloperation, 1);

    $mydatadeleted = $OtherstoremovementDAO->load($deloperation);


    //return array($mydata, $notdeletedData, $mydatadeleted, $deletedData);
    return array($mydata, $notdeletedData, $mydatadeleted, $deletedData);
}

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 $myStoredetailEx;
    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 = $myStoredetailEx->queryWithStoreAndProduct($productId, $storeid);

        $productquantityBefore = $storedetailData->productquantity;
    }

    return $productquantityBefore;
}

function decreaseProductParcodeSerialQuantity($moveRow, $storeId) {
    global $myProductserialDAO;
    global $myProductserialEx;
    global $myStoremovementEx;
    global $operationFlag;

    $requiredQuantity = $moveRow->transferproductamount;
    if ($operationFlag == 0) //add
        $proSerials = $moveRow->expireDate;
    elseif ($operationFlag == 1) //del
        $proSerials = $moveRow->expireDateTo;

    $storemovementId = $moveRow->transferproductid;

    $doneQuantity = 0;
    $stillNeededQuantity = $requiredQuantity;
    $productSerials = '';
    $temp;
    if (isset($proSerials) && !empty($proSerials) && $requiredQuantity > 0) {
        foreach (explode(',', $proSerials) as $productserailId) {
            if ($stillNeededQuantity > 0) {
                if ($operationFlag == 1 || strpos($productserailId, "*")) { //del
                    $temp = explode('*', $productserailId);
                    $productserailId = $temp[0];
                }
                $serialData = $myProductserialDAO->load($productserailId);
                $don = $serialData->don;
                if ($operationFlag == 1) //del
                    $don = $temp[1];

                if ($don > 0) {
                    //know quantity to reduce form this serial
                    $quantityForThisSerial = 0;
                    if ($don >= $stillNeededQuantity) {
                        $quantityForThisSerial = $stillNeededQuantity;
                    } elseif ($don < $stillNeededQuantity) {
                        $quantityForThisSerial = $don;
                    }

                    #decrease store quantity
                    $serialData->don -= $quantityForThisSerial;
                    $myProductserialEx->updateDon($serialData);

                    //                        $result = $myProductserialEx->queryByserialnumber_Store_ProductAndExpireDateNotDel($serialData->serialnumber, $serialData->productid, $serialData->sizeid, $serialData->colorid, $storeId, $serialData->enddate);
                    //                        if (count($result) > 0) {
                    //                            $result[0]->don -= $quantityForThisSerial;
                    //                            $myProductserialEx->updateDon($result[0]);
                    //                        } else {
                    //                            $serialData->don = $quantityForThisSerial;
                    //                            $serialData->storeid = $storeId;
                    //                            $serialData->productserailid = $myProductserialDAO->insert($serialData, '');
                    //                        }
                    #
                    //
                    $doneQuantity += $quantityForThisSerial;
                    $stillNeededQuantity -= $quantityForThisSerial;
                    $productSerials .= $serialData->productserailid . '*' . $quantityForThisSerial . ','; //$serialData->serialnumber . ',';
                }
            }
        }

        if ($storemovementId > 0 /* && $doneQuantity == $requiredQuantity */) {
            $productSerials = rtrim($productSerials, ',');
            if ($_GET['do'] == "add") //add
                $myStoremovementEx->updateExpireDateEX($storemovementId, $productSerials);
        }
    }
}

function increaseProductParcodeSerialQuantity($moveRow, $storeId) {
    global $myProductserialDAO;
    global $myProductserialEx;
    global $myStoremovementRecord;
    global $myStoremovementEx;
    global $operationFlag;

    $moveRow = $myStoremovementRecord->load($moveRow->transferproductid);
    $requiredQuantity = $moveRow->transferproductamount;
    if ($operationFlag == 0) //add
        $proSerials = $moveRow->expireDate;
    elseif ($operationFlag == 1) //del
        $proSerials = $moveRow->expireDate;
    $storemovementId = $moveRow->transferproductid;


    $doneQuantity = 0;
    $stillNeededQuantity = $requiredQuantity;
    $productSerials = '';
    if (isset($proSerials) && !empty($proSerials) && $requiredQuantity > 0) {
        foreach (explode(',', $proSerials) as $productserailId) {
            if ($stillNeededQuantity > 0) {
                $temp = explode('*', $productserailId);
                $productserailId = $temp[0];
                $don = $temp[1];
                $serialData = $myProductserialDAO->load($productserailId);

                //if ($don > 0) {
                //know quantity to reduce form this serial
                $quantityForThisSerial = 0;
                if ($don >= $stillNeededQuantity) {
                    $quantityForThisSerial = $stillNeededQuantity;
                } elseif ($don < $stillNeededQuantity) {
                    $quantityForThisSerial = $don;
                }


                //increase store
                if ($operationFlag == 0) { //add
                    $result = $myProductserialEx->queryByserialnumber_Store_ProductAndExpireDateNotDel($serialData->serialnumber, $serialData->productid, $serialData->sizeid, $serialData->colorid, $storeId, $serialData->enddate);
                    if (count($result) > 0) {
                        $result[0]->don += $quantityForThisSerial;
                        $myProductserialEx->updateDon($result[0]);
                    } else {
                        $serialData->don = $quantityForThisSerial;
                        $serialData->storeid = $storeId;
                        $serialData->productserailid = $myProductserialDAO->insert($serialData, '');
                    }
                } elseif ($operationFlag == 1) { //del
                    $serialData->don += $quantityForThisSerial;
                    $myProductserialEx->updateDon($serialData);
                }


                $doneQuantity += $quantityForThisSerial;
                $stillNeededQuantity -= $quantityForThisSerial;
                $productSerials .= $serialData->productserailid . '*' . $quantityForThisSerial . ','; //$serialData->serialnumber . ',';
                //}
            }
        }

        if ($storemovementId > 0 /* && $doneQuantity == $requiredQuantity */) {
            $productSerials = rtrim($productSerials, ',');
            if ($_GET['do'] == "add") //add
                $myStoremovementEx->updateExpireDateToEX($storemovementId, $productSerials);
        }
    }
}

function makeStoreMovementDailyEntry($mainData, $detailArr, $type = 0) { //$type=0 from store to store , 1 from part only , 2 to part only
    global $myStoremovementEx;
    global $myStoreRecord;
    global $myProductRecord;
    global $Programsettingdata;


    //Transaction
    $mytransactions = new Transaction();
    try {
        if ($Programsettingdata->makeDailyEntry == 1 && ($mainData->storeidfrom > 0 || $mainData->storeidto > 0) && $mainData->operationnum > 0 && count($detailArr) > 0) {
            $storefrom = $myStoreRecord->load($mainData->storeidfrom);
            $storeto = $myStoreRecord->load($mainData->storeidto);
            $sumPrice = 0;
            foreach ($detailArr as $value) {
                $proData = $myProductRecord->load($value->productid);
                $pro_price = 0;
                switch ($Programsettingdata->dailyEntryCostprice) {
                    case "first":
                        $pro_price = (float) $proData->productBuyPrice;
                        break;
                    case "last":
                        $pro_price = (float) $proData->lastbuyprice;
                        break;
                    case "mean":
                        $pro_price = (float) $proData->meanbuyprice;
                        break;
                    case "last_discount":
                        $pro_price = (float) $proData->lastbuyprice_withDiscount;
                        break;
                    case "mean_discount":
                        $pro_price = (float) $proData->meanbuyprice_withDiscount;
                        break;
                    case "tax":
                        $pro_price = (float) $proData->lastbuyprice_withTax;
                        break;
                    case "mean_tax":
                        $pro_price = (float) $proData->meanbuyprice_withTax;
                        break;
                    default:
                        $pro_price = (float) $proData->overAllAveragePrice;
                        break;
                }

                $sumPrice += $value->amount * $pro_price;
            }

            $dailyEntry->entryComment = "تحويل من مخزن " . $storefrom->storeName . " الى مخزن " . $storeto->storeName . "";
            $dailyEntry->fromFlag = 1;
            $dailyEntryDebtorArray = array();
            $dailyEntryCreditorArray = array();

            //type 3 to check direct or using between store
            if ($type == 3) {
                if ($mainData->recieveType == 1) {
                    $type = 1;
                } else {
                    $type = 0;
                }
            }

            switch ($type) {
                case 0: // from to "all cycle Done"
                    $dailyEntryDebtor = new stdClass();
                    $dailyEntryDebtor->value = $sumPrice;
                    $dailyEntryDebtor->accountstreeid = $storeto->treeId;
                    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

                    $dailyEntryCreditor = new stdClass();
                    $dailyEntryCreditor->value = $sumPrice;
                    $dailyEntryCreditor->accountstreeid = $storefrom->treeId;
                    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
                    break;
                case 1: // from part only
                    $dailyEntryDebtor = new stdClass();
                    $dailyEntryDebtor->value = $sumPrice;
                    $dailyEntryDebtor->accountstreeid = $storefrom->treeIdBetween;
                    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

                    $dailyEntryCreditor = new stdClass();
                    $dailyEntryCreditor->value = $sumPrice;
                    $dailyEntryCreditor->accountstreeid = $storefrom->treeId;
                    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
                    break;
                case 2: // to part only
                    $dailyEntry->entryComment = "استلام التحويل من مخزن " . $storefrom->storeName . " الى مخزن " . $storeto->storeName . "";
                    $dailyEntryDebtor = new stdClass();
                    $dailyEntryDebtor->value = $sumPrice;
                    $dailyEntryDebtor->accountstreeid = $storeto->treeId;
                    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

                    $dailyEntryCreditor = new stdClass();
                    $dailyEntryCreditor->value = $sumPrice;
                    $dailyEntryCreditor->accountstreeid = $storefrom->treeIdBetween;
                    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
                    break;
            }


            $returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $mainData->operationnum, "storemovementController.php?do=show&operationnum=" . $mainData->operationnum);
            $dailyentryid = $returnDailyId[1];
        }
        $mytransactions->commit();
        //we get $dailyentryid after commit
        if ($dailyentryid > 0) {
            $myStoremovementEx->updatedailyentryidByoperationnum($dailyentryid, $mainData->operationnum);
        }
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
}

function markStoreDetailNotInUse($storeDetailIds, $sizeColorStoreDetailIds) {
    //mark storedetail as not InUSe
    if ($storeDetailIds) {
        foreach ($storeDetailIds as $id) {
            if($id){
                $detailData = R::getRow('select * from storedetail where storedetailid = ' . $id);
                if($detailData && $detailData['inUse'] == 1) {
                    R::exec('update storedetail set inUse = 0 where storedetailid = ' . $id);
                }
            }
        }
    }
    if ($sizeColorStoreDetailIds) {
        foreach ($sizeColorStoreDetailIds as $id) {
            if($id){
                $detailData = R::getRow('select * from sizecolorstoredetail where id = ' . $id);
                if($detailData && $detailData['inUse'] == 1) {
                    R::exec('update sizecolorstoredetail set inUse = 0 where id = ' . $id);
                }
            }
        }
    }
}
class storeTotals {

    public $storeName;
    public $totalQuantityFrom = 0;
    public $totalQuantityTo = 0;

}
