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

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

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

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

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

//
require_once('../models/dao/ProductionoutDAO.class.php');
require_once('../models/dto/Productionout.class.php');
require_once('../models/mysql/ProductionoutMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionoutMySqlExtDAO.class.php');
//
require_once('../models/dao/ProductionoutdetailsDAO.class.php');
require_once('../models/dto/Productionoutdetail.class.php');
require_once('../models/mysql/ProductionoutdetailsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionoutdetailsMySqlExtDAO.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');
//Supplier
require_once('../models/dao/SupplierDAO.class.php');
require_once('../models/dto/Supplier.class.php');
require_once('../models/mysql/SupplierMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierMySqlExtDAO.class.php');
//Supplierdebtchange
require_once('../models/dao/SupplierdebtchangeDAO.class.php');
require_once('../models/dto/Supplierdebtchange.class.php');
require_once('../models/mysql/SupplierdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierdebtchangeMySqlExtDAO.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();

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

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

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

//
$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();
//Productionout
$productionOut = new Productionout();
$productionOutDAO = new ProductionoutMySqlDAO();
$productionOutEX = new ProductionoutMySqlExtDAO();
//Productionoutdetail
$productionOutDetail = new Productionoutdetail();
$productionOutDetailDAO = new ProductionoutdetailsMySqlDAO();
$productionOutDetailEX = new ProductionoutdetailsMySqlExtDAO();
//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();
//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//Supplierdebtchange
$supplierDebtChange = new Supplierdebtchange();
$supplierDebtChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDebtChangeExt = new SupplierdebtchangeMySqlExtDAO();
//
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingEX = new ProgramsettingsMySqlExtDAO();

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

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

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

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

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

    $smarty->assign("customProductionOut", 1);
    $smarty->display("productionOutView/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 == "edit") {


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

    $id = (int) $_GET["id"];

    $productionOut = $productionOutEX->queryAllExt(" and productionout.id = $id");
    $productionOut = $productionOut[0];
    if (!$productionOut) {
        header('location:productionOutController.php?do=show');
    }
    $productionOut->productName = $productionOut->productName . '/ ' . $productionOut->productCatName;
    if (!empty($productionOut->sizeid) && !empty($productionOut->colorid)) {
        $productionOut->productid = "hasSizeColor" . $productionOut->productid . "-" . $productionOut->sizeid . "-" . $productionOut->colorid;
        $productionOut->productName .= '/ ' . $productionOut->sizeName . '/ ' . $productionOut->colorName;
    }
    $smarty->assign('productionOutData', $productionOut);
    //products in
    $allProductionOutDetail = $productionOutDetailEX->queryByProductionOutIdEX($id);
    foreach ($allProductionOutDetail 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('allProductionOutDetail', $allProductionOutDetail);

    //services
    $allServiceDetail = R::getAll('SELECT productionservicedetail.*,product.productName,productcat.productCatName,supplier.suppliername, store.storeName 
                FROM productionservicedetail
                left JOIN product	ON product.productId = productionservicedetail.productid
                left JOIN productcat ON product.productCatId = productcat.productCatId
                left JOIN supplier ON supplier.supplierid = productionservicedetail.supplierid
                left JOIN store ON store.storeId = productionservicedetail.storeid
                WHERE productionoutid = ?', [$id]);
    $dataArr = [];
    foreach ($allServiceDetail as $p) {
        $p['productName'] = $p['productName'] . '/ ' . $p['productCatName'];
        $dataArr[] = $p;
    }
    $smarty->assign('allServiceDetail', $dataArr);

    $smarty->assign("customProductionOut", 1);
    $smarty->display("productionOutView/edit.html");
//print_r($Productionrateproduct->conditions);
} elseif ($do == "update") {
    try {
        delete();
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
//echo $e;
        header("location:?do=error");
    }
} elseif ($do == "show") {

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


    $outStore = (int) filter_input(INPUT_POST, 'outStore');
    $inStore = (int) filter_input(INPUT_POST, 'inStore');
    $supplier = (int) filter_input(INPUT_POST, 'supplier');
    $productId = (int) filter_input(INPUT_POST, 'productOut');
    $from = filter_input(INPUT_POST, 'from');
    $to = filter_input(INPUT_POST, 'to');
    $outId = (int) filter_input(INPUT_POST, 'outId');

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

    $query = " and productionout.del=0 ";
    if (!empty($outStore) && $outStore > 0)
        $query .= " and productionout.outStore = $outStore ";
    if (!empty($inStore) && $inStore > 0)
        $query .= " and productionout.inStore = $inStore ";
    if (!empty($supplier) && $supplier > 0)
        $query .= " and productionout.supplier = $supplier ";
    if (!empty($productId) && $productId > 0)
        $query .= " and productionout.productid = $productId and productionout.sizeid=$sizeId and productionout.colorid = $colorId ";
    if (!empty($from))
        $query .= " and date(productionout.sysDate) >= '$from' ";

    if (!empty($to))
        $query .= " and date(productionout.sysDate) <= '$to' ";

    if (!empty($outId) && $outId > 0)
        $query .= " and productionout.id = $outId";

    if ($query == " and productionout.del=0 ") {
        $from = $to = date('Y-m-d');
        $query .= " and date(productionout.sysDate) >= '$from' and date(productionout.sysDate) <= '$to' ";
    }
    $allProductionOut = $productionOutEX->queryAllExt($query);
    $smarty->assign("allProductionOut", $allProductionOut);

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

    $smarty->assign("customProductionOut", 1);
    $smarty->display("productionOutView/show.html");
} 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 $productionOutDAO;
    global $productionOutEX;

    global $productionOutDetailDAO;
    global $productionOutDetailEX;

    global $productExt;
    global $myProductunitEx;
    global $supplierDAO;

    //Transaction
    $mytransactions = new Transaction();
    try {
        ## out product
        $id = (int) filter_input(INPUT_POST, 'id');
        $outStore = (int) filter_input(INPUT_POST, 'outStore');
        $inStore = (int) filter_input(INPUT_POST, 'inStore');
        $supplier = (int) filter_input(INPUT_POST, 'supplier');
        $comment = filter_input(INPUT_POST, 'comment');
        $outAllCostTot = (float) filter_input(INPUT_POST, 'outAllCostTot_h');

        $productId = $outProductId = filter_input(INPUT_POST, 'productOut');
        $sizeId = 0;
        $colorId = 0;
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productId = $outProductId = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
        }
        $outQuantity = (float) filter_input(INPUT_POST, 'outQuantity');
        $outUnitCost = (float) filter_input(INPUT_POST, 'outUnitCost');
        $outAllCost = $outQuantity * $outUnitCost;

        $productionOut->outStore = $outStore;
        $productionOut->inStore = $inStore;
        $productionOut->supplier = $supplier;
        $productionOut->productid = $productId;
        $productionOut->sizeid = $sizeId;
        $productionOut->colorid = $colorId;
        $productionOut->outQuantity = $outQuantity;
        $productionOut->outUnitCost = $outUnitCost;
        $productionOut->outAllCostTot = $outAllCostTot;
        $productionOut->outAllCost = $outAllCost;
        $productionOut->comment = $comment;
        $productionOut->userid = $_SESSION['userid'];
        $productionOut->del = 0;
        $productionOut->sysDate = date('Y-m-d H:i:s');
        if (empty($id)) {
            $id = $productionOutDAO->insert($productionOut);
        } else {
            $productionOut->id = $id;
            $id = $productionOutEX->insertWithId($productionOut);
        }


        increase($productId, $sizeId, $colorId, $outQuantity, $id, $outStore);


        ##in products
        $productItr = (int) filter_input(INPUT_POST, 'inProItr');
        $totalInProductsCost = 0;
        for ($i = 1; $i <= $productItr; $i++) {
            if (filter_input(INPUT_POST, 'product' . $i)) {
                $detailid = (int) filter_input(INPUT_POST, 'detailid' . $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];
                }
                $unitId = (int) filter_input(INPUT_POST, 'unitId' . $i); //id at productunit table
                $price = (float) filter_input(INPUT_POST, 'price' . $i);
                $quantity = (float) filter_input(INPUT_POST, 'quantity' . $i);
                $inTotalCost = $price * $quantity;

                $productunitData = $myProductunitEx->queryWithProductIdAndUnitId($productId, $unitId);
                $finalquantity = $quantity * $productunitData->productnumber;

                $productionOutDetail->productionOutId = $id;
                $productionOutDetail->productid = $productId;
                $productionOutDetail->sizeid = $sizeId;
                $productionOutDetail->colorid = $colorId;
                $productionOutDetail->unitid = $unitId;
                $productionOutDetail->price = $price;
                $productionOutDetail->quantity = $quantity;
                $productionOutDetail->inTotalCost = $inTotalCost;
                if (empty($detailid)) {
                    $productionOutDetailDAO->insert($productionOutDetail);
                } else {
                    $productionOutDetail->id = $detailid;
                    $productionOutDetailEX->insertWithId($productionOutDetail);
                }


                decrease($productId, $sizeId, $colorId, $finalquantity, $id, $inStore);
                $totalInProductsCost += $inTotalCost;
            }
        }

        ##services products
        $serviceItr = (int) filter_input(INPUT_POST, 'serviceProItr');
        $totalServiceProductsCost = 0;
        for ($i = 1; $i <= $serviceItr; $i++) {
            if (filter_input(INPUT_POST, 'service' . $i)) {
                $servicedetailid = (int) filter_input(INPUT_POST, 'servicedetailid' . $i);
                $productId = filter_input(INPUT_POST, 'service' . $i);
                $supplierId = (int) filter_input(INPUT_POST, 'supplierService' . $i);
                $price = (float) filter_input(INPUT_POST, 'priceservice' . $i);
                $quantity = (float) filter_input(INPUT_POST, 'quantityService' . $i);
                $storeId = (int) filter_input(INPUT_POST, 'storeId' . $i);
                $deliverService = (int) filter_input(INPUT_POST, 'deliverService' . $i);
                $receiveService = (int) filter_input(INPUT_POST, 'receiveService' . $i);
                $serviceTotalCost = $price * $quantity;

                $finalquantity = $quantity;
                $details = R::dispense('productionservicedetail');
                $details->productionoutid = $id;
                $details->productid = $productId;
                $details->supplierid = $supplierId;
                $details->price = $price;
                $details->quantity = $quantity;
                $details->totalcost = $serviceTotalCost;
                $details->storeid = $storeId;
                $details->deliverservice = $deliverService;
                $details->receiveservice = $receiveService;
                // if ($servicedetailid && $servicedetailid > 0) {
                //     $details->id = $servicedetailid;
                // }
                
                R::store($details);
                $totalServiceProductsCost += $serviceTotalCost;
            }
        }

        ##update out pro data in buypricehistorybook , all buy prices
//        $outProductPrice = ($totalInProductsCost + $outAllCost) / $outQuantity;
        $outProductPrice = $outAllCostTot;
        //$newMeanBuyPrice = calcMeanBuyPrice($productId, $outQuantity, $outAllCost, $rowData->meanbuyprice);
        increaseBuyPricesHistoryBookBuyQuantity(date('Y-m-d'), $outStore, $outProductId, 0, 0, $outProductPrice, $outQuantity);
        $productExt->updateQueryString("update product set productBuyPrice=$outProductPrice,lastbuyprice=$outProductPrice,lastbuyprice_withDiscount=$outProductPrice,meanbuyprice=$outProductPrice,meanbuyprice_withDiscount=$outProductPrice where productId=$outProductId");
        $productExt->updateQueryString("UPDATE productunit SET proUnitBuyPrice = productnumber*$outProductPrice WHERE productid=$outProductId");

        ##supplier
        //update supplierdebt
        $supdata = $supplierDAO->load($supplier); // رصيد المورد
        $totaldeptbefore = $supdata->suppliercurrentDebt;
        $totaldeptafter = $totaldeptbefore + $outAllCost;
        updateSupplierDebt($supplier, $totaldeptafter);
        insertSupplierDebtChange($supplier, $totaldeptbefore, $outAllCost, 0, "تصنيع مبسط لمنتج", $id, $totaldeptafter, "productionOutController.php", $comment);
        //commit
        $mytransactions->commit();
        doInventoryDailyEntry($productionOut);
    } catch (Exception $e) {
        $mytransactions->rollback($e);
        //echo $e;
    }
}

