<?php

//Transaction
include_once("../models/sql/Transaction.class.php");
//the global file operation
include("../public/impOpreation.php");

//global varable
global $showoutside;

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


//here the db files that include in the file
// 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');

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

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

//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
$smarty->display("header.html");


//here goes the instances and general variables
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
//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 = new ProductMySqlDAO();

//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();
//Usergroup
$Usergroup = new Usergroup();
$UsergroupDAO = new UsergroupMySqlDAO();
$UsergroupEX = new UsergroupMySqlExtDAO();

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

$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);
//
$Usergroupdata = $UsergroupDAO->load($_SESSION['usergroupid']);
$smarty->assign("Usergroupdata", $Usergroupdata);
//Decide operation add,del do
$operationFlag = -1;
$addArr = array('add', 'returndelete');
$delArr = array('tempdelete');
$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
$detailArr = array();

//check and use the condetion that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");

    $smarty->assign("storenegative", $_SESSION['storenegative']);
    // 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);
        $storedef = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("storedef", $storedef);
        $smarty->assign("storeid", $_SESSION['storeid']);
    } else {
        $storedef = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("storedef", $storedef);
        $smarty->assign("storeid", $_SESSION['storeid']);
    }




    $storeData = loadStore();
    $smarty->assign("storeData", $storeData);
    $today = date("Y-m-d");
    $smarty->assign("today", $today);

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

    $last = $last_val->operationnum + 1;

    $smarty->assign("nextId", $last);
    //here the smarty templates
    $smarty->assign("othercustomStoremovement", 1);
    $smarty->display("otherstoremovementview/add.html");
} elseif ($do == "edit") {
    //here the permssion check
    include_once("../public/authentication.php");










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




    $loadData = edit();




    $myolddata = $loadData[0];
    $smarty->assign("myolddata", $myolddata);


    //  $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);
    //     $storedef = $myStoreEx->queryByConditionsOne(' and store.storeId = '.$_SESSION['storeid'].' ');
    //     $smarty->assign("storedef", $storedef);
    //     $smarty->assign("storeid", $_SESSION['storeid']);
    // }else{
    //     $storedef = $myStoreEx->queryByConditionsOne(' and store.storeId = '.$_SESSION['storeid'].' ');
    //     $smarty->assign("storedef", $storedef);
    //     $smarty->assign("storeid", $_SESSION['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("stores", $stores);
        $storedef = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("storedef", $storedef);
        $smarty->assign("storeid", $_SESSION['storeid']);
    } else {
        $storedef = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("storedef", $storedef);
        $smarty->assign("storeid", $_SESSION['storeid']);
    }







    $myoldmovement = $loadData[1];
    $smarty->assign("myoldmovement", $myoldmovement);

    $smarty->assign("itr", count($myoldmovement));


    $smarty->display("otherstoremovementview/edit.html");

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

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

    // here the function that do the action
    $productsAfterValid = add();
    if ($productsAfterValid[0] === "error") {//coming from rollback
        header("location:?do=error");
    } else if ($productsAfterValid == 1) {
        makeStoreMovementDailyEntry($detailArr);
        header("location:?do=sucess");
    } else {
        makeStoreMovementDailyEntry($detailArr);
        $url = "otherstoremovementController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لا يوجد بالمخزن الكمية الكافية لتحويل المنتجات";

        $smarty->assign('msgnote', $note);

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

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

    //Transaction
    $mytransactions2 = new Transaction();
    try {
        // here the function that do the action
        $oldoperationnum = $_POST["oldoperationnum"];
        $operationFlag = 1; //means del, decrease store to & increase store from
        tempdelete($oldoperationnum);
        $operationFlag = 0; //means add , decrease store from & increase store to
        $productsAfterValid = newadd($oldoperationnum);
        makeStoreMovementDailyEntry($detailArr);
        $mytransactions2->commit();
        if ($productsAfterValid[0] === "error") {//coming from rollback
            header("location:?do=error");
        } else {
            header("location:?do=sucess");
        }
        //tempdelete($oldoperationnum);
//    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");
//    }
    } catch (Exception $ex) {
        $mytransactions2->rollback();
    }
} elseif ($do == "show") {

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

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

    $alloperationnum = $OtherstoremovementDAO->queryByDel(0);
    $smarty->assign('alloperationnum', $alloperationnum);
    show();
    $smarty->display("otherstoremovementview/show.html");
    $smarty->assign("customCheck", 1);
}



