<?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");

//Productionorder
require_once('../models/dao/ProductionorderDAO.class.php');
require_once('../models/dto/Productionorder.class.php');
require_once('../models/mysql/ProductionorderMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionorderMySqlExtDAO.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');

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



//Stage
require_once('../models/dao/StageDAO.class.php');
require_once('../models/dto/Stage.class.php');
require_once('../models/mysql/StageMySqlDAO.class.php');
require_once('../models/mysql/ext/StageMySqlExtDAO.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');

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

//Productunit
require_once('../models/dao/ProductunitDAO.class.php');
require_once('../models/dto/Productunit.class.php');
require_once('../models/mysql/ProductunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductunitMySqlExtDAO.class.php');

//productUnit
require_once('../models/dao/ProductunitDAO.class.php');
require_once('../models/dto/Productunit.class.php');
require_once('../models/mysql/ProductunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductunitMySqlExtDAO.class.php');


//unit
require_once('../models/dao/UnitDAO.class.php');
require_once('../models/dto/Unit.class.php');
require_once('../models/mysql/UnitMySqlDAO.class.php');
require_once('../models/mysql/ext/UnitMySqlExtDAO.class.php');


//damagedProduct
require_once('../models/dao/DamagedproductDAO.class.php');
require_once('../models/dto/Damagedproduct.class.php');
require_once('../models/mysql/DamagedproductMySqlDAO.class.php');
require_once('../models/mysql/ext/DamagedproductMySqlExtDAO.class.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');

//////////////////////////for The Report/////////////////
//stagestep
require_once('../models/dao/StagestepDAO.class.php');
require_once('../models/dto/Stagestep.class.php');
require_once('../models/mysql/StagestepMySqlDAO.class.php');
require_once('../models/mysql/ext/StagestepMySqlExtDAO.class.php');
//workStation
require_once('../models/dao/WorkstationDAO.class.php');
require_once('../models/dto/Workstation.class.php');
require_once('../models/mysql/WorkstationMySqlDAO.class.php');
require_once('../models/mysql/ext/WorkstationMySqlExtDAO.class.php');


//workstationworker
require_once('../models/dao/WorkstationworkerDAO.class.php');
require_once('../models/dto/Workstationworker.class.php');
require_once('../models/mysql/WorkstationworkerMySqlDAO.class.php');
require_once('../models/mysql/ext/WorkstationworkerMySqlExtDAO.class.php');

//Assetes
require_once('../models/dao/AssetsDAO.class.php');
require_once('../models/dto/Asset.class.php');
require_once('../models/mysql/AssetsMySqlDAO.class.php');
require_once('../models/mysql/ext/AssetsMySqlExtDAO.class.php');

//settingOperation
require_once('../models/dao/SettingoperationDAO.class.php');
require_once('../models/dto/Settingoperation.class.php');
require_once('../models/mysql/SettingoperationMySqlDAO.class.php');
require_once('../models/mysql/ext/SettingoperationMySqlExtDAO.class.php');

//workstationassets
require_once('../models/dao/WorkstationassetsDAO.class.php');
require_once('../models/dto/Workstationasset.class.php');
require_once('../models/mysql/WorkstationassetsMySqlDAO.class.php');
require_once('../models/mysql/ext/WorkstationassetsMySqlExtDAO.class.php');

//employee
require_once('../models/dao/EmployeeDAO.class.php');
require_once('../models/dto/Employee.class.php');
require_once('../models/mysql/EmployeeMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeeMySqlExtDAO.class.php');