function delete() {
    global $productionOutDAO;
    global $productionOutDetailDAO;

    global $productExt;
    global $myProductunitEx;
    global $supplierDAO;

    //Transaction
    $mytransactions = new Transaction();
    try {
        ## out product
        $id = (int) $_REQUEST['id'];
        $productionOut = $productionOutDAO->load($id);
        $outAllCost = $productionOut->outAllCost;
        decrease($productionOut->productid, $productionOut->sizeid, $productionOut->colorid, $productionOut->outQuantity, $id, $productionOut->outStore);
        $productionOutDAO->delete($id);

        ##in products
        $allProductionOutDetail = $productionOutDetailDAO->queryByProductionOutId($id);
        $totalInProductsCost = 0;
        foreach ($allProductionOutDetail as $p) {
            $totalInProductsCost += $p->inTotalCost;

            $productunitData = $myProductunitEx->queryWithProductIdAndUnitId($p->productid, $p->unitid);
            $finalquantity = $p->quantity * $productunitData->productnumber;
            increase($p->productid, $p->sizeid, $p->colorid, $finalquantity, $id, $productionOut->inStore);
            $productionOutDetailDAO->delete($p->id);
        }

        //services
        $allServiceDetail = R::getAll('SELECT productionservicedetail.*,product.productName,productcat.productCatName,supplier.suppliername 
                FROM productionservicedetail
                left JOIN product	ON product.productId = productionservicedetail.productid
                left JOIN productcat ON product.productCatId = productcat.productCatId
                left JOIN supplier ON supplier.supplierid = productionservicedetail.supplierid
                WHERE productionoutid = ?', [$id]);
        $totalServiceProductsCost = 0;
        foreach ($allServiceDetail as $p) {
            $totalServiceProductsCost += $p['totalcost'];
             R::exec('DELETE FROM productionservicedetail WHERE id = ?', [$p['id']]);
        }
        ##update out pro data in buypricehistorybook , all buy prices
        ##supplier
        //update supplierdebt
        $supdata = $supplierDAO->load($productionOut->supplier); // رصيد المورد
        $totaldeptbefore = $supdata->suppliercurrentDebt;
        $totaldeptafter = $totaldeptbefore - $outAllCost;
        updateSupplierDebt($productionOut->supplier, $totaldeptafter);
        insertSupplierDebtChange($productionOut->supplier, $totaldeptbefore, $outAllCost, 1, "حذف تصنيع مبسط لمنتج", $id, $totaldeptafter, "productionOutController.php", "");
        //commit
        $mytransactions->commit();
        reverseEntryWithItsID($productionOut->dailyentryid);
    } catch (Exception $e) {
        $mytransactions->rollback($e);
        echo $e;
    }
}

function decrease($productId, $sizeId, $colorId, $finalquantity, $sellbillId, $sellbillstoreId = 0, $type = "") {
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;


    $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($storedetailData->productid, 1, $sizeId, $colorId);
            $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

            $sizeColorStoreDetail->storeid = $storedetailData->storeid;
            $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;

    $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($storedetailData->productid, 1, $sizeId, $colorId);
            $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

            $sizeColorStoreDetail->storeid = $storedetailData->storeid;
            $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;
    $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 updateSupplierDebt($supplierId, $supplierDebtAfter) {
    global $supplier;
    global $supplierExt;
    global $today;

    //update clientdebt in client tbl
    $supplier->userid = $_SESSION['userid'];
    $supplier->suppliercurrentDebt = $supplierDebtAfter;
    $supplier->supplierid = $supplierId;
    $supplier->supplierdate = date('Y-m-d');

    $supplierExt->updatedept($supplier);
}

// insert data into Clientdebtchange tbl

function insertSupplierDebtChange($supplierId, $supplierDebtChangeBefore, $supplierDebtChangeAmount, $supplierDebtChangeType, $processname, $supplierDebtChangeModelId, $supplierDebtChangeAfter, $tablename, $comment) {
    global $supplierDebtChange;
    global $supplierDebtChangeDAO;
    global $today;

    $supplierDebtChange->comment = $comment;
    $supplierDebtChange->processname = $processname;
    $supplierDebtChange->supplierdebtchangeafter = $supplierDebtChangeAfter;
    $supplierDebtChange->supplierdebtchangeamount = $supplierDebtChangeAmount;
    $supplierDebtChange->supplierdebtchangebefore = $supplierDebtChangeBefore;
    $supplierDebtChange->supplierdebtchangedate = date('Y-m-d H:i:s');
    $supplierDebtChange->supplierdebtchangemodelid = $supplierDebtChangeModelId;
    $supplierDebtChange->supplierdebtchangetype = $supplierDebtChangeType;
    $supplierDebtChange->supplierid = $supplierId;
    $supplierDebtChange->tablename = $tablename;
    $supplierDebtChange->userid = $_SESSION['userid'];
    $supplierDebtChange->dailyentryid = 0;

    $supplierDebtChangeDAO->insert($supplierDebtChange);
}

function doInventoryDailyEntry($productionOut) {
    global $ProgramsettingEX;

//    if ($productionOut->outStore != $productionOut->inStore) {
    ## 1- get needed data
    $rawMaterialCost = R::getCell('select sum(inTotalCost) from productionoutdetails where productionOutId=' . $productionOut->id);
    $productName = R::getCell('select productName from product where productId=' . $productionOut->productid);
    $treeIdInStore = R::getCell('select treeId from store where storeId=' . $productionOut->inStore);
    $treeIdOutStore = R::getCell('select treeId from store where storeId=' . $productionOut->outStore);
    $suppData = R::getRow('select treeId,suppliername from supplier where supplierid=' . $productionOut->supplier);

    ## 2- do entry
    $dailyEntry->entryComment = 'تصنيع مبسط ' . $productName . ' و المورد ' . $suppData['suppliername'] . '';
    $dailyEntry->reverseofid = 0;

    $dailyEntryDebtorArray = array();
    $dailyEntryDebtor->accountstreeid = $treeIdOutStore;
    $dailyEntryDebtor->value = $rawMaterialCost;
    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
    $dailyEntryDebtor = new stdClass();
    $dailyEntryDebtor->accountstreeid = $suppData['treeId'];
    $dailyEntryDebtor->value = $productionOut->outAllCost;

    $dailyEntryCreditorArray = array();
    $dailyEntryCreditor->value = $rawMaterialCost + $productionOut->outAllCost;
    $dailyEntryCreditor->accountstreeid = $treeIdInStore;

    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
    $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $productionOut->id, 'productionOutController.php?do=edit&id= ' . $productionOut->id);
    $did = $returnedData[1];
    $ProgramsettingEX->runSqlQuery('update productionout set dailyentryid = ' . $did . ' where id=' . $productionOut->id);
    return $did;
//    }
}

?>