//returndelete
elseif ($do == "returndelete") {
    include_once("../public/authentication.php");

    $operationnum = $_GET['operationnum'];

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


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

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

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

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

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

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

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    } else {
        $url = "otherstoremovementController.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("otherstoremovementview/editprint.html");


    $smarty->assign("customPrint", 1);
}
//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("otherstoremovementview/editshow.html");
}


//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("otherstoremovementview/show.html");

    $smarty->assign("customCheck", 1);
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}
$smarty->assign("othercustomStoremovement", 1);

$smarty->assign('customValidation', 1);
//here the global templates
$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;
}

// add in storemovement tbl
function newadd($oldoperationnum) {

    //to use the variable out side the funcion
    global $myStoremovement;
    global $myStoremovementRecord;
    global $myStoremovementEx;

    global $Otherstoremovement;
    global $OtherstoremovementDAO;
    global $OtherstoremovementEX;

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

    ##for daily entry
    global $detailArr;


    //Transaction
    if ($_GET['do'] != "update")
        $mytransactions = new Transaction();
    try {
        $serail = $_POST['serail'];

        $comment = $_POST['comment'];
        $mydate = $_POST["mydate"];
        $productItr = $_POST['productitr'];


        $Otherstoremovement->comment = $comment;
        $Otherstoremovement->del = 0;
        $Otherstoremovement->deloperation = $oldoperationnum;
        $Otherstoremovement->oprationdata = $mydate; //date("Y-m-d");
        $Otherstoremovement->oprationnumber = $serail;
        $Otherstoremovement->userid = $_SESSION['userid'];

        $Otherstoremovementid = $OtherstoremovementDAO->insert($Otherstoremovement);


        $OtherstoremovementEX->updatedel(1, $oldoperationnum);




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


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


                $productId = $oldproduct;
            }

            if (isset($productId) && !empty($productId) && $productId != '-1' && $productId != '') {
                //get storefrom productquantity before change
                $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'];



                    $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 = 1;
        $i = 1;
        $operationnum = 0;
        for ($h = 1; $h <= $productItr; $h++) {
            $productId = $_POST['product' . $h . ''];
            $transferproductAmount = $_POST['productamount' . $h . ''];
            $storeidfrom = $_POST['storeidfrom' . $h . ''];
            $storeidto = $_POST['storeidto' . $h . ''];
            $oldproduct = $_POST['oldproduct' . $h . ''];

            if (!isset($productId) || empty($productId)) {
                $productId = $oldproduct;
            }


            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 = new stdClass();
                $myStoremovement->conditions = 0;
                $myStoremovement->storeidfrom = $storeidfrom;
                $myStoremovement->storeidto = $storeidto;
                $myStoremovement->transferproductdate = $mydate;
                $myStoremovement->userid = $_SESSION["userid"];
                $myStoremovement->productid = $productId;
                $myStoremovement->transferproductamount = $transferproductAmount;
                $myStoremovement->comment = $comment;

                $myStoremovement->deloperationnum = $oldoperationnum;
                $myStoremovement->sizeid = $sizeId;
                $myStoremovement->colorid = $colorId;


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

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

                        $transferproductId = $spData->id;
                        $operationnum = $serail = $spData->optnum;
                        $OtherstoremovementEX->updateoprationnumber($operationnum, $Otherstoremovementid);
                        $i++;
                    } else {
                        $myStoremovement->operationnum = $operationnum; //$Otherstoremovementid;
                        $transferproductId = $myStoremovementEx->insertEX($myStoremovement);
                    }
                    $myStoremovement->transferproductid = $transferproductId;

                    //
                    array_push($detailArr, $myStoremovement);

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

        //
        if ($_GET['do'] != "update")
            $mytransactions->commit();
    } catch (Exception $ex) {
        //echo $ex;
        //
        if ($_GET['do'] != "update") {
            $mytransactions->rollback();
            $productsBeforeValid = array('error');
        }
    }
    return $productsBeforeValid;
}

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

    global $Otherstoremovement;
    global $OtherstoremovementDAO;
    global $OtherstoremovementEX;

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

    ##for daily entry
    global $detailArr;

    //Transaction
    $mytransactions = new Transaction();
    try {

        $serail = $_POST['serail'];

        $comment = $_POST['comment'];
        $mydate = $_POST["mydate"];
        $productItr = $_POST['productitr'];



        //print_r("productItr".$productItr."<br>");

        $h = 1;
        for ($h = 1; $h <= $productItr; $h++) {
            $productId = $_POST['product' . $h . ''];
            $transferproductAmount = $_POST['productamount' . $h . ''];
            $storeidfrom = $_POST['storeidfrom' . $h . ''];
            $storeidto = $_POST['storeidto' . $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;
                }
            }
        }


        $Otherstoremovement->del = 0;
        $Otherstoremovement->deloperation = 0;
        $Otherstoremovement->oprationnumber = $serail;
        $Otherstoremovement->userid = $_SESSION['userid'];
        $Otherstoremovement->comment = $comment;
        $Otherstoremovement->oprationdata = date("Y-m-d");

        $otherstoremovementid = $OtherstoremovementDAO->insert($Otherstoremovement);

        $h;
        $i = 1;
        for ($h = 1; $h <= $productItr; $h++) {
            $productId = $_POST['product' . $h . ''];
            $transferproductAmount = $_POST['productamount' . $h . ''];
            $storeidfrom = $_POST['storeidfrom' . $h . ''];
            $storeidto = $_POST['storeidto' . $h . ''];
            $expireDate = $_POST['proSerials' . $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 = new stdClass();
                $myStoremovement->conditions = 0;
                $myStoremovement->storeidfrom = $storeidfrom;
                $myStoremovement->storeidto = $storeidto;
                $myStoremovement->transferproductdate = $mydate;
                $myStoremovement->userid = $_SESSION["userid"];
                $myStoremovement->productid = $productId;
                $myStoremovement->transferproductamount = $transferproductAmount;
                $myStoremovement->comment = $comment;
                $myStoremovement->operationnum = $serail; //$otherstoremovementid;
                $myStoremovement->deloperationnum = 0;

                $myStoremovement->sizeid = $sizeId;
                $myStoremovement->colorid = $colorId;
                $myStoremovement->expireDate = $expireDate;

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

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

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

                        $OtherstoremovementEX->updateoprationnumber($operationnum, $otherstoremovementid);
                        $i++;
                    } else {
                        $transferproductId = $myStoremovementEx->insertEX($myStoremovement);
                    }
                    $myStoremovement->transferproductid = $transferproductId;
                    //
                    array_push($detailArr, $myStoremovement);

                    //////////////**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);
                    }
                }
            }
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $productsBeforeValid = array('error');
    }
    return $productsBeforeValid;
}

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

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

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

