<?php

//the global file operation
include("../public/impOpreation.php");

//global varable
global $showoutside;

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

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

//Productionrate
require_once('../models/dao/ProductionrateDAO.class.php');
require_once('../models/dto/Productionrate.class.php');
require_once('../models/mysql/ProductionrateMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionrateMySqlExtDAO.class.php');
//Productionrateproduct
require_once('../models/dao/ProductionrateproductDAO.class.php');
require_once('../models/dto/Productionrateproduct.class.php');
require_once('../models/mysql/ProductionrateproductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionrateproductMySqlExtDAO.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');

//task order
require_once('../models/dao/TaskorderDAO.class.php');
require_once('../models/dto/Taskorder.class.php');
require_once('../models/mysql/TaskorderMySqlDAO.class.php');
require_once('../models/mysql/ext/TaskorderMySqlExtDAO.class.php');
//task order products
require_once('../models/dao/TaskorderproductsDAO.class.php');
require_once('../models/dto/Taskorderproduct.class.php');
require_once('../models/mysql/TaskorderproductsMySqlDAO.class.php');
require_once('../models/mysql/ext/TaskorderproductsMySqlExtDAO.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');

//productionExecution
require_once('../models/dao/ProductionexecutionDAO.class.php');
require_once('../models/dto/Productionexecution.class.php');
require_once('../models/mysql/ProductionexecutionMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionexecutionMySqlExtDAO.class.php');
//productionExecutionProduct
require_once('../models/dao/ProductionexecutionoutputDAO.class.php');
require_once('../models/dto/Productionexecutionoutput.class.php');
require_once('../models/mysql/ProductionexecutionoutputMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionexecutionoutputMySqlExtDAO.class.php');
//productionExecutionOutput
require_once('../models/dao/ProductionexecutionproductDAO.class.php');
require_once('../models/dto/Productionexecutionproduct.class.php');
require_once('../models/mysql/ProductionexecutionproductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionexecutionproductMySqlExtDAO.class.php');
//productionExecutionWaste
require_once('../models/dao/ProductionexecutionwasteDAO.class.php');
require_once('../models/dto/Productionexecutionwaste.class.php');
require_once('../models/mysql/ProductionexecutionwasteMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionexecutionwasteMySqlExtDAO.class.php');

//Simplemanufacturesetting
require_once('../models/dao/SimplemanufacturesettingDAO.class.php');
require_once('../models/dto/Simplemanufacturesetting.class.php');
require_once('../models/mysql/SimplemanufacturesettingMySqlDAO.class.php');
require_once('../models/mysql/ext/SimplemanufacturesettingMySqlExtDAO.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');

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

//Productcat
require_once('../models/dao/ProductcatDAO.class.php');
require_once('../models/dto/Productcat.class.php');
require_once('../models/mysql/ProductcatMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatMySqlExtDAO.class.php');

//Sellbilldetail
require_once('../models/dao/SellbilldetailDAO.class.php');
require_once('../models/dto/Sellbilldetail.class.php');
require_once('../models/mysql/SellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbilldetailMySqlExtDAO.class.php');
//
require_once('../models/dao/SizecolorstoredetailDAO.class.php');
require_once('../models/dto/Sizecolorstoredetail.class.php');
require_once('../models/mysql/SizecolorstoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SizecolorstoredetailMySqlExtDAO.class.php');

//
require_once('../models/dao/BuypriceshistorybookDAO.class.php');
require_once('../models/dto/Buypriceshistorybook.class.php');
require_once('../models/mysql/BuypriceshistorybookMySqlDAO.class.php');
require_once('../models/mysql/ext/BuypriceshistorybookMySqlExtDAO.class.php');

require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');

//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 :- productionExecutionController

  OPERTATION in Controller///////////////////////////////////////////////////

  1-display add form
  2- add in productCat tble
  4-display sucess or error
  5-display show and delete
  6-delete from productCat tbl
  7-display edit
  8- update productCat tbl
  ======================== */


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

//here goes the instances and general variables
//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();
//Productionrate
$productionrate = new Productionrate();
$productionrateDAO = new ProductionrateMySqlDAO();
$productionrateEX = new ProductionrateMySqlExtDAO();

//Productionrateproduct
$Productionrateproduct = new Productionrateproduct();
$ProductionrateproductDAO = new ProductionrateproductMySqlDAO();
$ProductionrateproductEX = new ProductionrateproductMySqlExtDAO();

//taskorder
$taskorder = new Taskorder();
$taskorderDao = new TaskorderMySqlDAO();
$taskorderExt = new TaskorderMySqlExtDAO();

//taskorder products
$taskorderproducts = new Taskorderproduct();
$taskorderproductsDao = new TaskorderproductsMySqlDAO();
$taskorderproductsExt = new TaskorderproductsMySqlExtDAO();

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

//productionExecution
$productionExecution = new Productionexecution();
$productionExecutionDao = new ProductionexecutionMySqlDAO();
$productionExecutionExt = new ProductionexecutionMySqlExtDAO();

//productionExecutionProduct
$productionExecutionProduct = new Productionexecutionproduct();
$productionExecutionProductDao = new ProductionexecutionproductMySqlDAO();
$productionExecutionProductExt = new ProductionexecutionproductMySqlExtDAO();

//productionExecutionOutput
$productionExecutionOutput = new Productionexecutionoutput();
$productionExecutionOutputDao = new ProductionexecutionoutputMySqlDAO();
$productionExecutionOutputExt = new ProductionexecutionoutputMySqlExtDAO();

//productionExecutionWaste
$productionExecutionWaste = new Productionexecutionwaste();
$productionExecutionWasteDao = new ProductionexecutionwasteMySqlDAO();
$productionExecutionWasteExt = new ProductionexecutionwasteMySqlExtDAO();

//Simplemanufacturesetting
$simplesetting = new Simplemanufacturesetting();
$simplesettingDao = new SimplemanufacturesettingMySqlDAO();
$simplesettingExt = new SimplemanufacturesettingMySqlExtDAO();

//Storedetail
$myStoredetailEx = $StoredetailEX = new StoredetailMySqlExtDAO();
$myStoredetailRecord = new StoredetailMySqlDAO();

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

$buyBillDetailExt = new BuybilldetailMySqlExtDAO();

//Productcat
$productCat = new Productcat();
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();

//Sellbilldetail
$mySellbilldetail = new Sellbilldetail();
$mySellbilldetailRecord = new SellbilldetailMySqlDAO();
$mySellbilldetailEx = new SellbilldetailMySqlExtDAO();
//
$sizeColorStoreDetail = new Sizecolorstoredetail();
$sizeColorStoreDetailDAO = new SizecolorstoredetailMySqlDAO();
$sizeColorStoreDetailEX = new SizecolorstoredetailMySqlExtDAO();

//Buypriceshistorybook
$buyPricesHistoryBook = new Buypriceshistorybook();
$buyPricesHistoryBookDAO = new BuypriceshistorybookMySqlDAO();
$buyPricesHistoryBookEX = new BuypriceshistorybookMySqlExtDAO();

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

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



$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingEX = new ProgramsettingsMySqlExtDAO();

$smarty->assign('today', date('Y-m-d'));

$ManufacuresettingData = $simplesettingDao->load(1);
$smarty->assign("ManufacuresettingData", $ManufacuresettingData);