//damagedProduct
require_once('../models/dao/DamagedproductDAO.class.php');
require_once('../models/dto/Damagedproduct.class.php');
require_once('../models/mysql/DamagedproductMySqlDAO.class.php');
require_once('../models/mysql/ext/DamagedproductMySqlExtDAO.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 :- productionOrderController

  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
//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

//Productionorder
$productionorder = new Productionorder();
$productionorderDAO = new ProductionorderMySqlDAO();
$productionorderEX = new ProductionorderMySqlExtDAO();

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


//stage
$stage = new Stage();
$stageDAO = new StageMySqlDAO();
$stageEX = new StageMySqlExtDAO();

//Store
$store = new Store();
$storeDAO = new StoreMySqlDAO();
$storeEX = new StoreMySqlExtDAO();

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

//Storedetail
$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailExt = new StoredetailMySqlExtDAO;

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

//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();

$productunit = new Productunit();
$productunitDAO = new ProductunitMySqlDAO();

//unit
$unit = new Unit();
$unitDAO = new UnitMySqlDAO();
$unitEx = new UnitMySqlExtDAO();

//damagedProduct
$damagedProduct = new Damagedproduct();
$damagedProductDAO = new DamagedproductMySqlDAO();
$damagedProductEx = new DamagedproductMySqlExtDAO();


//Productionrate
$productionrate = new Productionrate();
$productionrateDAO = new ProductionrateMySqlDAO();
$productionrateEX = new ProductionrateMySqlExtDAO();

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

//////////////////////////////////for The Report///////////////////////
//stagestep
$StagestepDAO = new StagestepMySqlDAO();
$Stagestep = new Stagestep();
$StagestepEX = new StagestepMySqlExtDAO();

//workStation
$workStation = new Workstation();
$workStationDOA = new WorkstationMySqlDAO();
$workStationEX = new WorkstationMySqlExtDAO();

//workstationworker
$workstationworker = new Workstationworker();
$workstationworkerADO = new WorkstationworkerMySqlDAO();
$workstationworkerEX = new WorkstationworkerMySqlExtDAO();

//Asetess
$assetes = new Asset();
$assetesADO = new AssetsMySqlDAO();
$assetesEX = new AssetsMySqlExtDAO();

//employee
$Employee = new Employee();
$EmployeeDAO = new EmployeeMySqlDAO();
$EmployeeEX = new EmployeeMySqlExtDAO();

//setting operation
$settingOperation = new Settingoperation();
$settingOperationDAO = new SettingoperationMySqlDAO();
$settingOperationEX = new SettingoperationMySqlExtDAO();

//workstationassets
$Workstationassets = new Workstationasset();
$WorkstationassetsDAO = new WorkstationassetsMySqlDAO();
$WorkstationassetsEX = new WorkstationassetsMySqlExtDAO();

//damagedProduct
$damagedProduct = new Damagedproduct();
$damagedProductDAO = new DamagedproductMySqlDAO();
$damagedProductEx = new DamagedproductMySqlExtDAO();

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

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

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

    $stages = $stageDAO->queryAll();
    $stores = $storeDAO->queryAll();

    $smarty->assign("stages", $stages);
    $smarty->assign("stores", $stores);

    //js for unit is with footer
    $smarty->display("productionOrderView/add.html");
} elseif ($do == "add") {
    //here the permssion check
    include_once("../public/authentication.php");



    try {
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "details") {
    //here the permssion check
    include_once("../public/authentication.php");

    $id = $_GET["id"];
    $productionorder = $productionorderDAO->load($id);


    $RawMaterialsdata = getRawMaterialsAndTotalCostOfIt($productionorder->productId, $productionorder->measureUnitId, $productionorder->outQuantity);

    //RawMaterials of production order
    $smarty->assign("Productionrateproduct", $RawMaterialsdata[0]);
    $smarty->assign("totalCostOfRawMaterials", $RawMaterialsdata[1]);


    //get damagedProduct
    try {

        $damagedProduct = $damagedProductEx->queryByProductionOrderIdAndGetProductNameAndUnitName($productionorder->productionOrderid);
        $quantity = 0;
        foreach ($damagedProduct as $mydamagedProduct) {
            $quantity+=$mydamagedProduct->productQuantity;
        }
        /* print_r('<pre>');
          print_r($damagedProduct);
          print_r('</pre>'); */

        $mydamagedata = getRawMaterialsAndTotalCostOfIt($damagedProduct[0]->productId, $damagedProduct[0]->measurUnitId, $quantity/* $damagedProduct[0]->productQuantity */);

        //damagedProduct
        $smarty->assign("damagedProductMaterials", $mydamagedata[0]);
        $smarty->assign("totalcostofdamagedProduct", $mydamagedata[1]);
    } catch (Exception $e) {
        $smarty->assign("totalcostofdamagedProduct", 0);
    }


    //workers && machines
    $Stagestep = $StagestepDAO->queryByStageId($productionorder->stageId);

    $y = 0;

    $queryString = ' ';
    $WorkstationassetsArray = array();
    $workstationworkerArray = array();
    foreach ($Stagestep as $ss) {
        $settingOperation = $settingOperationEX->queryByoperationid($ss->operationId);
        foreach ($settingOperation as $so) {
            $workstationworkerArray[$y] = $workstationworkerEX->queryAllx($so->workStationID);
            //set settingOperation realtime
            foreach ($workstationworkerArray[$y] as $a) {
                $a->settingOperationrealTime = $so->realTime;
            }
            $WorkstationassetsArray[$y] = $WorkstationassetsEX->queryAllx($so->workStationID);



            //set settingOperation realtime
            foreach ($WorkstationassetsArray[$y] as $a) {
                $a->settingOperationrealTime = $so->realTime;
            }
            $y++;
        }
    }



    //workers
    $workstationworkerArrayOnelevel = array();
    foreach ($workstationworkerArray as $x) {
        foreach ($x as $s) {
            array_push($workstationworkerArrayOnelevel, $s);
        }
    }
    $Workersdata = getuniqueArrayAndTotal($workstationworkerArrayOnelevel, 1);
    $smarty->assign("workstationworkerArrayUnique", $Workersdata[0]);
    $smarty->assign("totalcostofWorkers", $Workersdata[1]);



    //assets
    $WorkstationassetsArrayOnelevel = array();
    foreach ($WorkstationassetsArray as $x) {
        foreach ($x as $s) {
            array_push($WorkstationassetsArrayOnelevel, $s);
        }
    }
    $assetsdata = getuniqueArrayAndTotal($WorkstationassetsArrayOnelevel, 2);
    $smarty->assign("WorkstationassetsArrayUnique", $assetsdata[0]);
    $smarty->assign("totalcostofassets", $assetsdata[1]);



    $totalOfTotals = 0;
    $totalOfTotals = $RawMaterialsdata[1] + $mydamagedata[1] + $assetsdata[1] + $Workersdata[1];
    $AverageUnitPrice = round($totalOfTotals / $productionorder->outQuantity, 2);
    $smarty->assign("totalOfTotals", $totalOfTotals);
    $smarty->assign("AverageUnitPrice", $AverageUnitPrice);


    //js for unit is with footer
    $smarty->display("productionOrderView/showDetails.html");
} elseif ($do == "showDetailsByDate") {
    $from = $_POST["from"];
    $to = $_POST["to"];

    //get productionorders ///////////for testing we are trying productionorder of date 17-4-2014
    if (isset($from) && !empty($from) && isset($to) && !empty($to)) {
        $productionorder = $productionorderEX->queryByOrderDateBettween($from, $to);
    } else {
        $productionorder = $productionorderDAO->queryAll();
    }

    $j = 0;
    $totalOfTotals = array();
    foreach ($productionorder as $myproductionorder) {
        //Get Raw MAterials
        $RawMaterialsdata[$j] = getRawMaterialsAndTotalCostOfIt($myproductionorder->productId, $myproductionorder->measureUnitId, $myproductionorder->outQuantity);


        //get damaged product
        $damagedProduct = $damagedProductEx->queryByProductionOrderIdAndGetProductNameAndUnitName($myproductionorder->productionOrderid);

        if (isset($damagedProduct) && !empty($damagedProduct)) {//////////////ساعات مش هيكون فيه تالف
            $mydamagedata[$j] = getRawMaterialsAndTotalCostOfIt($damagedProduct[0]->productId, $damagedProduct[0]->measurUnitId, $damagedProduct[0]->productQuantity);
        }


        //workers && machines
        $Stagestep = $StagestepDAO->queryByStageId($myproductionorder->stageId);

        $y = 0;

        $queryString = ' ';
        $WorkstationassetsArray = array();
        $workstationworkerArray = array();
        foreach ($Stagestep as $ss) {
            $settingOperation = $settingOperationEX->queryByoperationid($ss->operationId);
            foreach ($settingOperation as $so) {
                $workstationworkerArray[$y] = $workstationworkerEX->queryAllx($so->workStationID);
                //set settingOperation realtime
                foreach ($workstationworkerArray[$y] as $a) {
                    $a->settingOperationrealTime = $so->realTime;
                }
                $WorkstationassetsArray[$y] = $WorkstationassetsEX->queryAllx($so->workStationID);



                //set settingOperation realtime
                foreach ($WorkstationassetsArray[$y] as $a) {
                    $a->settingOperationrealTime = $so->realTime;
                }
                $y++;
            }
        }


        //workers
        $workstationworkerArrayOnelevel = array();
        foreach ($workstationworkerArray as $x) {
            foreach ($x as $s) {
                array_push($workstationworkerArrayOnelevel, $s);
            }
        }
        $Workersdata[$j] = getuniqueArrayAndTotal($workstationworkerArrayOnelevel, 1);


        //assets
        $WorkstationassetsArrayOnelevel = array();
        foreach ($WorkstationassetsArray as $x) {
            foreach ($x as $s) {
                array_push($WorkstationassetsArrayOnelevel, $s);
            }
        }
        $assetsdata[$j] = getuniqueArrayAndTotal($WorkstationassetsArrayOnelevel, 2);


        $totalOfTotals[$j] = $RawMaterialsdata[$j][1] + $mydamagedata[$j][1] + $Workersdata[$j][1] + $assetsdata[$j][1];
        $j++;
    }


    //RawMaterialsdataArrayOnelevel
    $RawMaterialsdataArrayOnelevel = array();
    $totalCostOfRawMaterials = 0;
    foreach ($RawMaterialsdata as $x) {
        $totalCostOfRawMaterials+=$x[1];
        end($x);
        array_pop($x);
        //print_r("<pre>");print_r($x);print_r("</pre>");
        foreach ($x as $s) {
            foreach ($s as $ss) {
                array_push($RawMaterialsdataArrayOnelevel, $ss);
            }
        }
    }

    $Productionrateproduct = getuniqueArrayAndTotal($RawMaterialsdataArrayOnelevel, 3);
    $smarty->assign("Productionrateproduct", $Productionrateproduct[0]);
    $smarty->assign("totalCostOfRawMaterials", $totalCostOfRawMaterials);

    //mydamagedataArrayOnelevel
    $mydamagedataArrayOnelevel = array();
    $totalcostofdamagedProduct = 0;
    if ($mydamagedata) {
        foreach ($mydamagedata as $x) {
            $totalcostofdamagedProduct+=$x[1];
            end($x);
            array_pop($x);
            foreach ($x as $s) {
                foreach ($s as $ss) {
                    array_push($mydamagedataArrayOnelevel, $ss);
                }
            }
        }
    }

    $Productionrateproduct = getuniqueArrayAndTotal($mydamagedataArrayOnelevel, 3);
    $smarty->assign("damagedProductMaterials", $Productionrateproduct[0]);
    $smarty->assign("totalcostofdamagedProduct", $totalcostofdamagedProduct);

    //WorkersdataArrayOnelevel
    $WorkersdataArrayOnelevel = array();
    $totalcostofWorkers = 0;
    foreach ($Workersdata as $x) {
        $totalcostofWorkers+=$x[1];
        end($x);
        array_pop($x);
        foreach ($x as $s) {
            foreach ($s as $ss) {
                array_push($WorkersdataArrayOnelevel, $ss);
            }
        }
    }

    $workstationworkerArrayUnique = getuniqueArrayAndTotal($WorkersdataArrayOnelevel, 11);
    $smarty->assign("workstationworkerArrayUnique", $workstationworkerArrayUnique[0]);
    $smarty->assign("totalcostofWorkers", $totalcostofWorkers);

    //assetsdataArrayOnelevel
    $assetsdataArrayOnelevel = array();
    $totalcostofassets = 0;
    foreach ($assetsdata as $x) {
        $totalcostofassets+=$x[1];
        end($x);
        array_pop($x);
        foreach ($x as $s) {
            foreach ($s as $ss) {
                array_push($assetsdataArrayOnelevel, $ss);
            }
        }
    }

    $WorkstationassetsArrayUnique = getuniqueArrayAndTotal($assetsdataArrayOnelevel, 22);
    $smarty->assign("WorkstationassetsArrayUnique", $WorkstationassetsArrayUnique[0]);
    $smarty->assign("totalcostofassets", $totalcostofassets);

    $totalOfTotals = 0;
    $totalOfTotals = $totalCostOfRawMaterials + $totalcostofdamagedProduct + $totalcostofWorkers + $totalcostofassets;
    $smarty->assign("totalOfTotals", $totalOfTotals);
    $smarty->assign("from", $from);
    $smarty->assign("to", $to);

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

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

    $stages = $stageDAO->queryAll();
    //$stores=$storeDAO->queryAll();

    $smarty->assign("stages", $stages);
    //$smarty->assign("stores", $stores);


    $id = $_GET["id"];



    $productionorder = $productionorderDAO->load($id);
    $store = $storeDAO->load($productionorder->storeId);

    $product = $productDAO->load($productionorder->productId);
    $productunit = $productunitDAO->load($productionorder->measureUnitId);
    $unit = $unitDAO->load($productunit->unitid);

    $smarty->assign("productionorder", $productionorder);
    $smarty->assign("product", $product->productName);
    $smarty->assign("Unit", $unit->unitName);
    $smarty->assign("store", $store->storeName);

    //js for unit is with footer
    $smarty->display("productionOrderView/edit.html");
} elseif ($do == "update") {
    //here the permssion check
    include_once("../public/authentication.php");



    try {
        $msg = update();

        //print_r($msg);
        if ($msg == "done") {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "show") {
    //here the permssion check
    include_once("../public/authentication.php");

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $value = $_POST["typeoforder"];
    if ($value == 2) {
        $productionorder = $productionorderDAO->queryAll();
    } else {
        $productionorder = $productionorderDAO->queryByOrderStatus(0);
    }

    $smarty->assign("productionorder", $productionorder);

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

    $id = $_GET["id"];
    $productionorder = $productionorderDAO->load($id);

    $product = $productDAO->load($productionorder->productId);
    $store = $storeDAO->load($productionorder->storeId);
    $stage = $stageDAO->load($productionorder->stageId);
    $productunit = $productunitDAO->load($productionorder->measureUnitId);
    $unit = $unitDAO->load($productunit->unitid);

    $damagedProduct = $damagedProductEx->queryByProductionOrderIdAndGetProductName($id);


    $smarty->assign("productionorder", $productionorder);
    $smarty->assign("damagedProduct", $damagedProduct);
    $smarty->assign("product", $product->productName);

    $smarty->assign("store", $store->storeName);
    $smarty->assign("stage", $stage->stagename);
    $smarty->assign("Unit", $unit->unitName);

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

    try {
        recievedone();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "stop") {
    //here the permssion check
    include_once("../public/authentication.php");

    try {

        stop_active();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "delete") {
    //here the permssion check
    include_once("../public/authentication.php");

    try {
        delete();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "damagedProduct") {
    //here the permission check
    include_once("../public/authentication.php");

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

    //All stores
    $allStores = $storeDAO->queryAll();
    $smarty->assign("allStores", $allStores);

    //production Order
    $id = $_GET['id'];
    $smarty->assign("id", $id);
    $productionOrderData = $productionorderDAO->load($id);
    $smarty->assign("productionOrderData", $productionOrderData);

    //final Product Name
    $finalOrder = $productionorderEX->queryAllWithProductName($id);
    $orderName = $finalOrder[0];
    $smarty->assign("orderName", $orderName);



    //$smarty->assign("customDamadagProduct",1);
    //here the smarty templates
    $smarty->display("productionOrderView/DamageProduct.html");
} elseif ($do == "addDamageProduct") {
    //here the permssion check
    include_once("../public/authentication.php");

    try {
        $id = $_POST['id'];
        addDamageProduct();
        header("location:productionOrderController.php?do=recieve&id=$id");
    } catch (Exception $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("customProductionOrder", 1);
$smarty->display("footer.html");

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

//add
function add() {
    //global variables
    //Productionrate
    global $productionrate;
    global $productionrateEX;

    //Productionrateproduct
    global $Productionrateproduct;
    global $ProductionrateproductDAO;

    //Productionorder
    global $productionorder;
    global $productionorderDAO;


    $productionOrderId = insertProductionOrder();

    $productionorder = $productionorderDAO->load($productionOrderId);
    $FinalproductunitData = loadProductUnitWithProductAndUnit($productionorder->productId, $productionorder->measureUnitId);
    $Finalproductnumber = $FinalproductunitData->productnumber;
    /* print_r("<pre>");
      print_r("ddddd".$Finalproductnumber); */

    //get final product
    $finalProductId = $_POST["productId"];
    /* print_r("<pre>");
      print_r("ddddd".$_POST["productId"]); */
    $productionrate = $productionrateEX->queryOneRateByfinalName($finalProductId);

    $Productionrateproduct = $ProductionrateproductDAO->queryByProductionRateId($productionrate->productionRateId);

    $i = 0;
    foreach ($Productionrateproduct as $p) {

        /* print_r($p);
          echo "</br>"; */

        //get product before
        $productId = $Productionrateproduct[$i]->productId;

        $productunitData = loadProductUnitWithProductAndUnit($productId, $Productionrateproduct[$i]->unitId);

        $productnumber = $productunitData->productnumber;

        $finalquantity = $_POST["outQuantity"] * $productnumber * $Finalproductnumber * $Productionrateproduct[$i]->quantity;

        if (isset($finalProductId) && $finalProductId != '-1' && $finalProductId != "") {
            //get store productquantity before change
            $storedetailData = getStoredetailData($_POST["store"], $productId);

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

            if (count($allStoredetailData) > 0) {

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


                //insert in storereport
                insertStorereport($productId, $_POST["store"], $finalquantity, $productquantityBefore, $productquantityAfter, 1, $productionOrderId, "تصنيع", "productionOrderController.php");
            } else {
                $specialQuantityAfter = $finalquantity * -1;

                //insert in storedetail tbl
                insertStoredetail($_POST["store"], $productId, $specialQuantityAfter);

                //insert in storereport
                insertStorereport($productId, $_POST["store"], $finalquantity, $productquantityBefore, $specialQuantityAfter, 1, $productionOrderId, "تصنيع", "productionOrderController.php");
            }
        }
        $i++;
    }
}

//insertProductionOrder
function insertProductionOrder() {

    //define global variables
    //Productionorder
    global $productionorder;
    global $productionorderDAO;


    //1-status=0 (تحت التنفيذ)
    //$productionorder->branchId; //we keep it with no data //in database it is nullable
    $productionorder->conditions = 0;
    $productionorder->startDate = $_POST["from"];
    $productionorder->endDate = $_POST["to"];
    $productionorder->measureUnitId = $_POST["unitId"];
    $productionorder->name = $_POST["orderName"];
    $productionorder->orderDate = date("Y-m-d");
    $productionorder->orderStatus = 0;
    $productionorder->outQuantity = $_POST["outQuantity"];
    $productionorder->productId = $_POST["productId"];
    $productionorder->stageId = $_POST["stage"];
    $productionorder->storeId = $_POST["store"];
    $productionorder->userId = $_SESSION["userid"];

    /* print_r("<pre>");
      print_r($productionorder); */
    //2-insert productionorder
    $productionOrderId = $productionorderDAO->insert($productionorder);
    //print_r( "ggggggggggggg".$productionOrderId."gggggggggggggggg");
    return $productionOrderId;
}

function update() {
    $v1 = $_POST["outQuantity"];
    $v2 = $_POST["oldOutQuantity"];



    if ($v1 < $v2) {
        $msg = "not done";
        return $msg;
    } else {

        //print_r(" كمل تحت");

        global $productionorder;
        global $productionorderDAO;
        global $productionrateEX;
        global $ProductionrateproductDAO;



        //1-update production order
        //1-status=0 (تحت التنفيذ)/////////////////////////////////////
        //$productionorder->branchId; //we keep it with no data //in database it is nullable
        $productionorder->productionOrderid = $_POST["productionOrderid"];
        $productionorder->conditions = $_POST["conditions"];
        $productionorder->startDate = $_POST["from"];
        $productionorder->endDate = $_POST["to"];
        $productionorder->measureUnitId = $_POST["unitId"];
        $productionorder->name = $_POST["orderName"];
        $productionorder->orderDate = date("Y-m-d");
        $productionorder->orderStatus = $_POST["orderStatus"];
        $productionorder->outQuantity = $_POST["outQuantity"];
        $productionorder->productId = $_POST["productId"];
        $productionorder->stageId = $_POST["stage"];
        $productionorder->storeId = $_POST["store"];
        $productionorder->userId = $_SESSION["userid"];

        $productionorderDAO->update($productionorder);

        //2-update store details and store report
        //get product before
        $productId = $_POST["productId"];
        //get outQuantity before
        $oldOutQuantity = $_POST["oldOutQuantity"];

        $FinalproductunitData = loadProductUnitWithProductAndUnit($productId, $_POST["unitId"]);
        $Finalproductnumber = $FinalproductunitData->productnumber;


        if ($v1 == $v2) {
            $newoutQuantity = 0;
        } else {
            $newoutQuantity = $_POST["outQuantity"] - $_POST["oldOutQuantity"];
        }



        $productionrate = $productionrateEX->queryOneRateByfinalName($productId);

        $Productionrateproduct = $ProductionrateproductDAO->queryByProductionRateId($productionrate->productionRateId);

        $i = 0;
        foreach ($Productionrateproduct as $p) {

            //get product before
            $productId = $Productionrateproduct[$i]->productId;

            $productunitData = loadProductUnitWithProductAndUnit($productId, $Productionrateproduct[$i]->unitId);

            $productnumber = $productunitData->productnumber;
            $finalquantity = $newoutQuantity * $productnumber * $Finalproductnumber * $Productionrateproduct[$i]->quantity;
            print_r("newoutQuantity=" . $newoutQuantity);
            echo "</br>";
            print_r("productnumber=" . $productnumber);
            echo "</br>";
            print_r("Finalproductnumber=" . $Finalproductnumber);
            echo "</br>";
            print_r("p quantity in p rate=" . $Productionrateproduct[$i]->quantity);
            echo "</br>";
            print_r("finalquantity=" . $finalquantity);
            echo "</br>";


            if (isset($productId) && $productId != '-1' && $productId != "") {
                //get store productquantity before change
                $storedetailData = getStoredetailData($_POST["store"], $productId);

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

                if (count($allStoredetailData) > 0) {

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


                    //insert in storereport
                    insertStorereport($productId, $_POST["store"], $finalquantity, $productquantityBefore, $productquantityAfter, 1, $_POST["productionOrderid"], " تعديل تصنيع", "productionOrderController.php");
                } else {
                    $specialQuantityAfter = $finalquantity * -1;

                    //insert in storedetail tbl
                    insertStoredetail($_POST["store"], $productId, $specialQuantityAfter);

                    //insert in storereport
                    insertStorereport($productId, $_POST["store"], $finalquantity, $productquantityBefore, $specialQuantityAfter, 1, $_POST["productionOrderid"], " تعديل تصنيع", "productionOrderController.php");
                }
            }
            $i++;
        }


        $msg = "done";
        return $msg;
    }
}

function recievedone() {
    global $productionorder;
    global $productionorderDAO;


    $id = $_POST["productionOrderid"];
    $productionorder = $productionorderDAO->load($id);

    //get product before
    $productId = $productionorder->productId; //$_POST["productId"];
    $unitId = $productionorder->measureUnitId;

    $productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
    $productnumber = $productunitData->productnumber;

    $finalquantity = $productionorder->outQuantity * $productnumber;
    if (isset($productId) && $productId != '-1' && $productId != "") {
        //get store productquantity before change
        $storeDetailData = getStoreDetails($productionorder->storeId, $productId);

        $allStoredetailData = $storeDetailData[0];
        $storeDetailId = $storeDetailData[1];
        $productQuantityBefore = $storeDetailData[2];


        if (count($allStoredetailData) > 0) {
            //update productquantity in storedetail
            $productQuantityAfter = increaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity);

            //insert in storereport
            insertStorereport($productId, $productionorder->storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 0, $productionorder->productionOrderid, "اضافة منتج نهائى بعد تصنيعه", "productionOrderController.php");
        } else {

            //insert in storedetail tbl
            insertStoredetail($productionorder->storeId, $productId, $finalquantity);

            //insert in storereport
            insertStorereport($productId, $productionorder->storeId, $finalquantity, 0, $finalquantity, 0, $productionorder->productionOrderid, "اضافة منتج نهائى بعد تصنيعه", "productionOrderController.php");
        }
    }


    //update productionorder
    $productionorder->orderStatus = 1;
    $productionorderDAO->update($productionorder);
}

function addDamageProduct() {
    //damadage table
    global $damagedProduct;
    global $damagedProductDAO;
    global $damagedProductEx;
    global $smarty;

    //Storedetail
    global $storeDetail;
    global $storeDetailExt;
    global $storeDetailDAO;

    //Store report
    global $myStorereport;
    global $myStorereportRecord;
    //global $storereportEx;
    //production order
    global $productionorder;
    global $productionorderDAO;
    global $productionorderEX;

    //Productionrate
    global $productionrate;
    global $productionrateDAO;
    global $productionrateEX;

    //Productionrateproduct
    global $Productionrateproduct;
    global $ProductionrateproductDAO;

    $productId = $_POST['productId'];
    $unitId = $_POST['unitId'];
    $productQuantity = $_POST['productQuantity'];
    $store = $_POST['store'];
    $cost = $_POST['cost'];

    $id = $_POST['id'];
    print_r("id=" . $id);
    $productionOrderData = $productionorderDAO->load($id);

    $damagedProduct->productId = $productId;
    $damagedProduct->measurUnitId = $unitId;

    $damagedProduct->productQuantity = $productQuantity;
    $damagedProduct->storeId = $store;
    $damagedProduct->cost = $cost;

    $damagedProduct->operationDate = date("Y-m-d");
    $damagedProduct->userID = $_SESSION['userid'];
    $damagedProduct->productionOrderId = $id;

    //insert in damaged Product table
    $modelId = $damagedProductDAO->insert($damagedProduct);

    /* ------------------------  خصم المواد الخام للمنتج التالف من المخزن ----------------- */
    $productionrate = $productionrateEX->queryOneRateByfinalName($productionOrderData->productId);
    $Productionrateproduct = $ProductionrateproductDAO->queryByProductionRateId($productionrate->productionRateId);
    print_r($productionrate);

    $i = 0;
    foreach ($Productionrateproduct as $p) {

        $productId = $Productionrateproduct[$i]->productId;
        print_r("</br>productId = " . $productId . "</br>");


        $quantity = $Productionrateproduct[$i]->quantity;
        print_r("</br>productQuantity = " . $quantity . "</br>");

        print_r("</br>productQuantity = " . $productQuantity . "</br>");

        $unitId = $Productionrateproduct[$i]->unitId;
        $productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
        $myproductNumber = $productunitData->productnumber;

        $storeValue = $quantity * $productQuantity * $myproductNumber;
        print_r("</br>storeValue = " . $storeValue . "</br>");

        $storedetailData = getStoredetailData($store, $productId);
        $productquantityBefore = $storedetailData[2];

        print_r("</br>productquantityBefore = " . $productquantityBefore . "</br>");
        //-------------------------update in storedetail tbl----------------------//
        $newQt = $productquantityBefore - $storeValue;

        print_r("</br>newQt = " . $newQt . "</br>");

        updateQuantityOfProduct($store, $productId, $newQt);



        /* ------------------------ insert in store report------------------------------------- */
        //get store productquantity before change
        $storedetailData = getStoredetailData($store, $productId);

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

        $productquantityAfter = $productquantityBefore - $storeValue;
        // print_r("productquantityAfter = ".$productquantityAfter);

        insertStorereport($productId, $store, $productQuantity, $productquantityBefore, $productquantityAfter, 1, $modelId, " اضافه منتج تالف", "damagedProductController.php");


        $i++;
    }
}

function updateQuantityOfProduct($storeid, $productid, $productChangeAmount) {
    global $storeDetailExt;

    $storeDetailExt->updateStoreDetails($storeid, $productid, $productChangeAmount);
}

//stop
function stop_active() {
    global $productionorder;
    global $productionorderDAO;

    $id = $_GET["id"];
    echo $id;
    $productionorder = $productionorderDAO->load($id);

    if ($productionorder->conditions == 0) {
        $productionorder->conditions = 1;
    } elseif ($productionorder->conditions == 1) {
        $productionorder->conditions = 0;
    }
    $productionorderDAO->update($productionorder);
}

function delete() {
    global $productionorder;
    global $productionorderDAO;
    global $productionrateEX;
    global $ProductionrateproductDAO;

    $productionorderid = $_GET["id"];
    $productionorder = $productionorderDAO->load($productionorderid);
    $FinalproductunitData = loadProductUnitWithProductAndUnit($productionorder->productId, $productionorder->measureUnitId);
    $Finalproductnumber = $FinalproductunitData->productnumber;
    //get final product
    $finalProductId = $productionorder->productId;
    $productionrate = $productionrateEX->queryOneRateByfinalName($finalProductId);

    $Productionrateproduct = $ProductionrateproductDAO->queryByProductionRateId($productionrate->productionRateId);

    $i = 0;
    foreach ($Productionrateproduct as $p) {
        //get product before
        $productId = $Productionrateproduct[$i]->productId;

        $productunitData = loadProductUnitWithProductAndUnit($productId, $Productionrateproduct[$i]->unitId);
        $productnumber = $productunitData->productnumber;

        $finalquantity = $productionorder->outQuantity * $productnumber * $Finalproductnumber * $Productionrateproduct[$i]->quantity;

        if (isset($finalProductId) && $finalProductId != '-1' && $finalProductId != "") {
            //get store productquantity before change
            $storeDetailData = getStoreDetails($productionorder->storeId, $productId);

            $allStoredetailData = $storeDetailData[0];
            $storeDetailId = $storeDetailData[1];
            $productQuantityBefore = $storeDetailData[2];


            if (count($allStoredetailData) > 0) {
                //update productquantity in storedetail
                $productQuantityAfter = increaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity);

                //insert in storereport
                insertStorereport($productId, $productionorder->storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 0, $productionorder->productionOrderid, " حذف امر انتاج", "productionOrderController.php");
            } else {

                //insert in storedetail tbl
                insertStoredetail($storeId, $productId, $finalquantity);

                //insert in storereport
                insertStorereport($productId, $productionorder->storeId, $finalquantity, 0, $finalquantity, 0, $productionorder->productionOrderid, " حذف امر انتاج", "productionOrderController.php");
            }
        }
        $i++;
    }

    //delete a complete productionorder
    $productionorderDAO->delete($productionorderid);
}

function getRawMaterialsAndTotalCostOfIt($myfinalProductId, $myunitId, $myOutQuantity) {
    //recieve variables
    $finalProductId = $myfinalProductId;
    $unitId = $myunitId;
    $OutQuantity = $myOutQuantity;
    //globals
    global $productionrateEX;
    global $ProductionrateproductEX;
    global $productunitData;

    //get final product $productnumber
    $finalproductId = $myfinalProductId;
    $finalunitId = $myunitId;
    $finalproductunitData = loadProductUnitWithProductAndUnit($finalproductId, $finalunitId);
    $productnumberOfFinal = $finalproductunitData->productnumber;

    //get final product
    $productionrate = $productionrateEX->queryOneRateByfinalName($finalProductId);

    //get raw materials  productionRateId
    $Productionrateproduct = $ProductionrateproductEX->queryAllByProductionRateId($productionrate->productionRateId);
    /* print_r("<pre>");
      print_r($Productionrateproduct);
      print_r("</pre>"); */
    //total cost of raw materials
    $totalCostOfRawMaterials = 0;
    foreach ($Productionrateproduct as $p) {
        $productId = $p->productId;
        $unitId = $p->unitId;
        $productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
        $productnumber = $productunitData->productnumber;

        $p->conditions = $OutQuantity * $productnumberOfFinal * $p->quantity/* $productnumber */; //total quantity

        /* print_r("productId=".$productId);
          print_r("</br>");
          print_r("OutQuantity=".$OutQuantity);
          print_r("</br>");
          print_r("productnumberOfFinal=".$productnumberOfFinal);
          print_r("</br>");
          print_r("pquantity=".$p->quantity);
          print_r("</br>");
          print_r("total quantity=".$p->conditions);
          print_r("</br>");
          print_r("</br>"); */

        $p->userId = $p->conditions * $p->productBuyPrice * $productnumber; //cost
        $totalCostOfRawMaterials+=$p->userId;
    }

    //$totalCostOfRawMaterials = array($totalCostOfRawMaterials);
    return array($Productionrateproduct/* all raw materials */, $totalCostOfRawMaterials/* total cost */);
    /* $p->conditions is total quantity *//* $p->userId is cost */
}

function getuniqueArrayAndTotal($OnelevelArray, $type/* 1 for wokers  2  for assets */) {
    global $myProductunitEx;

    global $productunit;

    $UniqueArray = array();
    $totalcost = 0;
    $IdSArray = array();
    if ($type == 1) {
        foreach ($OnelevelArray as $myOnelevelArray) {

            $totalcost+=$myOnelevelArray->Hourlyrate * $myOnelevelArray->settingOperationrealTime;
            if (!in_array($myOnelevelArray->employeeid, $IdSArray, TRUE)) {
                $myOnelevelArray->workstationid = $myOnelevelArray->settingOperationrealTime;
                array_push($IdSArray, $myOnelevelArray->employeeid);
                array_push($UniqueArray, $myOnelevelArray);
            } else {
                foreach ($UniqueArray as $u) {
                    if ($u->employeeid == $myOnelevelArray->employeeid) {
                        $u->workstationid+=$myOnelevelArray->settingOperationrealTime;
                    }
                }
            }
        }
    } elseif ($type == 11) {
        foreach ($OnelevelArray as $myOnelevelArray) {

            $totalcost+=$myOnelevelArray->Hourlyrate * $myOnelevelArray->settingOperationrealTime;
            if (!in_array($myOnelevelArray->employeeid, $IdSArray, TRUE)) {
                //no need for it
                //$myOnelevelArray->workstationid=$myOnelevelArray->workstationid;
                array_push($IdSArray, $myOnelevelArray->employeeid);
                array_push($UniqueArray, $myOnelevelArray);
            } else {
                foreach ($UniqueArray as $u) {
                    if ($u->employeeid == $myOnelevelArray->employeeid) {
                        $u->workstationid+=$myOnelevelArray->workstationid;
                    }
                }
            }
        }
    } elseif ($type == 2) {
        foreach ($OnelevelArray as $myOnelevelArray) {
            $totalcost+=$myOnelevelArray->Hourlyrate * $myOnelevelArray->settingOperationrealTime;
            if (!in_array($myOnelevelArray->assetsId, $IdSArray, TRUE)) {
                $myOnelevelArray->workstationid = $myOnelevelArray->settingOperationrealTime;
                array_push($IdSArray, $myOnelevelArray->assetsId);
                array_push($UniqueArray, $myOnelevelArray);
            } else {
                foreach ($UniqueArray as $u) {
                    if ($u->assetsId == $myOnelevelArray->assetsId) {
                        $u->workstationid+=$myOnelevelArray->settingOperationrealTime;
                    }
                }
            }
        }
    } elseif ($type == 22) {
        foreach ($OnelevelArray as $myOnelevelArray) {
            $totalcost+=$myOnelevelArray->Hourlyrate * $myOnelevelArray->settingOperationrealTime;
            if (!in_array($myOnelevelArray->assetsId, $IdSArray, TRUE)) {
                //no need for it
                //$myOnelevelArray->workstationid=$myOnelevelArray->workstationid;
                array_push($IdSArray, $myOnelevelArray->assetsId);
                array_push($UniqueArray, $myOnelevelArray);
            } else {
                foreach ($UniqueArray as $u) {
                    if ($u->assetsId == $myOnelevelArray->assetsId) {
                        $u->workstationid+=$myOnelevelArray->workstationid;
                    }
                }
            }
        }
    } elseif ($type == 3) {
        foreach ($OnelevelArray as $myOnelevelArray) {
            //no need for sum here
            //$totalcost+=$myOnelevelArray->Hourlyrate*$myOnelevelArray->settingOperationrealTime;
            $totalcost = 0; //just to return a value

            $productId = $myOnelevelArray->productId;
            $unitId = $myOnelevelArray->unitId;
            $productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
            $productnumber = $productunitData->productnumber;

            $productunit = $myProductunitEx->getMaxUnitOfAProduct($productId);

            if (!in_array($myOnelevelArray->productId, $IdSArray, TRUE)) {
                //for the first time total quantity,cost will be initialized
                $myOnelevelArray->conditions = ($myOnelevelArray->conditions * $productnumber) / $productunit->productnumber; //total quantity
                $myOnelevelArray->unitid = $productunit->unitid;
                $myOnelevelArray->unitName = $productunit->unitName;
                //$myOnelevelArray->userId;//cost
                array_push($IdSArray, $myOnelevelArray->productId);
                array_push($UniqueArray, $myOnelevelArray);
            } else {
                foreach ($UniqueArray as $u) {
                    if ($u->productId == $myOnelevelArray->productId) {


                        $u->conditions+=($myOnelevelArray->conditions * $productnumber) / $productunit->productnumber;
                        $u->userId+=$myOnelevelArray->userId;
                    }
                }
            }
        }
    }
    return array($UniqueArray, $totalcost);
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// get productquantity from storedetail tbl
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) {

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

    //increase productquantity
    $productquantityAfter = $productquantityBefore - $productChangeAmount;

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

    $myStoredetailEx->updateProductquantity($myStoredetail);

    return $productquantityAfter;
}

//update and increase productquantity in storedetail tbl
function increaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount) {
    global $storeDetail;
    global $storeDetailExt;

    //increase productquantity
    $productquantityAfter = $productquantityBefore + $productChangeAmount;

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

    $storeDetailExt->updateProductquantity($storeDetail);

    return $productquantityAfter;
}

//add in Storemovement tbl
function insertStorereport($productid, $storeid, $productChangeAmount, $productbefore, $productafter, $storereporttype, $storereportmodelid, $processname, $tablename) {
    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'];

    $myStorereportRecord->insert($myStorereport);
}

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

    global $myStoredetail;
    global $myStoredetailRecord;

    $myStoredetail->userid = $_SESSION['userid'];
    $myStoredetail->storedetaildate = date("Y-m-d");
    $myStoredetail->productquantity = $productChangeAmount;
    $myStoredetail->storeid = $storeid;
    $myStoredetail->productid = $productid;

    $myStoredetailRecord->insert($myStoredetail);
}

function loadProductUnitWithProductAndUnit($productId, $unitId) {

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

    // select all data from productunit tbl
    $productunitData = $myProductunitEx->queryWithProductIdAndUnitId($productId, $unitId);

    return $productunitData;
}

function getStoreDetails($storeId, $productId) {
    // get productquantity from storedetail tbl
    global $storeDetailExt;

    //select data from storedetails by storeid and productid
    $storeDetailData = $storeDetailExt->queryWithStoreAndProduct($productId, $storeId);

    $storeDetailId = $storeDetailData->storedetailid;
    $productQuantityBefore = $storeDetailData->productquantity;

    return array($storeDetailData, $storeDetailId, $productQuantityBefore);
}

?>