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


//Product
$myProductRecord = new ProductMySqlDAO();

//user
$user = new User();
$userDAO = new UserMySqlDAO();
$userEX = new UserMySqlExtDAO();
//
$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);
//
$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', '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
    $storeData = loadStore();
    $smarty->assign("storeData", $storeData);


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

    //user session
    $sessionUserId = $_SESSION['userid'];
    $userData = $userDAO->load($sessionUserId);
    $loadStoreByUser = $myStoreRecord->load(1);
    $smarty->assign("loadStoreByUser", $loadStoreByUser);


    $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("storetransferrequestview/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 ($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);
            header('Location: storemovementController.php?do=editorder&on=' . $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 == "show") {

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

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

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

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

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


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


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

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

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

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


    if (isset($operationnum) && $operationnum != -1) {
        $message = " عرض تحميلات المخازن لرقم الايصال: " . $operationnum . "";
        $smarty->assign('message', $message);
        showByoperationnum($operationnum);
    }
//    elseif (isset($storeidto) && $storeidto != -1 && isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "" && $operationnum == -1) {
//        $mystore =  $myStoreRecord->load($storeidto);
//        $message = " عرض تحميلات المخازن الى  مخزن: " . $mystore->storeName . "  من تاريخ " . $startDate . "الى تاريخ:" . $endDate;;
//        $smarty->assign('message', $message);
//        showBystoreidto2($storeidto , $startDate, $endDate);
//    }
//    elseif (isset($storeidto) && $storeidto != -1) {
//        $mystore =  $myStoreRecord->load($storeidto);
//        $message = " عرض تحميلات المخازن الى  مخزن: " . $mystore->storeName . "";
//        $smarty->assign('message', $message);
//        showBystoreidto($storeidto);
//    }
    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("storetransferrequestview/showdetails.html");


    $smarty->assign("customCheck", 1);
}


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

    $transferproductId = $_GET['transferproductid'];

    // here the function that do the action
    $productsAfterValid = returndelete($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=";
        $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 ($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("storetransferrequestview/editprint.html");


    $smarty->assign("customPrint", 1);
}
//edit  transfer
elseif ($do == "edit") {
    //here the permssion check
    include_once("../public/authentication.php");

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

    $smarty->display("storetransferrequestview/edit.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("storetransferrequestview/recieve.html");
}
//
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($e);
        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("storetransferrequestview/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("customStoremovement", 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 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();
    try {
        $storeidfrom = $_POST['storeidfrom'];
        $storeidto = $_POST['storeidto'];

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

        $driverid = $_POST['driver'];
        $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 . ''];
            $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 = 1; //#تحميل بين المخازن

                $myStoremovement->sizeid = $sizeId;
                $myStoremovement->colorid = $colorId;
                $myStoremovement->expireDate = $expireDate;
                $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;
                        $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);
                }
            }
        }


        $add_print = $_POST['add_print'];
        $product_arr = array($productsBeforeValid, $add_print, $operationnum);
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback($ex);
        $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 $Storedetail;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    ##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'];
        //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 . ''];

            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 = 1; //#تحميل بين المخازن
                $myStoremovement->sizeid = $sizeId;
                $myStoremovement->colorid = $colorId;
                $myStoremovement->expireDate = $expireDate;
                $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($ex);
        $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;
        $sizeId = $storeMovementObject->sizeid;
        $colorId = $storeMovementObject->colorid;
        $transferproductAmount = $storeMovementObject->transferproductamount;
        $transferproductId = $storeMovementObject->transferproductid;

        $mainData = $storeMovementObject;

        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($ex);
    }
}

//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 != '') {
        $storeQuery = 'and  ( storemovement.storeidfrom  = ' . $storeId . '  or storemovement.storeidto = ' . $storeId . ' )';
    }
    // get the all colums number
    $storemovementData = $myStoremovementEx->queryWithDate($startDate, $endDate, $queryString, 1, $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) {
    //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) ";
    }
    // get the all colums number
    $storemovementData = $myStoremovementEx->queryWithDate2($startDate, $endDate, $queryString, 1);

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

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

function showBystoreidto($storeidto) {
    //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) ";
    }
    // get the all colums number
    $storemovementData = $myStoremovementEx->queryWithstoreTo($storeidto, $queryString, 1);

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

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

function showBystoreidto2($storeidto, $startDate, $endDate) {
    //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) ";
    }
    // get the all colums number
    $storemovementData = $myStoremovementEx->queryWithstoreTo2($storeidto, $startDate, $endDate, $queryString, 1);

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

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

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


    if (count($storemovementData) == 0) {

        $storemovementData = $myStoremovementEx->querybyoperationnumsearch2($operationnum, 'operationnum', '', 1);
    }

    //
    $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) {
                // عشان اخفى الصف اللى اتعمل عليه تعديل قبل كدا
                //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) ";
    }

    // get the all colums number
    $storemovementData = $myStoremovementEx->querybyoperationnumsearch3($operationnum, 'deloperationnum', $queryString, 1);


    if (count($storemovementData) == 0) {

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

    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) {
                // عشان اخفى الصف اللى اتعمل عليه تعديل قبل كدا
                //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)) {
        $singleStoremovement = $myStoremovementEx->loadStoremovementById($transferproductId);
        //Transaction
        $mytransactions = new Transaction();
        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) {
            $note = "حدث خطأ أثناء حذف التحويل";
            $productsBeforeValid = 2;
            $mytransactions->rollback($e);
        }
        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)) {
        $Storemovement_data = $myStoremovementEx->operationData2($operationnum);


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

            $transferproductId = $oper_data->transferproductid;
            $singleStoremovement = $myStoremovementEx->loadStoremovementById($transferproductId);
            //Transaction
            $mytransactions = new Transaction();
            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;

                    //get storefrom productquantity before change
                    $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
                    $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
                    $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);
                }
                //قيود اليومية
                $dailyentryIdArr = !empty($dailyentryIdArr) ? array_unique($dailyentryIdArr) : [0];
                foreach ($dailyentryIdArr as $entryid) {
                    reverseEntryWithItsID($entryid, 1);
                }
                $mytransactions->commit();
            } catch (Exception $e) {
                $note = "حدث خطأ أثناء حذف التحويل";
                $productsBeforeValid = 2;
                $mytransactions->rollback($e);
            }
        }
        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) {
            $note = "حدث خطأ أثناء اعادة حذف التحويل";
            $productsBeforeValid = 2;
            $mytransactions->rollback($e);
        }

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

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


        foreach ($Storemovement_data as $oper_data) {
            $transferproductId = $oper_data->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;
                    $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, $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);
                    //
                    $obj = new stdClass();
                    $obj->productid = $productId;
                    $obj->amount = $transferproductAmount;
                    array_push($detailArr, $obj);
                }
                $mytransactions->commit();
            } catch (Exception $e) {
                $note = "حدث خطأ أثناء اعادة حذف التحويل";
                $productsBeforeValid = 2;
                $mytransactions->rollback($e);
            }
        }


        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['transferproductid'];

    $loadData = $myStoremovementEx->loadStoremovementById($transferproductId);
    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);
}

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

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,3 like 1 but you decide from $mainData
    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];

            $myStoremovementEx->updatedailyentryidByoperationnum($dailyentryid, $mainData->operationnum);
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback($ex);
    }
}

Class storeTotals {

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

}

?>