$smarty->assign('allowedit', 1);
//check and use the condition that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");

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

    $allTaskOrders = $taskorderExt->queryAllWithProductName();
    $smarty->assign('allTaskOrders', $allTaskOrders);

    $allStore = $myStoreRecord->queryByConditions(0);
    $smarty->assign('allStore', $allStore);

    $orderId = 1;
    $allExecution = $productionExecutionDao->queryAllOrderBy('id');
    if (count($allExecution) >= 1) {
        $orderId = $allExecution[count($allExecution) - 1]->id + 1;
    }
    $smarty->assign('orderId', $orderId);

    $smarty->assign("customProductionExecution", 1);
    //$smarty->assign("rows", $rows);
    $smarty->display("productionExecutionView/add.html");
} elseif ($do == "add") {
    include_once("../public/authentication.php");

    try {
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        echo $e;
        header("location:?do=error");
    }
} elseif ($do == "executeAdd") {
    include_once("../public/authentication.php");

    $flag = executeAdd();
    if ($flag == 1) {
        header("location:?do=sucess");
    } else {
        header("location:?do=error");
    }
} elseif ($do == "edit") {

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

    $allTaskOrders = $taskorderExt->queryAllWithProductName();
    $smarty->assign('allTaskOrders', $allTaskOrders);

    $allStore = $myStoreRecord->queryByConditions(0);
    $smarty->assign('allStore', $allStore);

    $id = $_GET["id"];

    $productionExecutionData = $productionExecutionDao->load($id);
    if (!$productionExecutionData) {
        header('location:productionExecutionController.php?do=show');
    }
    $smarty->assign('productionExecutionData', $productionExecutionData);

    $product = $productDAO->load($productionExecutionData->productid);
    $productCat = $productCatDAO->load($product->productCatId);

    $smarty->assign("oldfinalproduct", $productionExecutionData->productid);
    $smarty->assign("oldfinalproductname", $product->productName . '/ ' . $productCat->productCatName);

    $productionExecutionProductsData = $productionExecutionProductExt->queryAllProductsByExecutionId($id);
    foreach ($productionExecutionProductsData as $p) {
        ##
        //$p->productName = $p->productName . '/ ' . $p->productCatName;
        if (!empty($p->sizeName) && !empty($p->colorName)) {
            $p->productid = "hasSizeColor" . $p->productid . "-" . $p->sizeid . "-" . $p->colorid;
            $p->productName .= '/ ' . $p->sizeName . '/ ' . $p->colorName;
        }
    }
    $smarty->assign('productionExecutionProductsData', $productionExecutionProductsData);

    $productionExecutionOutputData = $productionExecutionOutputExt->queryAllProductsByExecutionId($id);
    foreach ($productionExecutionOutputData as $p) {
        ##
        //$p->productName = $p->productName . '/ ' . $p->productCatName;
        if (!empty($p->sizeName) && !empty($p->colorName)) {
            $p->productid = "hasSizeColor" . $p->productid . "-" . $p->sizeid . "-" . $p->colorid;
            $p->productName .= '/ ' . $p->sizeName . '/ ' . $p->colorName;
        }
    }
    $smarty->assign('productionExecutionOutputData', $productionExecutionOutputData);

    $productionExecutionWasteData = $productionExecutionWasteExt->queryAllProductsByExecutionId($id);
    foreach ($productionExecutionWasteData as $p) {
        ##
        //$p->productName = $p->productName . '/ ' . $p->productCatName;
        if (!empty($p->sizeName) && !empty($p->colorName)) {
            $p->productid = "hasSizeColor" . $p->productid . "-" . $p->sizeid . "-" . $p->colorid;
            $p->productName .= '/ ' . $p->sizeName . '/ ' . $p->colorName;
        }
    }
    $smarty->assign('productionExecutionWasteData', $productionExecutionWasteData);

    $smarty->assign("customProductionExecution", 1);
    $smarty->assign("customProductionExecutionEdit", 1);

    $smarty->display("productionExecutionView/edit.html");
    //print_r($Productionrateproduct->conditions);
} elseif ($do == "details") {

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

    $allTaskOrders = $taskorderExt->queryAllWithProductName();
    $smarty->assign('allTaskOrders', $allTaskOrders);

    $allStore = $myStoreRecord->queryByConditions(0);
    $smarty->assign('allStore', $allStore);

    $id = $_GET["id"];

    $productionExecutionData = $productionExecutionDao->load($id);
    if (!$productionExecutionData) {
        header('location:productionExecutionController.php?do=show');
    }
    $smarty->assign('productionExecutionData', $productionExecutionData);

    $product = $productDAO->load($productionExecutionData->productid);
    $productCat = $productCatDAO->load($product->productCatId);

    $smarty->assign("oldfinalproduct", $productionExecutionData->productid);
    $smarty->assign("oldfinalproductname", $product->productName . '/ ' . $productCat->productCatName);

    $productionExecutionProductsData = $productionExecutionProductExt->queryAllProductsByExecutionId($id);
    foreach ($productionExecutionProductsData as $p) {
        ##
        //$p->productName = $p->productName . '/ ' . $p->productCatName;
        if (!empty($p->sizeName) && !empty($p->colorName)) {
            $p->productid = "hasSizeColor" . $p->productid . "-" . $p->sizeid . "-" . $p->colorid;
            $p->productName .= '/ ' . $p->sizeName . '/ ' . $p->colorName;
        }
    }
    $smarty->assign('productionExecutionProductsData', $productionExecutionProductsData);

    $productionExecutionOutputData = $productionExecutionOutputExt->queryAllProductsByExecutionId($id);
    foreach ($productionExecutionOutputData as $p) {
        ##
        //$p->productName = $p->productName . '/ ' . $p->productCatName;
        if (!empty($p->sizeName) && !empty($p->colorName)) {
            $p->productid = "hasSizeColor" . $p->productid . "-" . $p->sizeid . "-" . $p->colorid;
            $p->productName .= '/ ' . $p->sizeName . '/ ' . $p->colorName;
        }
    }
    $smarty->assign('productionExecutionOutputData', $productionExecutionOutputData);

    $productionExecutionWasteData = $productionExecutionWasteExt->queryAllProductsByExecutionId($id);
    foreach ($productionExecutionWasteData as $p) {
        ##
        //$p->productName = $p->productName . '/ ' . $p->productCatName;
        if (!empty($p->sizeName) && !empty($p->colorName)) {
            $p->productid = "hasSizeColor" . $p->productid . "-" . $p->sizeid . "-" . $p->colorid;
            $p->productName .= '/ ' . $p->sizeName . '/ ' . $p->colorName;
        }
    }
    $smarty->assign('productionExecutionWasteData', $productionExecutionWasteData);

    $smarty->assign("customProductionExecution", 1);
    $smarty->assign("customProductionExecutionEdit", 1);

    $smarty->display("productionExecutionView/details.html");
} elseif ($do == "editprint") {

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

    $allTaskOrders = $taskorderExt->queryAllWithProductName();
    $smarty->assign('allTaskOrders', $allTaskOrders);

    $allStore = $myStoreRecord->queryByConditions(0);
    $smarty->assign('allStore', $allStore);

    $id = $_GET["id"];

    $productionExecutionData = $productionExecutionDao->load($id);
    if (!$productionExecutionData) {
        header('location:productionExecutionController.php?do=show');
    }
    $smarty->assign('productionExecutionData', $productionExecutionData);

    $product = $productDAO->load($productionExecutionData->productid);
    $productCat = $productCatDAO->load($product->productCatId);

    $smarty->assign("oldfinalproduct", $productionExecutionData->productid);
    $smarty->assign("oldfinalproductname", $product->productName . '/ ' . $productCat->productCatName);

    $productionExecutionProductsData = $productionExecutionProductExt->queryAllProductsByExecutionId($id);
    $smarty->assign('productionExecutionProductsData', $productionExecutionProductsData);

    $productionExecutionOutputData = $productionExecutionOutputExt->queryAllProductsByExecutionId($id);
    $smarty->assign('productionExecutionOutputData', $productionExecutionOutputData);

    $productionExecutionWasteData = $productionExecutionWasteExt->queryAllProductsByExecutionId($id);
    $smarty->assign('productionExecutionWasteData', $productionExecutionWasteData);

    $smarty->assign("customProductionExecution", 1);
    $smarty->assign("customProductionExecutionEdit", 1);

    $smarty->display("productionExecutionView/details.html");
} elseif ($do == "update") {
    try {
        update();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
} elseif ($do == "executeUpdate") {
    try {
        executeUpdate();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //        echo $e;
        header("location:?do=error");
    }
} elseif ($do == "execute") {
    try {
        execute();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
} elseif ($do == "show") {

    $from = filter_input(INPUT_POST, 'from');
    $to = filter_input(INPUT_POST, 'to');
    $id = filter_input(INPUT_POST, 'orderId');

    $query = "";

    if ($from)
        $query .= " and orderdate >= '$from'";

    if ($to)
        $query .= " and orderdate <= '$to'";

    if ($id && $id != -1)
        $query .= " and id = $id";

    $allOrders = $productionExecutionExt->queryAllExt($query);
    $smarty->assign("allOrders", $allOrders);

    $allIds = $productionExecutionDao->queryAll();
    $smarty->assign("allIds", $allIds);

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

    $smarty->display("productionExecutionView/show.html");
}
/* elseif ($do == "stop") {
  try {

  stop_active();
  header("location:?do=sucess");
  } catch (Exception $e) {
  header("location:?do=error");
  }
  } */ elseif ($do == "delete") {

    try {

        delete();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //        echo $e;
        header("location:?do=error");
    }
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}
//here the global templates
//$smarty->assign("productScripts",1);

$smarty->display("footer.html");

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

//add
function add() {
    global $productionExecution;
    global $productionExecutionDao;

    global $productionExecutionProduct;
    global $productionExecutionProductDao;

    global $productionExecutionOutput;
    global $productionExecutionOutputDao;

    global $productionExecutionWaste;
    global $productionExecutionWasteDao;

    $outItr = filter_input(INPUT_POST, 'countItr');
    $piecesNum = 0;
    for ($i = 1; $i <= $outItr; $i++) {
        if (filter_input(INPUT_POST, 'product' . $i)) {
            $piecesNum += filter_input(INPUT_POST, 'amount' . $i);
        }
    }

    $actualTotalCost = filter_input(INPUT_POST, 'actlTotalCost');
    $rentCost = filter_input(INPUT_POST, 'rentCost');
    $otherCost = filter_input(INPUT_POST, 'otherCost');

    $productId = filter_input(INPUT_POST, 'finalProductId');
    $sizeId = 0;
    $colorId = 0;
    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
        $sizeId = $productIdComplex[1];
        $colorId = $productIdComplex[2];
    }

    // $allExecution = $productionExecutionDao->queryByOrderId($orderId);
    // if (count($allExecution) >= 1) {
    $allExecution = $productionExecutionDao->queryAllOrderBy('id');
    if (count($allExecution) >= 1) {
        $orderId = $allExecution[count($allExecution) - 1]->id + 1;
    }
    // }

    $productionExecution->title = filter_input(INPUT_POST, 'title');
    $productionExecution->orderId = $orderId;
    $productionExecution->orderdate = filter_input(INPUT_POST, 'orderdate');
    $productionExecution->taskid = filter_input(INPUT_POST, 'orderId');
    $productionExecution->productid = $productId;
    $productionExecution->num = filter_input(INPUT_POST, 'proNum');
    $productionExecution->outstoreid = filter_input(INPUT_POST, 'storeMain');
    $productionExecution->wastestoreid = filter_input(INPUT_POST, 'storeWasteMain');
    $productionExecution->rentcost = $rentCost;
    $productionExecution->othercost = $otherCost;
    $productionExecution->executioncost = $actualTotalCost + ($rentCost * $piecesNum) + ($otherCost * $piecesNum);
    $productionExecution->sysdate = date('Y-m-d H:i:s');
    $productionExecution->executed = 0;
    $productionExecution->comment = filter_input(INPUT_POST, 'comment');
    $productionExecution->sizeid = $sizeId;
    $productionExecution->colorid = $colorId;

    $id = $productionExecutionDao->insert($productionExecution);

    $productItr = filter_input(INPUT_POST, 'rowitr');
    $totalActualCost = 0;
    for ($i = 1; $i <= $productItr; $i++) {
        if (filter_input(INPUT_POST, 'pro' . $i)) {
            $productId = filter_input(INPUT_POST, 'pro' . $i);
            $sizeId = 0;
            $colorId = 0;
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }

            $productionExecutionProduct->executionid = $id;
            $productionExecutionProduct->productid = $productId;
            $productionExecutionProduct->sizeid = $sizeId;
            $productionExecutionProduct->colorid = $colorId;
            $productionExecutionProduct->unitid = filter_input(INPUT_POST, 'unit' . $i);
            $productionExecutionProduct->quantity = filter_input(INPUT_POST, 'quantity' . $i);
            $productionExecutionProduct->actualquantity = filter_input(INPUT_POST, 'actual' . $i);
            $productionExecutionProduct->cost = filter_input(INPUT_POST, 'cost' . $i);
            $productionExecutionProduct->actualcost = filter_input(INPUT_POST, 'actualCost' . $i);
            $productionExecutionProductDao->insert($productionExecutionProduct);

            $totalActualCost += filter_input(INPUT_POST, 'actualCost' . $i);
        }
    }

    ////////////output/////////////////
    $totalNum = 0;
    for ($i = 1; $i <= $outItr; $i++) {
        if (filter_input(INPUT_POST, 'product' . $i)) {
            $totalNum += filter_input(INPUT_POST, 'amount' . $i);
        }
    }
    for ($i = 1; $i <= $outItr; $i++) {
        if (filter_input(INPUT_POST, 'product' . $i)) {
            $productId = filter_input(INPUT_POST, 'product' . $i);
            $sizeId = 0;
            $colorId = 0;
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }

            $productionExecutionOutput->exeutionid = $id;
            $productionExecutionOutput->productid = $productId;
            $productionExecutionOutput->sizeid = $sizeId;
            $productionExecutionOutput->colorid = $colorId;
            $productionExecutionOutput->allprice = filter_input(INPUT_POST, 'allPrice' . $i);
            $productionExecutionOutput->halfprice = filter_input(INPUT_POST, 'halfPrice' . $i);
            $productionExecutionOutput->unitprice = filter_input(INPUT_POST, 'unitPrice' . $i);
            $productionExecutionOutput->num = filter_input(INPUT_POST, 'amount' . $i);
            $productionExecutionOutput->cost = $totalActualCost / $totalNum; //filter_input(INPUT_POST, 'amount' . $i);
            $productionExecutionOutput->storeid = filter_input(INPUT_POST, 'outStore' . $i);

            $oid = $productionExecutionOutputDao->insert($productionExecutionOutput);
        }
    }

    $wasteItr = filter_input(INPUT_POST, 'wasteItr');
    for ($i = 1; $i <= $wasteItr; $i++) {
        if (filter_input(INPUT_POST, 'wasteproduct' . $i)) {
            $productId = filter_input(INPUT_POST, 'wasteproduct' . $i);
            $sizeId = 0;
            $colorId = 0;
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }
            $productionExecutionWaste->executionid = $id;
            $productionExecutionWaste->productid = $productId;
            $productionExecutionWaste->sizeid = $sizeId;
            $productionExecutionWaste->colorid = $colorId;
            $productionExecutionWaste->allprice = filter_input(INPUT_POST, 'wasteAllPrice' . $i);
            $productionExecutionWaste->halfprice = filter_input(INPUT_POST, 'wasteHalfPrice' . $i);
            $productionExecutionWaste->unitprice = filter_input(INPUT_POST, 'wasteUnitPrice' . $i);
            $productionExecutionWaste->num = filter_input(INPUT_POST, 'wasteAmount' . $i);
            $productionExecutionWaste->storeid = filter_input(INPUT_POST, 'wasteStore' . $i);
            $productionExecutionWasteDao->insert($productionExecutionWaste);
        }
    }
}