//showByoperationnum

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

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

        $storemovementData = $myStoremovementEx->querybyoperationnumsearch($operationnum, 'operationnum');
    }
    foreach ($storemovementData as $mystoremovementData) {

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

        $deloperationnum = $mystoremovementData->deloperationnum;
        if ($deloperationnum != 0 && $mystoremovementData->conditions <> 1) {
            $mystoremovementData->userid = -1;
        }
    }
    // assign your db results to the template
    $smarty->assign('storemovementData', $storemovementData);
}

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

    global $Otherstoremovement;
    global $OtherstoremovementDAO;
    global $OtherstoremovementEX;


    global $smarty;

    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $operationnum = $_REQUEST["operationnum"];
    $queryString = 'AND';




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

        if (isset($startDate) && $startDate != '' && isset($endDate) && $endDate != '') {


            $message = " عرض تحويلات المخازن من تاريخ: " . $startDate . "الى تاريخ:" . $endDate;
            $smarty->assign('message', $message);
            $queryString .= ' oprationdata >= "' . $startDate . '" and oprationdata <= "' . $endDate . '" AND';
        }


        if (!isset($startDate) || $startDate == '' || !isset($endDate) || $endDate == '') {
            $message = " عرض تحويلات المخازن من تاريخ: " . date("Y-m-d") . " الى تاريخ: " . date("Y-m-d");
            $smarty->assign('message', $message);
            $today = date("Y-m-d");
            $queryString .= ' oprationdata >= "' . $today . '" and oprationdata <= "' . $today . '" AND';
        }
    }


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

    // get the all colums number
    $storemovementData = $OtherstoremovementEX->queryAllEX($queryString);



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

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

    global $OtherstoremovementDAO;

    global $OtherstoremovementEX;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    if (isset($operationnum)) {
        //Transaction
        if ($_GET['do'] != "update")
            $mytransactions = new Transaction();
        try {
            $myotherdata = $OtherstoremovementDAO->load($operationnum);
            $operationnumStoreMovement = $myotherdata->oprationnumber;

            $myalldata = $myStoremovementEx->queryStoremovementByoperationnum($operationnumStoreMovement, 0);
            foreach ($myalldata as $myStoremovementdata) {

                $transferproductId = $myStoremovementdata->transferproductid;
                $conditions = $myStoremovementdata->conditions;
                if (isset($transferproductId)) {
                    $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);


                            reverseEntryWithItsID($storemovementData->dailyentryid, 1);
                        }
                    } catch (Exception $e) {
                        $note = "حدث خطأ أثناء حذف التحويل";
                        $productsBeforeValid = 2;
                    }
                }
            }
            $OtherstoremovementEX->updatedel(1, $operationnum);

            //
            if ($_GET['do'] != "update")
                $mytransactions->commit();
        } catch (Exception $ex) {
            //
            if ($_GET['do'] != "update")
                $mytransactions->rollback();
        }
        return array($note, $productsBeforeValid);
    }
}