//executeAdd
function executeAdd() {
    global $productionExecution;
    global $productionExecutionDao;

    global $productionExecutionProduct;
    global $productionExecutionProductDao;

    global $productionExecutionOutput;
    global $productionExecutionOutputDao;

    global $productionExecutionWaste;
    global $productionExecutionWasteDao;

    global $productDAO;
    global $product;
    global $ManufacuresettingData;
    global $sizeColorStoreDetailEX;



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

        $outItr = filter_input(INPUT_POST, 'countItr');
        $piecesNum = 0;
        for ($i = 1; $i <= $outItr; $i++) {
            if (filter_input(INPUT_POST, 'product' . $i)) {
                $piecesNum += filter_input(INPUT_POST, 'amount' . $i);
            }
        }

        $actualTotalCost = filter_input(INPUT_POST, 'actlTotalCost');
        $rentCost = filter_input(INPUT_POST, 'rentCost');
        $otherCost = filter_input(INPUT_POST, 'otherCost');

        $productId = filter_input(INPUT_POST, 'finalProductId');
        $sizeId = 0;
        $colorId = 0;
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productId = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
        }

        $orderId = filter_input(INPUT_POST, 'proOrderId');
        $allExecution = $productionExecutionDao->queryByOrderId($orderId);
        if (count($allExecution) >= 1) {
            $allExecution = $productionExecutionDao->queryAllOrderBy('id');
            if (count($allExecution) >= 1) {
                $orderId = $allExecution[count($allExecution) - 1]->id + 1;
            }
        }

        $productionExecution->title = filter_input(INPUT_POST, 'title');
        $productionExecution->orderId = $orderId;
        $productionExecution->orderdate = filter_input(INPUT_POST, 'orderdate');
        $productionExecution->taskid = filter_input(INPUT_POST, 'orderId');
        $productionExecution->productid = $productId;
        $productionExecution->num = filter_input(INPUT_POST, 'proNum');
        $productionExecution->outstoreid = filter_input(INPUT_POST, 'storeMain');
        $productionExecution->wastestoreid = filter_input(INPUT_POST, 'storeWasteMain');
        $productionExecution->rentcost = $rentCost;
        $productionExecution->othercost = $otherCost;
        $productionExecution->executioncost = $actualTotalCost + ($rentCost * $piecesNum) + ($otherCost * $piecesNum);
        $productionExecution->sysdate = date('Y-m-d H:i:s');
        $productionExecution->executed = 1;
        $productionExecution->sizeid = $sizeId;
        $productionExecution->colorid = $colorId;

        $id = $productionExecutionDao->insert($productionExecution);

        $productItr = filter_input(INPUT_POST, 'rowitr');
        $totalActualCost = 0;
        for ($i = 1; $i <= $productItr; $i++) {
            $productId = filter_input(INPUT_POST, 'pro' . $i);
            $sizeId = 0;
            $colorId = 0;
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }
            if ($productId) {
                $quantity = filter_input(INPUT_POST, 'actual' . $i);

                $proData = $productDAO->load($productId);
                $comingData = getBuyPriceFromAndHandleBuyPricesHistoryBook($ManufacuresettingData->storeid, $productId, 0, 0, $proData->productBuyPrice, $quantity);
                $theBuyPrice = $comingData[0];
                $buyPricesHistoryBookIdQuantity = $comingData[1];

                $productionExecutionProduct->executionid = $id;
                $productionExecutionProduct->productid = $productId;
                $productionExecutionProduct->sizeid = $sizeId;
                $productionExecutionProduct->colorid = $colorId;
                $productionExecutionProduct->unitid = filter_input(INPUT_POST, 'unit' . $i);
                $productionExecutionProduct->quantity = filter_input(INPUT_POST, 'quantity' . $i);
                $productionExecutionProduct->actualquantity = $quantity;
                $productionExecutionProduct->cost = filter_input(INPUT_POST, 'cost' . $i); //$theBuyPrice * $quantity;
                $productionExecutionProduct->actualcost = $theBuyPrice * $quantity; //filter_input(INPUT_POST, 'actualCost' . $i);
                $productionExecutionProduct->buyPricesHistoryBookIdQuantity = $buyPricesHistoryBookIdQuantity; //filter_input(INPUT_POST, 'actualCost' . $i);

                $productionExecutionProductDao->insert($productionExecutionProduct);

                decrease($productId, $sizeId, $colorId, $quantity, $id);
                $totalActualCost += $theBuyPrice * $quantity; //filter_input(INPUT_POST, 'actualCost' . $i);
            }
        }

        //executioncost after getting prices from buypricehistorybook table
        $productionExecution->executioncost = $totalActualCost + ($rentCost * $piecesNum) + ($otherCost * $piecesNum);
        $productionExecutionDao->update($productionExecution);

        ////////////output/////////////////
        $totalNum = 0;
        for ($i = 1; $i <= $outItr; $i++) {
            if (filter_input(INPUT_POST, 'product' . $i)) {
                $totalNum += filter_input(INPUT_POST, 'amount' . $i);
            }
        }
        for ($i = 1; $i <= $outItr; $i++) {
            $productId = $outProId = filter_input(INPUT_POST, 'product' . $i);
            $sizeId = 0;
            $colorId = 0;
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $outProId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }
            if ($outProId) {
                $sellAllPrice = filter_input(INPUT_POST, 'allPrice' . $i);
                $sellHalfPrice = filter_input(INPUT_POST, 'halfPrice' . $i);
                $sellUnitPrice = filter_input(INPUT_POST, 'unitPrice' . $i);

                $outnum = filter_input(INPUT_POST, 'amount' . $i);
                $outStore = filter_input(INPUT_POST, 'outStore' . $i);
                $cost = $totalActualCost / $totalNum; //filter_input(INPUT_POST, 'amount' . $i);

                $productionExecutionOutput->exeutionid = $id;
                $productionExecutionOutput->productid = $outProId;
                $productionExecutionOutput->sizeid = $sizeId;
                $productionExecutionOutput->colorid = $colorId;
                $productionExecutionOutput->allprice = $sellAllPrice;
                $productionExecutionOutput->halfprice = $sellHalfPrice;
                $productionExecutionOutput->unitprice = $sellUnitPrice;
                $productionExecutionOutput->num = $outnum;
                $productionExecutionOutput->cost = $cost;
                $productionExecutionOutput->storeid = $outStore;

                $oid = $productionExecutionOutputDao->insert($productionExecutionOutput);

                $rowData = $productDAO->load($outProId);

                $newMeanBuyPrice = calcMeanBuyPrice($outProId, $outnum, $cost, $rowData->meanbuyprice);

                increaseBuyPricesHistoryBookBuyQuantity(date('Y-m-d'), $outStore, $outProId, 0, 0, $newMeanBuyPrice, $outnum);

                ##
                $product = $rowData;
                $product->productId = $outProId;
                $product->productBuyPrice = $cost;
                $product->productSellAllPrice = $sellAllPrice;
                $product->productSellHalfPrice = $sellHalfPrice;
                $product->productSellUnitPrice = $sellUnitPrice;
                $product->lastbuyprice = $cost;
                $product->lastbuyprice_withDiscount = $cost;
                $product->meanbuyprice = $newMeanBuyPrice;
                $product->meanbuyprice_withDiscount = $newMeanBuyPrice;
                $product->productbuypricereal = $cost;


                $productDAO->update($product);

                $sizeColorStoreDetailEX->updatebuyprice($cost, $outProId, $sizeId, $colorId, $outStore);
                increase($outProId, $sizeId, $colorId, $outnum, $id, $outStore);
            }
        }

        $wasteItr = filter_input(INPUT_POST, 'wasteItr');
        for ($i = 1; $i <= $wasteItr; $i++) {
            $productId = $wasteProId = filter_input(INPUT_POST, 'wasteproduct' . $i);
            $sizeId = 0;
            $colorId = 0;
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $wasteProId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }
            if ($wasteProId) {
                $wastenum = filter_input(INPUT_POST, 'wasteAmount' . $i);
                $awsteStore = filter_input(INPUT_POST, 'wasteStore' . $i);
                $productionExecutionWaste->executionid = $id;
                $productionExecutionWaste->productid = $productId;
                $productionExecutionWaste->sizeid = $sizeId;
                $productionExecutionWaste->colorid = $colorId;
                $productionExecutionWaste->allprice = filter_input(INPUT_POST, 'wasteAllPrice' . $i);
                $productionExecutionWaste->halfprice = filter_input(INPUT_POST, 'wasteHalfPrice' . $i);
                $productionExecutionWaste->unitprice = filter_input(INPUT_POST, 'wasteUnitPrice' . $i);
                $productionExecutionWaste->num = $wastenum;
                $productionExecutionWaste->storeid = $awsteStore;
                $productionExecutionWasteDao->insert($productionExecutionWaste);

                $rowData = $productDAO->load($wasteProId);
                increaseBuyPricesHistoryBookBuyQuantity(date('Y-m-d'), $awsteStore, $wasteProId, 0, 0, $rowData->meanbuyprice, $wastenum);

                increase($wasteProId, $sizeId, $colorId, $wastenum, $id, $awsteStore);
            }
        }

        $mytransactions->commit();
        doInventoryDailyEntry($productionExecution);
        return 1;
    } catch (Exception $ex) {
        //echo $ex;
        $mytransactions->rollback();
        return 0;
    }
}

//update
function update() {
    global $productionExecution;
    global $productionExecutionDao;
    global $productionExecutionProduct;
    global $productionExecutionProductDao;
    global $productionExecutionOutput;
    global $productionExecutionOutputDao;
    global $productionExecutionWaste;
    global $productionExecutionWasteDao;

    $id = filter_input(INPUT_POST, 'executionId');

    $productionExecution = $productionExecutionDao->load($id);

    $outItr = filter_input(INPUT_POST, 'outItr'); //countItr
    $piecesNum = 0;
    for ($i = 1; $i <= $outItr; $i++) {
        if (filter_input(INPUT_POST, 'product' . $i)) {
            $piecesNum += filter_input(INPUT_POST, 'amount' . $i);
        }
    }

    $actualTotalCost = filter_input(INPUT_POST, 'actlTotalCost');
    $rentCost = filter_input(INPUT_POST, 'rentCost');
    $otherCost = filter_input(INPUT_POST, 'otherCost');

    $productId = filter_input(INPUT_POST, 'finalProductId');
    $sizeId = 0;
    $colorId = 0;
    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
        $sizeId = $productIdComplex[1];
        $colorId = $productIdComplex[2];
    }

    $productionExecution->title = filter_input(INPUT_POST, 'title');
    $productionExecution->orderId = filter_input(INPUT_POST, 'proOrderId');
    $productionExecution->orderdate = filter_input(INPUT_POST, 'orderdate');
    $productionExecution->taskid = filter_input(INPUT_POST, 'orderId');
    $productionExecution->productid = $productId;
    $productionExecution->num = filter_input(INPUT_POST, 'proNum');
    $productionExecution->outstoreid = filter_input(INPUT_POST, 'storeMain');
    $productionExecution->wastestoreid = filter_input(INPUT_POST, 'storeWasteMain');
    $productionExecution->rentcost = $rentCost;
    $productionExecution->othercost = $otherCost;
    $productionExecution->executioncost = $actualTotalCost + ($rentCost * $piecesNum) + ($otherCost * $piecesNum);
    $productionExecution->executed = 0;
    $productionExecution->comment = filter_input(INPUT_POST, 'comment');
    $productionExecution->sizeid = $sizeId;
    $productionExecution->colorid = $colorId;
    $productionExecution->id = $id;
    $productionExecutionDao->update($productionExecution);

    $productionExecutionOutputDao->deleteByExeutionid($id);
    $productionExecutionProductDao->deleteByExecutionid($id);
    $productionExecutionWasteDao->deleteByExecutionid($id);

    $productItr = filter_input(INPUT_POST, 'rowitr');
    $totalActualCost = 0;
    for ($i = 1; $i <= $productItr; $i++) {
        if (filter_input(INPUT_POST, 'pro' . $i)) {
            $productId = filter_input(INPUT_POST, 'pro' . $i);
            $sizeId = 0;
            $colorId = 0;
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }
            $productionExecutionProduct->executionid = $id;
            $productionExecutionProduct->productid = $productId;
            $productionExecutionProduct->sizeid = $sizeId;
            $productionExecutionProduct->colorid = $colorId;
            $productionExecutionProduct->unitid = filter_input(INPUT_POST, 'unit' . $i);
            $productionExecutionProduct->quantity = filter_input(INPUT_POST, 'quantity' . $i);
            $productionExecutionProduct->actualquantity = filter_input(INPUT_POST, 'actual' . $i);
            $productionExecutionProduct->cost = filter_input(INPUT_POST, 'cost' . $i);
            $productionExecutionProduct->actualcost = filter_input(INPUT_POST, 'actualCost' . $i);
            $productionExecutionProductDao->insert($productionExecutionProduct);

            $totalActualCost += filter_input(INPUT_POST, 'actualCost' . $i);
        }
    }

    ////////////output/////////////////
    $totalNum = 0;
    for ($i = 1; $i <= $outItr; $i++) {
        if (filter_input(INPUT_POST, 'product' . $i)) {
            $totalNum += filter_input(INPUT_POST, 'amount' . $i);
        }
    }

    for ($i = 1; $i <= $outItr; $i++) {
        if (filter_input(INPUT_POST, 'product' . $i)) {
            $productId = filter_input(INPUT_POST, 'product' . $i);
            $sizeId = 0;
            $colorId = 0;
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }
            $productionExecutionOutput->exeutionid = $id;
            $productionExecutionOutput->productid = $productId;
            $productionExecutionOutput->sizeid = $sizeId;
            $productionExecutionOutput->colorid = $colorId;
            $productionExecutionOutput->allprice = filter_input(INPUT_POST, 'allPrice' . $i);
            $productionExecutionOutput->halfprice = filter_input(INPUT_POST, 'halfPrice' . $i);
            $productionExecutionOutput->unitprice = filter_input(INPUT_POST, 'unitPrice' . $i);
            $productionExecutionOutput->num = filter_input(INPUT_POST, 'amount' . $i);
            $productionExecutionOutput->cost = $totalActualCost / $totalNum; // filter_input(INPUT_POST, 'amount' . $i);
            $productionExecutionOutput->storeid = filter_input(INPUT_POST, 'outStore' . $i);

            $oid = $productionExecutionOutputDao->insert($productionExecutionOutput);
        }
    }

    $wasteItr = filter_input(INPUT_POST, 'wasteItr');
    for ($i = 1; $i <= $wasteItr; $i++) {
        if (filter_input(INPUT_POST, 'wasteproduct' . $i)) {
            $productId = filter_input(INPUT_POST, 'wasteproduct' . $i);
            $sizeId = 0;
            $colorId = 0;
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }

            $productionExecutionWaste->executionid = $id;
            $productionExecutionWaste->productid = $productId;
            $productionExecutionWaste->sizeid = $sizeId;
            $productionExecutionWaste->colorid = $colorId;
            $productionExecutionWaste->allprice = filter_input(INPUT_POST, 'wasteAllPrice' . $i);
            $productionExecutionWaste->halfprice = filter_input(INPUT_POST, 'wasteHalfPrice' . $i);
            $productionExecutionWaste->unitprice = filter_input(INPUT_POST, 'wasteUnitPrice' . $i);
            $productionExecutionWaste->num = filter_input(INPUT_POST, 'wasteAmount' . $i);
            $productionExecutionWaste->storeid = filter_input(INPUT_POST, 'wasteStore' . $i);
            $productionExecutionWasteDao->insert($productionExecutionWaste);
        }
    }
}