function returndelete($operationnum) {

    global $myStoremovement;
    global $myStoremovementRecord;
    global $myStoremovementEx;

    global $OtherstoremovementDAO;

    global $OtherstoremovementEX;
    global $sizeColorStoreDetailEX;

    ##for daily entry
    global $detailArr;

    $myotherdata = $OtherstoremovementDAO->load($operationnum);
    $operationnumStoreMovement = $myotherdata->oprationnumber;

    $OtherstoremovementEX->updatedel(0, $operationnum);

    if (isset($operationnum)) {

        //Transaction
        $mytransactions = new Transaction();
        try {
            $myalldata = $myStoremovementEx->queryStoremovementByoperationnum($operationnumStoreMovement, 1);

            foreach ($myalldata as $myStoremovementdata) {

                $transferproductId = $myStoremovementdata->transferproductid;
                if (isset($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;
                            $sizeId = $storemovementData->sizeid;
                            $colorId = $storemovementData->colorid;
                            $transferproductId = $storemovementData->transferproductid;

                            //
                            array_push($detailArr, $storemovementData);


                            //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);
                        }
                    } catch (Exception $e) {
                        $note = "حدث خطأ أثناء اعادة حذف التحويل";
                        $productsBeforeValid = 2;
                    }

                    //return array($note,$productsBeforeValid);
                }
            }
            $mytransactions->commit();
        } catch (Exception $ex) {
            $mytransactions->rollback();
        }
        return array($note, $productsBeforeValid);
    }
}

//edit from transfer tbl
function edit() {
    //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;

    $operationnumStoreMovement = $myotherdata->oprationnumber;

    $notdeletedData = $myStoremovementEx->queryStoremovementByoperationnum($operationnumStoreMovement, 0);


    $mydata = $myStoremovementEx->loadByoperationnum($operationnumStoreMovement, 0);
    $deletedData = $myStoremovementEx->queryStoremovementByoperationnum($operationnumStoreMovement, 1);

    $mydatadeleted = $myStoremovementEx->loadByoperationnum($operationnumStoreMovement, 1);

    return array($myotherdata, $notdeletedData, $myotherdata, $deletedData);
}

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;

    $operationnumStoreMovement = $myotherdata->oprationnumber;

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


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

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


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

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 $operationnum) {

            if ($operationType == '1') {
                //tempdelete
                $note = tempdelete($operationnum);

                //print_r($note);
                if ($note[0] != "success") {
                    $outputString .= $note[0] . "<br/>";
                } else {
                    $outputString .= "تمت العملية بنجاح <br/>";
                }
                //print_r("<br><br>");
                //print_r($outputString);
            } elseif ($operationType == "2") {
                //returndelete
                $note = returndelete($operationnum);
                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);
}

//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 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($detailArr) {
    global $myStoremovementEx;
    global $myStoreRecord;
    global $myProductRecord;
    global $Programsettingdata;

    //Transaction
    $mytransactions = new Transaction();
    try {
        if ($Programsettingdata->makeDailyEntry == 1) {
            foreach ($detailArr as $value) {
                if ($value->storeidfrom > 0 && $value->storeidto > 0 && $value->operationnum > 0) {
                    $storefrom = $myStoreRecord->load($value->storeidfrom);
                    $storeto = $myStoreRecord->load($value->storeidto);

                    $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->transferproductamount * $pro_price;



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


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

                    $returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $mainData->operationnum, "otherstoremovementController.php?do=show&operationnum=" . $value->operationnum);
                    $dailyentryid = $returnDailyId[1];

                    $myStoremovementEx->updatedailyentryidBytransferproductid($dailyentryid, $value->transferproductid);
                }
            }
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
}

?>