//execute
function execute() {
    global $productionExecution;
    global $productionExecutionDao;
    global $productionExecutionProduct;
    global $productionExecutionProductDao;
    global $productionExecutionOutput;
    global $productionExecutionOutputDao;
    global $productionExecutionWaste;
    global $productionExecutionWasteDao;
    global $productDAO;
    global $product;
    global $ManufacuresettingData;
    global $sizeColorStoreDetailEX;


    //Transaction
    $mytransactions = new Transaction();
    try {
        $id = filter_input(INPUT_GET, 'id');

        $productionExecution = $productionExecutionDao->load($id);
        $oldExecuted = $productionExecution->executed;
        if ($oldExecuted == 0) {
            $oldExecutionProducts = $productionExecutionProductDao->queryByExecutionid($id);
            $oldExecutionOutput = $productionExecutionOutputDao->queryByExeutionid($id);
            $oldExecutionWaste = $productionExecutionWasteDao->queryByExecutionid($id);

            $totalActualCost = 0;
            foreach ($oldExecutionProducts as $Expro) {
                $proData = $productDAO->load($Expro->productid);
                $comingData = getBuyPriceFromAndHandleBuyPricesHistoryBook($ManufacuresettingData->storeid, $Expro->productid, 0, 0, $proData->productBuyPrice, $Expro->actualquantity);
                $theBuyPrice = $comingData[0];
                $buyPricesHistoryBookIdQuantity = $comingData[1];

                $Expro->cost = $theBuyPrice * $Expro->actualquantity;
                $Expro->actualcost = $theBuyPrice * $Expro->actualquantity;
                $Expro->buyPricesHistoryBookIdQuantity = $buyPricesHistoryBookIdQuantity;

                $productionExecutionProductDao->update($Expro);



                decrease($Expro->productid, $Expro->sizeid, $Expro->colorid, $Expro->actualquantity, $id, 0, '(معدلة)');
                $totalActualCost += $theBuyPrice * $Expro->actualquantity;
            }

            foreach ($oldExecutionOutput as $ExOut) {
                $cost = $totalActualCost / $ExOut->num;
                $ExOut->cost = $cost;
                $productionExecutionOutputDao->update($ExOut);


                $rowData = $productDAO->load($ExOut->productid);

                $newMeanBuyPrice = calcMeanBuyPrice($ExOut->productid, $ExOut->num, $ExOut->cost, $rowData->meanbuyprice);

                increaseBuyPricesHistoryBookBuyQuantity(date('Y-m-d'), $ExOut->storeid, $ExOut->productid, 0, 0, $newMeanBuyPrice, $ExOut->num);
                $product = $rowData;
                $product->productId = $ExOut->productid;
                $product->productBuyPrice = $ExOut->cost;
                $product->productSellAllPrice = $ExOut->allprice;
                $product->productSellHalfPrice = $ExOut->halfprice;
                $product->productSellUnitPrice = $ExOut->unitprice;
                $product->lastbuyprice = $ExOut->cost;
                $product->lastbuyprice_withDiscount = $ExOut->cost;
                $product->meanbuyprice = $newMeanBuyPrice;
                $product->meanbuyprice_withDiscount = $newMeanBuyPrice;
                $product->productbuypricereal = $ExOut->cost;

                $productDAO->update($product);
                $sizeColorStoreDetailEX->updatebuyprice($ExOut->cost, $ExOut->productid, $ExOut->sizeid, $ExOut->colorid, $ExOut->storeid);

                increase($ExOut->productid, $ExOut->sizeid, $ExOut->colorid, $ExOut->num, $id, $ExOut->storeid, '(معدلة)');
            }

            foreach ($oldExecutionWaste as $ExWaste) {
                $rowData = $productDAO->load($ExWaste->productid);
                increaseBuyPricesHistoryBookBuyQuantity(date('Y-m-d'), $ExWaste->storeid, $ExWaste->productid, 0, 0, $rowData->meanbuyprice, $ExWaste->num);

                increase($ExWaste->productid, $ExWaste->sizeid, $ExWaste->colorid, $ExWaste->num, $id, $ExWaste->storeid, '(معدلة)');
            }

            $productionExecution->executed = 1;
            $productionExecution->id = $id;

            //executioncost after getting prices from buypricehistorybook table
            $piecesNum = count($oldExecutionOutput);
            $productionExecution->executioncost = $totalActualCost + ($productionExecution->rentcost * $piecesNum) + ($productionExecution->othercost * $piecesNum);
            $productionExecution->sysdate = date('Y-m-d H:i:s'); //needed for buyprice history book
            $productionExecutionDao->update($productionExecution);
        }
        $mytransactions->commit();

        doInventoryDailyEntry($productionExecution);
        return 1;
    } catch (Exception $ex) {
        $mytransactions->rollback();
        return 0;
    }
}

//executeUpdate
function executeUpdate() {
    global $productionExecution;
    global $productionExecutionDao;
    global $productionExecutionProduct;
    global $productionExecutionProductDao;
    global $productionExecutionOutput;
    global $productionExecutionOutputDao;
    global $productionExecutionWaste;
    global $productionExecutionWasteDao;
    global $productDAO;
    global $product;
    global $myStoredetailEx;

    global $sizeColorStoreDetailEX;
    global $ManufacuresettingData;



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


        $id = filter_input(INPUT_POST, 'executionId');

        $productionExecution = $productionExecutionDao->load($id);
        $oldExecuted = $productionExecution->executed;
        $oldExecutionDate = explode(" ", $productionExecution->sysdate)[0];
        $oldOutStoreId = $productionExecution->outstoreid;
        $oldWasteStoreId = $productionExecution->wastestoreid;

        $outItr = filter_input(INPUT_POST, 'outItr'); //countItr
        $piecesNum = 0;
        for ($i = 1; $i <= $outItr; $i++) {
            if (filter_input(INPUT_POST, 'product' . $i)) {
                $piecesNum += filter_input(INPUT_POST, 'amount' . $i);
            }
        }

        $actualTotalCost = filter_input(INPUT_POST, 'actlTotalCost');
        $rentCost = filter_input(INPUT_POST, 'rentCost');
        $otherCost = filter_input(INPUT_POST, 'otherCost');

        $productId = filter_input(INPUT_POST, 'finalProductId');
        $sizeId = 0;
        $colorId = 0;
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productId = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
        }

        $productionExecution->title = filter_input(INPUT_POST, 'title');
        $productionExecution->orderId = filter_input(INPUT_POST, 'proOrderId');
        $productionExecution->orderdate = filter_input(INPUT_POST, 'orderdate');
        $productionExecution->taskid = filter_input(INPUT_POST, 'orderId');
        $productionExecution->productid = $productId;
        $productionExecution->num = filter_input(INPUT_POST, 'proNum');
        $productionExecution->outstoreid = filter_input(INPUT_POST, 'storeMain');
        $productionExecution->wastestoreid = filter_input(INPUT_POST, 'storeWasteMain');
        $productionExecution->rentcost = $rentCost;
        $productionExecution->othercost = $otherCost;
        $productionExecution->executioncost = $actualTotalCost + ($rentCost * $piecesNum) + ($otherCost * $piecesNum);
        $productionExecution->executed = 1;
        $productionExecution->sysdate = date('Y-m-d H:i:s'); //needed for buyprice history book
        $productionExecution->sizeid = $sizeId;
        $productionExecution->colorid = $colorId;
        $productionExecution->id = $id;
        $productionExecutionDao->update($productionExecution);

        if ($oldExecuted == 1) {
            reverseEntryWithItsID($productionExecution->dailyentryid);
            $oldExecutionProducts = $productionExecutionProductDao->queryByExecutionid($id);
            foreach ($oldExecutionProducts as $Expro) {
                decreaseSellQuantityHandleBuyPricesHistoryBook($Expro->buyPricesHistoryBookIdQuantity);
                increase($Expro->productid, $Expro->sizeid, $Expro->colorid, $Expro->actualquantity, $id, 0, '(معدلة)');
            }

            $oldExecutionOutput = $productionExecutionOutputDao->queryByExeutionid($id);
            $lastMeanPriceArray = array();
            foreach ($oldExecutionOutput as $ExOut) {
                $storeDetailData = $myStoredetailEx->getProductQuantityInAllStores($ExOut->productid);

                $proData = $productDAO->load($ExOut->productid);
                $lastMeanPrice = (($storeDetailData * $proData->meanbuyprice) - ($ExOut->cost * $ExOut->num)) / ($storeDetailData - $ExOut->num);
                $lastMeanPrice = round($lastMeanPrice, 2);
                $item = array(
                    'proid' => $ExOut->productid, 'lastMeanPrice' => $lastMeanPrice
                );
                array_push($lastMeanPriceArray, $item);

                decreaseBuyPricesHistoryBookBuyQuantity($oldExecutionDate, $ExOut->storeid, $ExOut->productid, 0, 0, $lastMeanPrice, $ExOut->num);
                decrease($ExOut->productid, $ExOut->sizeid, $ExOut->colorid, $ExOut->num, $id, $ExOut->storeid, '(معدلة)');
            }

            $oldExecutionWaste = $productionExecutionWasteDao->queryByExecutionid($id);
            foreach ($oldExecutionWaste as $ExWaste) {
                $proData = $productDAO->load($ExWaste->productid);
                decreaseBuyPricesHistoryBookBuyQuantity($oldExecutionDate, $ExWaste->storeid, $ExWaste->productid, 0, 0, $proData->productBuyPrice, $ExWaste->num);
                decrease($ExWaste->productid, $ExWaste->sizeid, $ExWaste->colorid, $ExWaste->num, $id, $ExWaste->storeid, '(معدلة)');
            }
        }

        $productionExecutionOutputDao->deleteByExeutionid($id);
        $productionExecutionProductDao->deleteByExecutionid($id);
        $productionExecutionWasteDao->deleteByExecutionid($id);


        $productItr = filter_input(INPUT_POST, 'rowitr');
        $totalActualCost = 0;
        for ($i = 1; $i <= $productItr; $i++) {
            $productId = filter_input(INPUT_POST, 'pro' . $i);
            $sizeId = 0;
            $colorId = 0;
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }
            if ($productId) {
                $quantity = filter_input(INPUT_POST, 'actual' . $i);

                $proData = $productDAO->load($productId);
                $comingData = getBuyPriceFromAndHandleBuyPricesHistoryBook($ManufacuresettingData->storeid, $productId, 0, 0, $proData->productBuyPrice, $quantity);
                $theBuyPrice = $comingData[0];
                $buyPricesHistoryBookIdQuantity = $comingData[1];

                $productionExecutionProduct->executionid = $id;
                $productionExecutionProduct->productid = $productId;
                $productionExecutionProduct->sizeid = $sizeId;
                $productionExecutionProduct->colorid = $colorId;
                $productionExecutionProduct->unitid = filter_input(INPUT_POST, 'unit' . $i);
                $productionExecutionProduct->quantity = filter_input(INPUT_POST, 'quantity' . $i);
                $productionExecutionProduct->actualquantity = $quantity;
                $productionExecutionProduct->cost = filter_input(INPUT_POST, 'cost' . $i); //$theBuyPrice * $quantity;
                $productionExecutionProduct->actualcost = $theBuyPrice * $quantity; //filter_input(INPUT_POST, 'actualCost' . $i);
                $productionExecutionProduct->buyPricesHistoryBookIdQuantity = $buyPricesHistoryBookIdQuantity; //filter_input(INPUT_POST, 'actualCost' . $i);

                $productionExecutionProductDao->insert($productionExecutionProduct);

                decrease($productId, $sizeId, $colorId, $quantity, $id, 0, '(معدلة)');
                $totalActualCost += $theBuyPrice * $quantity; //filter_input(INPUT_POST, 'actualCost' . $i);
            }
        }

        //executioncost after getting prices from buypricehistorybook table
        $productionExecution->executioncost = $totalActualCost + ($rentCost * $piecesNum) + ($otherCost * $piecesNum);
        $productionExecutionDao->update($productionExecution);

        ////////////output/////////////////
        $totalNum = 0;
        for ($i = 1; $i <= $outItr; $i++) {
            if (filter_input(INPUT_POST, 'product' . $i)) {
                $totalNum += filter_input(INPUT_POST, 'amount' . $i);
            }
        }
        for ($i = 1; $i <= $outItr; $i++) {
            $productId = $outProId = filter_input(INPUT_POST, 'product' . $i);
            $sizeId = 0;
            $colorId = 0;
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $outProId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }
            if ($outProId) {
                $sellAllPrice = filter_input(INPUT_POST, 'allPrice' . $i);
                $sellHalfPrice = filter_input(INPUT_POST, 'halfPrice' . $i);
                $sellUnitPrice = filter_input(INPUT_POST, 'unitPrice' . $i);

                $outnum = filter_input(INPUT_POST, 'amount' . $i);
                $outStore = filter_input(INPUT_POST, 'outStore' . $i);
                $cost = $totalActualCost / $totalNum; //filter_input(INPUT_POST, 'amount' . $i);

                $productionExecutionOutput->exeutionid = $id;
                $productionExecutionOutput->productid = $outProId;
                $productionExecutionOutput->sizeid = $sizeId;
                $productionExecutionOutput->colorid = $colorId;
                $productionExecutionOutput->allprice = $sellAllPrice;
                $productionExecutionOutput->halfprice = $sellHalfPrice;
                $productionExecutionOutput->unitprice = $sellUnitPrice;
                $productionExecutionOutput->num = $outnum;
                $productionExecutionOutput->cost = $cost;
                $productionExecutionOutput->storeid = $outStore;

                $oid = $productionExecutionOutputDao->insert($productionExecutionOutput);

                $rowData = $productDAO->load($outProId);
                $newMeanBuyPrice = calcMeanBuyPrice($outProId, $outnum, $cost, $rowData->meanbuyprice);

                increaseBuyPricesHistoryBookBuyQuantity(date('Y-m-d'), $outStore, $outProId, 0, 0, $newMeanBuyPrice, $outnum);

                foreach ($lastMeanPriceArray as $itm) {
                    if ($itm['proid'] == $outProId) {
                        $lastMeanPrice = $itm['lastMeanPrice'];
                        $newMeanBuyPrice = calcMeanBuyPrice($outProId, $outnum, $cost, $lastMeanPrice);
                    }
                }
                echo 'lastMeanPrice' . $lastMeanPrice . '<br/>';
                echo 'newMeanBuyPriceAfter' . $newMeanBuyPrice . '<br/>';

                $product = $rowData;
                $product->productId = $outProId;
                $product->productBuyPrice = $cost;
                $product->productSellAllPrice = $sellAllPrice;
                $product->productSellHalfPrice = $sellHalfPrice;
                $product->productSellUnitPrice = $sellUnitPrice;
                $product->lastbuyprice = $cost;
                $product->lastbuyprice_withDiscount = $cost;
                $product->meanbuyprice = $newMeanBuyPrice;
                $product->meanbuyprice_withDiscount = $newMeanBuyPrice;
                $product->productbuypricereal = $cost;

                $productDAO->update($product);
                $sizeColorStoreDetailEX->updatebuyprice($cost, $outProId, $sizeId, $colorId, $outStore);

                increase($outProId, $sizeId, $colorId, $outnum, $id, $outStore, '(معدلة)');
            }
        }

        $wasteItr = filter_input(INPUT_POST, 'wasteItr');
        for ($i = 1; $i <= $wasteItr; $i++) {
            $productId = $wasteProId = filter_input(INPUT_POST, 'wasteproduct' . $i);
            $sizeId = 0;
            $colorId = 0;
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $wasteProId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
            }
            if ($wasteProId) {
                $wastenum = filter_input(INPUT_POST, 'wasteAmount' . $i);
                $wasteStore = filter_input(INPUT_POST, 'wasteStore' . $i);
                $productionExecutionWaste->executionid = $id;
                $productionExecutionWaste->productid = $productId;
                $productionExecutionWaste->sizeid = $sizeId;
                $productionExecutionWaste->colorid = $colorId;
                $productionExecutionWaste->allprice = filter_input(INPUT_POST, 'wasteAllPrice' . $i);
                $productionExecutionWaste->halfprice = filter_input(INPUT_POST, 'wasteHalfPrice' . $i);
                $productionExecutionWaste->unitprice = filter_input(INPUT_POST, 'wasteUnitPrice' . $i);
                $productionExecutionWaste->num = $wastenum;
                $productionExecutionWaste->storeid = $wasteStore;
                $productionExecutionWasteDao->insert($productionExecutionWaste);

                $rowData = $productDAO->load($wasteProId);
                increaseBuyPricesHistoryBookBuyQuantity(date('Y-m-d'), $wasteStore, $wasteProId, 0, 0, $rowData->meanbuyprice, $wastenum);

                increase($wasteProId, $sizeId, $colorId, $wastenum, $id, $wasteStore, '(معدلة)');
            }
        }

        $mytransactions->commit();
        doInventoryDailyEntry($productionExecution);
        return 1;
    } catch (Exception $ex) {
        $mytransactions->rollback();
        return 0;
    }
}

//delete
function delete() {
    global $productionExecutionDao;
    global $productionExecutionProductDao;
    global $productionExecutionOutputDao;
    global $productionExecutionWasteDao;
    global $productDAO;
    global $myStoredetailEx;
    global $mySellbilldetailEx;
    global $ManufacuresettingData;



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

        $id = $_GET["id"];

        $oldExecution = $productionExecutionDao->load($id);
        $oldExecutionDate = explode(" ", $oldExecution->sysdate)[0];

        if ($oldExecution->executed == 1) {
            reverseEntryWithItsID($oldExecution->dailyentryid);
            $oldExecutionOutput = $productionExecutionOutputDao->queryByExeutionid($id);
            foreach ($oldExecutionOutput as $ExOut) {
                $storeDetailData = $myStoredetailEx->getProductQuantityInAllStores($ExOut->productid);
                $product = $productDAO->load($ExOut->productid);
                $meanPrice = (($storeDetailData * $product->meanbuyprice) - ($ExOut->cost * $ExOut->num)) / ($storeDetailData - $ExOut->num);
                $meanPrice = round($meanPrice, 2);
                decreaseBuyPricesHistoryBookBuyQuantity($oldExecutionDate, $ExOut->storeid, $ExOut->productid, 0, 0, $meanPrice, $ExOut->num);

                $mysellbildetailes = $mySellbilldetailEx->queryWithProductid($ExOut->productid);
                if (empty($mysellbildetailes)) {
                    $product->productBuyPrice = $meanPrice;
                    $product->lastbuyprice = $meanPrice;
                    $product->lastbuyprice_withDiscount = $meanPrice;
                    $product->productbuypricereal = $meanPrice;
                } else {
                    $product->productBuyPrice = $mysellbildetailes->buyprice;
                    $product->lastbuyprice = $mysellbildetailes->lastbuyprice;
                    $product->lastbuyprice_withDiscount = $mysellbildetailes->lastbuyprice_withDiscount;
                    $product->productbuypricereal = productBuyPrice;
                }

                $product->productId = $ExOut->productid;
                $product->meanbuyprice = $meanPrice;
                $product->meanbuyprice_withDiscount = $meanPrice;

                $productDAO->update($product);
                $sizeColorStoreDetailEX->updatebuyprice($cost, $product->lastbuyprice, $ExOut->sizeid, $ExOut->colorid, $ExOut->storeid);

                decrease($ExOut->productid, $ExOut->sizeid, $ExOut->colorid, $ExOut->num, $id, $ExOut->storeid, '(حذف)');
            }

            $oldExecutionProducts = $productionExecutionProductDao->queryByExecutionid($id);
            foreach ($oldExecutionProducts as $Expro) {
                decreaseSellQuantityHandleBuyPricesHistoryBook($Expro->buyPricesHistoryBookIdQuantity);
                increase($Expro->productid, $Expro->sizeid, $Expro->colorid, $Expro->actualquantity, $id, 0, '(حذف)');
            }

            $oldExecutionWaste = $productionExecutionWasteDao->queryByExecutionid($id);
            foreach ($oldExecutionWaste as $ExWaste) {
                $proData = $productDAO->load($ExWaste->productid);
                decreaseBuyPricesHistoryBookBuyQuantity($oldExecutionDate, $ExWaste->storeid, $ExWaste->productid, 0, 0, $proData->productBuyPrice, $ExWaste->num);
                decrease($ExWaste->productid, $ExWaste->sizeid, $ExWaste->colorid, $ExWaste->num, $id, $ExWaste->storeid, '(حذف)');
            }
        }

        $productionExecutionProductDao->deleteByExecutionid($id);
        $productionExecutionOutputDao->deleteByExeutionid($id);
        $productionExecutionWasteDao->deleteByExecutionid($id);
        $productionExecutionDao->delete($id);


        $mytransactions->commit();
        return 1;
    } catch (Exception $ex) {
        $mytransactions->rollback();
        return 0;
    }
}

function decrease($productId, $sizeId, $colorId, $finalquantity, $sellbillId, $sellbillstoreId = 0, $type = "") {
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;
    if (!$sellbillstoreId || $sellbillstoreId == 0) {
        global $simplesettingDao;
        $simpleSetting = $simplesettingDao->load(1);
        $sellbillstoreId = $simpleSetting->storeid;
    }

    $storedetailData = getStoredetailData($sellbillstoreId, $productId);

    $allStoredetailData = $storedetailData[0];
    $storedetailId = $storedetailData[1];
    $productquantityBefore = $storedetailData[2];
    $productquantityAfter = 0;
    if (count($allStoredetailData) > 0) {

        //update productquantity in storedetail
        $productquantityAfter = decreaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity);

        //insert in storereport
        insertStorereportupdate($productId, $sizeId, $colorId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillId, "إضافة أمر إنتاج " . $type, "productionExecutionController.php", date("Y-m-d H:i:s"));
    } else {
        $specialQuantityAfter = $finalquantity * -1;

        //insert in storedetail tbl
        insertStoredetailupdate($sellbillstoreId, $productId, $specialQuantityAfter, date("Y-m-d H:i:s"));

        //insert in storereport
        insertStorereportupdate($productId, $sizeId, $colorId, $sellbillstoreId, $finalquantity, 0, $specialQuantityAfter, 1, $sellbillId, "إضافة أمر إنتاج", "productionExecutionController.php", date("Y-m-d H:i:s"));
    }
    //now affect product to in size color stores
    if ($sizeId > 0 && $colorId > 0) {
        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
        if (empty($sizeColorStoreDetailId)) {
            //try to copy from existing data in store 1
            $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, 1, $sizeId, $colorId);
            $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

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

            $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
        } else {
            $sizecolorstoredetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);
            $sizecolorstoredetail->userid = $_SESSION['userid'];
            $sizecolorstoredetail->sysdate = date("Y-m-d H:i:s");
            $sizecolorstoredetail->quantity -= $finalquantity;
            $sizeColorStoreDetailDAO->update($sizecolorstoredetail);
        }
    }
}

function increase($productId, $sizeId, $colorId, $finalquantity, $sellbillId, $sellbillstoreId = 0, $type = "") {
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;
    if (!$sellbillstoreId || $sellbillstoreId == 0) {
        global $simplesettingDao;
        $simpleSetting = $simplesettingDao->load(1);
        $sellbillstoreId = $simpleSetting->storeid;
    }

    $storedetailData = getStoredetailData($sellbillstoreId, $productId, 0);

    $allStoredetailData = $storedetailData[0];
    $storedetailId = $storedetailData[1];
    $productquantityBefore = $storedetailData[2];

    if (count($allStoredetailData) > 0) {

        //update productquantity in storedetail
        $productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity);


        //insert in storereport
        insertStorereportupdate($productId, $sizeId, $colorId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $sellbillId, " إضافة أمر إنتاج" . $type, "productionExecutionController.php", date("Y-m-d H:i:s"));
    } else {
        //insert in storedetail tbl
        insertStoredetailupdate($sellbillstoreId, $productId, $finalquantity, date("Y-m-d H:i:s"));


        //insert in storereport
        insertStorereportupdate($productId, $sizeId, $colorId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $sellbillId, "إضافة أمر إنتاج", "productionExecutionController.php", date("Y-m-d H:i:s"));
    }
    //now affect product to in size color stores
    if ($sizeId > 0 && $colorId > 0) {
        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
        if (empty($sizeColorStoreDetailId)) {
            //try to copy from existing data in store 1
            $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, 1, $sizeId, $colorId);
            $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

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

            $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
        } else {
            $sizecolorstoredetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);
            $sizecolorstoredetail->userid = $_SESSION['userid'];
            $sizecolorstoredetail->sysdate = date("Y-m-d H:i:s");
            $sizecolorstoredetail->quantity += $finalquantity;
            $sizeColorStoreDetailDAO->update($sizecolorstoredetail);
        }
    }
}

function getStoredetailData($storeid, $productid) {

    //to use the variable out side the funcion
    global $myStoredetailEx;

    //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 decrease Rawmaterialamount in storerawmaterialdetails tbl
function decreaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount) { //, $colName, $detailId, $productId, $tableName) {
    //to use the variable out side the funcion
    global $myStoredetail;
    global $myStoredetailEx;

    //increase productquantity
    $productquantityAfter = $productquantityBefore - $productChangeAmount;
    //////////////////////////////lastAndMeanBuyPrice_Sell($colName, $detailId, $productId, $tableName, $productquantityBefore, $productquantityAfter, $productChangeAmount);
    //update productquantity in storedetail tbl
    $myStoredetail->storedetailid = $storedetailId;
    $myStoredetail->userid = $_SESSION['userid'];
    $myStoredetail->storedetaildate = date("Y-m-d H:i:s");
    $myStoredetail->productquantity = $productquantityAfter;

    $myStoredetailEx->updateProductquantity($myStoredetail);

    return $productquantityAfter;
}

//update and increase productquantity in storedetail tbl
function increaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount) { //, $colName, $detailId, $productId, $tableName) {
    //to use the variable out side the funcion
    global $myStoredetail;
    global $myStoredetailEx;

    //increase productquantity
    $productquantityAfter = $productquantityBefore + $productChangeAmount;
    //lastAndMeanBuyPrice_Sell($colName, $detailId, $productId, $tableName, $productquantityBefore, $productquantityAfter, $productChangeAmount);
    //update productquantity in storedetail tbl
    $myStoredetail->storedetailid = $storedetailId;
    $myStoredetail->userid = $_SESSION['userid'];
    $myStoredetail->storedetaildate = date("Y-m-d H:i:s");
    $myStoredetail->productquantity = $productquantityAfter;

    $myStoredetailEx->updateProductquantity($myStoredetail);

    return $productquantityAfter;
}

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

    $myStorereport->processname = $processname;
    $myStorereport->productafter = $productafter;
    $myStorereport->productbefore = $productbefore;
    $myStorereport->productquantity = $productChangeAmount;
    $myStorereport->productid = $productid;
    $myStorereport->sizeid = $sizeId;
    $myStorereport->colorid = $colorId;
    $myStorereport->storeid = $storeid;
    $myStorereport->storereportdate = $mydate;
    $myStorereport->storereportmodelid = $storereportmodelid;
    $myStorereport->storereporttype = $storereporttype;
    $myStorereport->tablename = $tablename;
    $myStorereport->userid = $_SESSION['userid'];

    $myStorereportRecord->insert($myStorereport);
}

//add in storerawmaterialdetails tbl
function insertStoredetailupdate($storeid, $productid, $productChangeAmount, $mydate) {

    global $myStoredetail;
    global $myStoredetailRecord;

    $myStoredetail->userid = $_SESSION['userid'];
    $myStoredetail->storedetaildate = $mydate;
    $myStoredetail->productquantity = $productChangeAmount;
    $myStoredetail->storeid = $storeid;
    $myStoredetail->productid = $productid;

    $myStoredetailRecord->insert($myStoredetail);
}

function calcMeanBuyPrice($proId, $quantity, $cost, $lastBuyMeanPrice) {
    global $myStoredetailEx;

    $storeDetailData = $myStoredetailEx->getProductQuantityInAllStores($proId);

    $lastMean = $storeDetailData * $lastBuyMeanPrice;
    $newMean = $quantity * $cost;
    $top = $lastMean + $newMean;
    $bottom = $storeDetailData + $quantity;
    if (empty($bottom)) {
        $bottom = 2;
    }
    $newBuyMeanPrice = $top / $bottom;

    return $newBuyMeanPrice;
}

##from sellbill cont for the ingridients

function getBuyPriceFromAndHandleBuyPricesHistoryBook($storeId, $productid, $sizeid, $colorid, $productBuyPrice, $soldQuantity, $type = 0) { //0 add ,1 del
    global $buyPricesHistoryBookDAO;
    global $buyPricesHistoryBookEX;

    $idQuantityString = '';
    $remainQuantity = $soldQuantity;
    $totalPrice = 0;
    do {
        $buyPriceFromHistoryBook = $buyPricesHistoryBookEX->getBuyPriceOfFirstAvailableSellQuantity($storeId, $productid, $sizeid, $colorid);
        if (isset($buyPriceFromHistoryBook->id) && $buyPriceFromHistoryBook->id > 0 && $remainQuantity > 0) {
            $availableBuyQuantity = $buyPriceFromHistoryBook->buyQuantity - $buyPriceFromHistoryBook->sellQuantity;
            if ($availableBuyQuantity >= $remainQuantity) {
                $totalPrice += $remainQuantity * $buyPriceFromHistoryBook->buyprice;
                if ($type == 0) {
                    $buyPricesHistoryBookEX->plusSellQuantityByValue($remainQuantity, $buyPriceFromHistoryBook->id);
                } elseif ($type == 1) {
                    $buyPricesHistoryBookEX->minusSellQuantityByValue($remainQuantity, $buyPriceFromHistoryBook->id);
                }
                //
                $idQuantityString .= "$buyPriceFromHistoryBook->id-$remainQuantity,";
                $remainQuantity -= $remainQuantity; //$remainQuantity = 0;
            } elseif ($remainQuantity > $availableBuyQuantity) {
                $totalPrice += $availableBuyQuantity * $buyPriceFromHistoryBook->buyprice;
                if ($type == 0) {
                    $buyPricesHistoryBookEX->plusSellQuantityByValue($availableBuyQuantity, $buyPriceFromHistoryBook->id);
                } elseif ($type == 1) {
                    $buyPricesHistoryBookEX->minusSellQuantityByValue($availableBuyQuantity, $buyPriceFromHistoryBook->id);
                }
                //
                $idQuantityString .= "$buyPriceFromHistoryBook->id-$availableBuyQuantity,";
                $remainQuantity -= $availableBuyQuantity;
            }
        }
    } while (isset($buyPriceFromHistoryBook->id) && $buyPriceFromHistoryBook->id > 0 && $remainQuantity > 0);

    if ($remainQuantity > 0) {
        $totalPrice += $remainQuantity * $productBuyPrice;
        $remainQuantity -= $remainQuantity;
    }

    $theBuyPrice = round(($totalPrice / $soldQuantity), 2);
    return array(
        $theBuyPrice,
        $idQuantityString
    );
}

##from sellbill cont for the ingridients

function decreaseSellQuantityHandleBuyPricesHistoryBook($idQuantityString) {
    global $buyPricesHistoryBookDAO;
    global $buyPricesHistoryBookEX;

    foreach (explode(',', $idQuantityString) as $row) {
        $data = explode('-', $row);
        $id = $data[0];
        $quantity = $data[1];
        if ($id > 0 && $quantity != 0) {
            $buyPricesHistoryBookEX->minusSellQuantityByValue($quantity, $id);
        }
    }
}

##from buybill cont for the production output,waste products

function increaseBuyPricesHistoryBookBuyQuantity($theDate, $storeId, $productid, $sizeid, $colorid, $buyprice, $buyQuantity) {
    global $buyPricesHistoryBookDAO;
    global $buyPricesHistoryBookEX;

    $buyPricesHistoryBook->theDate = $theDate;
    $buyPricesHistoryBook->storeId = $storeId;
    $buyPricesHistoryBook->productid = $productid;
    $buyPricesHistoryBook->sizeid = $sizeid;
    $buyPricesHistoryBook->colorid = $colorid;
    $buyPricesHistoryBook->buyprice = $buyprice;
    $buyPricesHistoryBook->buyQuantity = $buyQuantity;
    $buyPricesHistoryBook->sellQuantity = 0; //to add zero quantity to sell quantity
    $buyPricesHistoryBook->del = 0;
    $buyPricesHistoryBook->userid = $_SESSION['userid'];
    $buyPricesHistoryBook->sysDate = date('Y-m-d H:i:s');
    $buyPricesHistoryBookEX->insertOrUpdatePlusEX($buyPricesHistoryBook);
}

##from buybill cont for the production output,waste products

function decreaseBuyPricesHistoryBookBuyQuantity($theDate, $storeId, $productid, $sizeid, $colorid, $buyprice, $buyQuantity) {
    global $buyPricesHistoryBookDAO;
    global $buyPricesHistoryBookEX;

    $buyPricesHistoryBook->theDate = $theDate;
    $buyPricesHistoryBook->storeId = $storeId;
    $buyPricesHistoryBook->productid = $productid;
    $buyPricesHistoryBook->sizeid = $sizeid;
    $buyPricesHistoryBook->colorid = $colorid;
    $buyPricesHistoryBook->buyprice = $buyprice;
    $buyPricesHistoryBook->buyQuantity = $buyQuantity;
    $buyPricesHistoryBook->sellQuantity = 0; //to add zero quantity to sell quantity
    $buyPricesHistoryBook->del = 0;
    $buyPricesHistoryBook->userid = $_SESSION['userid'];
    $buyPricesHistoryBook->sysDate = date('Y-m-d H:i:s');
    $buyPricesHistoryBookEX->insertOrUpdateMinusEXBuyPriceNoUpdate($buyPricesHistoryBook);
}

function doInventoryDailyEntry($productionExecution) {
    global $simplesettingDao;
    global $ProgramsettingEX;

    $simpleSetting = $simplesettingDao->load(1);
    $rawMaterialStoreid = $simpleSetting->storeid;

    $outstoreid = R::getCell('select storeid from productionexecutionoutput where exeutionid=' . $productionExecution->id);

    if ($rawMaterialStoreid != $outstoreid) {
        ## 1- get needed data
        $rawMaterialCost = R::getCell('select sum(actualcost) from productionexecutionproduct where executionid=' . $productionExecution->id);
        $productName = R::getCell('select productName from product where productId=' . $productionExecution->productid);
        $treeIdRawMaterial = R::getCell('select treeId from store where storeId=' . $rawMaterialStoreid);
        $treeIdOutStore = R::getCell('select treeId from store where storeId=' . $outstoreid);

        ## 2- do entry
        $dailyEntry->entryComment = 'امر انتاج  ' . $productName;
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->accountstreeid = $treeIdRawMaterial;
        $dailyEntryDebtor->value = $rawMaterialCost;
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $rawMaterialCost;
        $dailyEntryCreditor->accountstreeid = $treeIdOutStore;

        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
        array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $productionExecution->id, 'productionExecutionController.php?do=details&id=' . $productionExecution->id);

        $did = $returnedData[1];
        $ProgramsettingEX->runSqlQuery('update productionexecution set dailyentryid=' . $did . ' where id=' . $productionExecution->id);
    }
}
