<?php

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


//global varable
global $showoutside;

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

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

//Buybill
require_once('../models/dao/BuybillDAO.class.php');
require_once('../models/dto/Buybill.class.php');
require_once('../models/mysql/BuybillMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybillMySqlExtDAO.class.php');
//Buybilldetail
require_once('../models/dao/BuybilldetailDAO.class.php');
require_once('../models/dto/Buybilldetail.class.php');
require_once('../models/mysql/BuybilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybilldetailMySqlExtDAO.class.php');
//Returnbuybill
require_once('../models/dao/ReturnbuybillDAO.class.php');
require_once('../models/dto/Returnbuybill.class.php');
require_once('../models/mysql/ReturnbuybillMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybillMySqlExtDAO.class.php');
//Returnbuybilldetail
require_once('../models/dao/ReturnbuybilldetailDAO.class.php');
require_once('../models/dto/Returnbuybilldetail.class.php');
require_once('../models/mysql/ReturnbuybilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybilldetailMySqlExtDAO.class.php');
//Buyandruternbill
require_once('../models/dao/BuyandruternbillDAO.class.php');
require_once('../models/dto/Buyandruternbill.class.php');
require_once('../models/mysql/BuyandruternbillMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbillMySqlExtDAO.class.php');
//Buyandruternbilldetail
require_once('../models/dao/BuyandruternbilldetailDAO.class.php');
require_once('../models/dto/Buyandruternbilldetail.class.php');
require_once('../models/mysql/BuyandruternbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbilldetailMySqlExtDAO.class.php');
//Buyandruternbillcurr
require_once('../models/dao/BuyandruternbillcurrDAO.class.php');
require_once('../models/dto/Buyandruternbillcurr.class.php');
require_once('../models/mysql/BuyandruternbillcurrMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbillcurrMySqlExtDAO.class.php');
//Buybillcurr
require_once('../models/dao/BuybillcurrDAO.class.php');
require_once('../models/dto/Buybillcurr.class.php');
require_once('../models/mysql/BuybillcurrMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybillcurrMySqlExtDAO.class.php');
//Returnbuybillcurr
require_once('../models/dao/ReturnbuybillcurrDAO.class.php');
require_once('../models/dto/Returnbuybillcurr.class.php');
require_once('../models/mysql/ReturnbuybillcurrMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybillcurrMySqlExtDAO.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');
//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');
//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');
//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');
//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');
//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');
//Billname
require_once('../models/dao/BillnameDAO.class.php');
require_once('../models/dto/Billname.class.php');
require_once('../models/mysql/BillnameMySqlDAO.class.php');
require_once('../models/mysql/ext/BillnameMySqlExtDAO.class.php');
//Billsetting
require_once('../models/dao/BillsettingsDAO.class.php');
require_once('../models/dto/Billsetting.class.php');
require_once('../models/mysql/BillsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsettingsMySqlExtDAO.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');
//Save
require_once('../models/dao/SaveDAO.class.php');
require_once('../models/dto/Save.class.php');
require_once('../models/mysql/SaveMySqlDAO.class.php');
require_once('../models/mysql/ext/SaveMySqlExtDAO.class.php');
//Savedaily
require_once('../models/dao/SavedailyDAO.class.php');
require_once('../models/dto/Savedaily.class.php');
require_once('../models/mysql/SavedailyMySqlDAO.class.php');
require_once('../models/mysql/ext/SavedailyMySqlExtDAO.class.php');
//Productserial
require_once('../models/dao/ProductserialDAO.class.php');
require_once('../models/dto/Productserial.class.php');
require_once('../models/mysql/ProductserialMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductserialMySqlExtDAO.class.php');
//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');

//user
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.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');

//Entryproductspurchased
require_once('../models/dao/EntryproductspurchasedDAO.class.php');
require_once('../models/dto/Entryproductspurchased.class.php');
require_once('../models/mysql/EntryproductspurchasedMySqlDAO.class.php');
require_once('../models/mysql/ext/EntryproductspurchasedMySqlExtDAO.class.php');


require_once('../models/dao/CostcenterDAO.class.php');
require_once('../models/dto/Costcenter.class.php');
require_once('../models/mysql/CostcenterMySqlDAO.class.php');
require_once('../models/mysql/ext/CostcenterMySqlExtDAO.class.php');

require_once('../models/dao/CostcenterdetailDAO.class.php');
require_once('../models/dto/Costcenterdetail.class.php');
require_once('../models/mysql/CostcenterdetailMySqlDAO.class.php');
require_once('../models/mysql/ext/CostcenterdetailMySqlExtDAO.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');

//
require_once('../models/dao/SizecolorDAO.class.php');
require_once('../models/dto/Sizecolor.class.php');
require_once('../models/mysql/SizecolorMySqlDAO.class.php');
require_once('../models/mysql/ext/SizecolorMySqlExtDAO.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');
//Currency
require_once('../models/dao/CurrencyDAO.class.php');
require_once('../models/dto/Currency.class.php');
require_once('../models/mysql/CurrencyMySqlDAO.class.php');
require_once('../models/mysql/ext/CurrencyMySqlExtDAO.class.php');
//Buybilloffer
require_once('../models/dao/BuybillofferDAO.class.php');
require_once('../models/dto/Buybilloffer.class.php');
require_once('../models/mysql/BuybillofferMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybillofferMySqlExtDAO.class.php');
//Buybilldetailoffer
require_once('../models/dao/BuybilldetailofferDAO.class.php');
require_once('../models/dto/Buybilldetailoffer.class.php');
require_once('../models/mysql/BuybilldetailofferMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybilldetailofferMySqlExtDAO.class.php');
//Client
require_once('../models/dao/ClientDAO.class.php');
require_once('../models/dto/Client.class.php');
require_once('../models/mysql/ClientMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientMySqlExtDAO.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'];


//lang
$lang = $_SESSION['erp_lang'];
include_once("../views/languages/$lang/buybill/buybill.php");
include_once("../views/languages/$lang/success.php");
include_once("../views/languages/$lang/error.php");

/* ======================

  Controller Name :- buyBillController

  OPERTATION in Controller

  1- add buy bill, buy And Return Bill and return buy bill
  2- show buy bill details
  3- show buy bills
  4- delete buy bill

  ======================== */



//handling saveid session
/* if(!isset($_SESSION['saveid']))
  {
  //$_SESSION['saveid'] = 1;
  } */


//here the global templates
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} else {
    $smarty->display("header.html");
}

//here goes the instances and general variables
//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

//Entryproductspurchased
$Entryproductspurchased = new Entryproductspurchased();
$EntryproductspurchasedDAO = new EntryproductspurchasedMySqlDAO();
$EntryproductspurchasedEX = new EntryproductspurchasedMySqlExtDAO();

//Productunit
$ProductunitDAO = new ProductunitMySqlDAO();
$myProductunitEx = new ProductunitMySqlExtDAO();


//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();


//Accountstree
$accountsTree2 = new Accountstree();
$accountsTreeDAO2 = new AccountstreeMySqlDAO();
$accountsTreeEX2 = new AccountstreeMySqlExtDAO();


//Dailyentry
$dailyEntry = new Dailyentry();
$dailyEntryDAO = new DailyentryMySqlDAO();
$dailyEntryEX = new DailyentryMySqlExtDAO();

//Dailyentrycreditor دائن
$dailyEntryCreditor = new Dailyentrycreditor();
$dailyEntryCreditorDAO = new DailyentrycreditorMySqlDAO();
$dailyEntryCreditorEX = new DailyentrycreditorMySqlExtDAO();


//Dailyentrycreditor دائن
$dailyEntryCreditor2 = new Dailyentrycreditor();
$dailyEntryCreditorDAO2 = new DailyentrycreditorMySqlDAO();
$dailyEntryCreditorEX2 = new DailyentrycreditorMySqlExtDAO();

//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();
$dailyEntryDebtorDAO = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX = new DailyentrydebtorMySqlExtDAO();

//Dailyentrydebtor مدين
$dailyEntryDebtor2 = new Dailyentrydebtor();
$dailyEntryDebtorDAO2 = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX2 = new DailyentrydebtorMySqlExtDAO();

//Buybill
$buyBill = new Buybill();
$buyBillDAO = new BuybillMySqlDAO();
$buyBillExt = new BuybillMySqlExtDAO();
//Buybilldetail
$buyBillDetail = new Buybilldetail();
$buyBillDetailDAO = new BuybilldetailMySqlDAO();
$buyBillDetailExt = new BuybilldetailMySqlExtDAO();
//Returnbuybill
$returnBuyBill = new Returnbuybill();
$returnBuyBillDAO = new ReturnbuybillMySqlDAO();
$returnBuyBillExt = new ReturnbuybillMySqlExtDAO();
//Returnbuybilldetail
$returnBuyBillDetail = new Returnbuybilldetail();
$returnBuyBillDetailDAO = new ReturnbuybilldetailMySqlDAO();
$returnBuyBillDetailExt = new ReturnbuybilldetailMySqlExtDAO();
//Buyandruternbill
$buyAndReturnBill = new Buyandruternbill();
$buyAndReturnBillDAO = new BuyandruternbillMySqlDAO();
$buyAndReturnBillExt = new BuyandruternbillMySqlExtDAO();
//Buyandruternbilldetail
$buyAndReturnBillDetail = new Buyandruternbilldetail();
$buyAndReturnBillDetailDAO = new BuyandruternbilldetailMySqlDAO();
$buyAndReturnBillDetailExt = new BuyandruternbilldetailMySqlExtDAO();
//Buyandruternbillcurr
$buyAndRuternBillCurr = new Buyandruternbillcurr();
$buyAndRuternBillCurrDAO = new BuyandruternbillcurrMySqlDAO();
$buyAndRuternBillCurrEX = new BuyandruternbillcurrMySqlExtDAO();
//Buybillcurr
$buyBillCurr = new Buybillcurr();
$buyBillCurrDAO = new BuybillcurrMySqlDAO();
$buyBillCurrEX = new BuybillcurrMySqlExtDAO();
//Returnbuybillcurr
$returnBuyBllCurr = new Returnbuybillcurr();
$returnBuyBllCurrDAO = new ReturnbuybillcurrMySqlDAO();
$returnBuyBllCurrEX = new ReturnbuybillcurrMySqlExtDAO();

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

//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();
//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();
//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//Supplierdebtchange
$supplierDebtChange = new Supplierdebtchange();
$supplierDebtChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDebtChangeExt = new SupplierdebtchangeMySqlExtDAO();
//Store
$storeDAO = new StoreMySqlDAO();
$storeExt = new StoreMySqlExtDAO();
//Programsetting
$programSettingExt = new ProgramsettingsMySqlExtDAO();
//Unit
$unitDAO = new UnitMySqlDAO();
$unitExt = new UnitMySqlExtDAO();
//Billname
$billNameDAO = new BillnameMySqlDAO();
$billNameExt = new BillnameMySqlExtDAO();
//Billsetting
$billSettingExt = new BillsettingsMySqlExtDAO();
//Storedetail
$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailExt = new StoredetailMySqlExtDAO();
//Storereport
$storeReport = new Storereport;
$storeReportDAO = new StorereportMySqlDAO();
$storeReportExt = new StorereportMySqlExtDAO();
//Save
$save = new Save();
$saveDAO = new SaveMySqlDAO();
$saveExt = new SaveMySqlExtDAO();
//Savedaily
$saveDaily = new Savedaily();
$saveDailyDAO = new SavedailyMySqlDAO();
$saveDailyExt = new SavedailyMySqlExtDAO();
//Productserial
$Productserial = $myProductserial = new Productserial();
$ProductserialDAO = new ProductserialMySqlDAO();
$ProductserialEX = $myProductserialEx = new ProductserialMySqlExtDAO();


$Costcenterdetail = new Costcenterdetail();
$CostcenterdetailDAO = new CostcenterdetailMySqlDAO();
$CostcenterdetailEX = new CostcenterdetailMySqlExtDAO();

//Costcenter
$Costcenter = new Costcenter();
$CostcenterDAO = new CostcenterMySqlDAO();
$CostcenterEX = new CostcenterMySqlExtDAO();

//save
$mySave = new Save();
$mySaveRecord = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();


$user = new User();
$userDAO = new UserMySqlDAO();
$userEX = new UserMySqlExtDAO();


//Usergroup
$Usergroup = new Usergroup();
$UsergroupDAO = new UsergroupMySqlDAO();
$UsergroupEX = new UsergroupMySqlExtDAO();

//
$sizeColor = new Sizecolor();
$sizeColorDAO = new SizecolorMySqlDAO();
$sizeColorEX = new SizecolorMySqlExtDAO();
//
$sizeColorStoreDetail = new Sizecolorstoredetail();
$sizeColorStoreDetailDAO = new SizecolorstoredetailMySqlDAO();
$sizeColorStoreDetailEX = new SizecolorstoredetailMySqlExtDAO();
//Buypriceshistorybook
$buyPricesHistoryBook = new Buypriceshistorybook();
$buyPricesHistoryBookDAO = new BuypriceshistorybookMySqlDAO();
$buyPricesHistoryBookEX = new BuypriceshistorybookMySqlExtDAO();


//Currency
$currency = new Currency();
$currencyDAO = new CurrencyMySqlDAO();
$currencyEX = new CurrencyMySqlExtDAO();

//Buybilloffer
$buyBillOffer = new Buybilloffer();
$buyBillOfferDAO = new BuybillofferMySqlDAO();
$buyBillOfferEX = new BuybillofferMySqlExtDAO();
//Buybilldetailoffer
$buyBillDetailOffer = new Buybilldetailoffer();
$buyBillDetailOfferDAO = new BuybilldetailofferMySqlDAO();
$buyBillDetailOfferEX = new BuybilldetailofferMySqlExtDAO();
//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();


$userdata = $userDAO->load($_SESSION['userid']);
$smarty->assign("userdata", $userdata);
$usergroup = $UsergroupDAO->load($_SESSION['usergroupid']);
$smarty->assign("usergroup", $usergroup);

//print_r($userdata);

include("buyBillfunction.php");
$today = date("Y-m-d H:i:s");
$smarty->assign("today", $today);

$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);
$noOfDecimalPlaces = ($Programsettingdata->roundnumbers == 0) ? 0 : (int) $Programsettingdata->noOfDecimalPlaces;
$smarty->assign("noOfDecimalPlaces", $noOfDecimalPlaces);
$smarty->assign("storenegative", $_SESSION['storenegative']);

/*
  print_r("<pre>");

  print_r($Programsettingdata);

  print_r("<pre>"); */

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

    $billNameData = getBuyBillNames();
    $smarty->assign("billNameData", $billNameData);

    $smarty->display("buyBillview/billType.html");
} elseif ($do == "bill") {
    include_once("../public/authentication.php");

    $billnameid = $_REQUEST['billnameid'];
    $smarty->assign("billnameid", $billnameid);
    if (!empty($billnameid)) {

        //in this case we have products to show from excel file
        if (isset($_SESSION['billFromExcel_' . $_SESSION['userid']]) && !empty($_SESSION['billFromExcel_' . $_SESSION['userid']])) {
            $productsAddedFromExcelArr = $_SESSION['billFromExcel_' . $_SESSION['userid']];
            $billFromExcel_date = $_SESSION['billFromExcel_date' . $_SESSION['userid']];
            $proIds = '';
            $countBillDetails = 0;
            foreach ($productsAddedFromExcelArr as $proid => $obj) {
                $proIds .= $proid . ',';
                $countBillDetails += $obj->quantity;
            }
            $proIds = rtrim($proIds, ',');
            //$buyBillDetails = $productExt->queryAllSimpleQueryString(" and productId in ($proIds) ");

            $i = 1;
            $buyBillDetails = array();
            foreach ($productsAddedFromExcelArr as $proid => $mydetales) {
                $productId = $mydetales->productid;
                $mydetales->parcode = $mydetales->excelparcode;
                $mydetales->buybilldetailproductid = $mydetales->productid;
                $mydetales->buybilldetailquantity = $mydetales->quantity;
                $mydetales->buybilldetailprice = $mydetales->price;
                $mydetales->buybilldetailtotalprice = $mydetales->buybilldetailquantity * $mydetales->buybilldetailprice;
                $mydetales->sizeid = $sizeId = $mydetales->sizeid;
                $mydetales->colorid = $colorId = $mydetales->colorid;
                $mydetales->otherdetailquantity = 0;

                $sizeColorStoreDetailId = 0;
                if ($sizeId > 0 && $colorId > 0) {
                    //$sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeId, $sizeId, $colorId);
                    $productData = $productExt->queryAllWithSizeColorData(" and product.productId = $productId and sizecolorstoredetail.sizeid=$sizeId and sizecolorstoredetail.colorid=$colorId ");
                    $mydetales->sizeName = $productData[0]->sizeName;
                    $mydetales->colorName = $productData[0]->colorName;
                } else {
                    $productData = $productExt->queryAllSimpleQueryString(" and productId = $productId ");
                    $mydetales->sizeName = '';
                    $mydetales->colorName = '';
                }
                $productData = $productData[0];

                $buypricereal_precentage = $mydetales->buypricereal_precentage = $productData->buypricereal_precentage;
                $parentId = $mydetales->productCatId = $productData->productCatId;





                //names of product's parents
                $pathArr = getProductPath_recursive($parentId, $categories);

                //new product name with all path
                $mydetales->productName = $productData->productName . '/' . $pathArr;



                $myunitdata = $myProductunitEx->queryWithProductIdAndCondition($productId);
                $smarty->assign("myunitdata" . $i, $myunitdata);

                //        $i = 0;
                //        foreach ($productUnitData as $unit) {
                //            if ($i == 0) {//get buy price for the first unit only
                //                //buy price
                //                $productQty = getProductUnitQuantity($unit->productunitid);
                //                $priceAfterUnit = $productQty * $buyPriceBeforeUnit; //$buyPriceBeforeUnit is coming from excel//عدد المنتجات في وحدة القياس * سعر شراء المنتج الواحد
                //            }
                //            $i++;
                //        }

                array_push($buyBillDetails, $mydetales);


                $i++;
            }

            $smarty->assign('billFromExcel_date', $billFromExcel_date);
            $smarty->assign('buyBillDetails', $buyBillDetails);
            $smarty->assign('countBillDetails', (count($buyBillDetails) + 1));
            $smarty->assign("customeditbuylbil", 1);
            unset($_SESSION['billFromExcel_' . $_SESSION['userid']]);
            unset($_SESSION['billFromExcel_date' . $_SESSION['userid']]);
        }
        $allCostcenter = $CostcenterEX->queryAllnotdel();
        $smarty->assign("allCostcenter", $allCostcenter);

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

        $billnameAddData = $billNameDAO->load($billnameid);
        if (isset($_GET['ordertype'])) {
            $ordertype = (int) $_GET['ordertype'];
            $billnameAddData->ordertype = $ordertype;
        }

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

        $billSettingsData = loadBillProperties($billnameid);
        $smarty->assign("billsettingsData", $billSettingsData);


        //saves are dropdown list
        $smarty->assign('sessionSave', $_SESSION['saveid']);
        if ($billSettingsData[87] == 1) {
            $allSaves = $mySaveRecord->queryByConditions(0);
            $smarty->assign('allSaves', $allSaves);
        }


        ##get client serial
        $DBName = ConnectionProperty::getDatabase();
        if ($_SESSION['dbname'] != "" && isset($_SESSION['dbname'])) {
            $DBName = $_SESSION['dbname'];
        }
        //check if bill sell or sell and return
        ##settingsvalue14 is buy
        ##settingsvalue0 is return
        ##1 off ,0 on
        $offerId = (int) $_GET['offerId'];
        $smarty->assign("offerId", $offerId);
        if ((int) $billnameAddData->ordertype == 0) { //bill
            if ($billSettingsData[14]->billsettingsvalue == 0 && $billSettingsData[0]->billsettingsvalue == 1) {
                //buy only
                $nextId = $buyBillExt->getAutoIncrementValue($DBName);
            } elseif ($billSettingsData[14]->billsettingsvalue == 0 && $billSettingsData[0]->billsettingsvalue == 0) {
                //buy and return
                $nextId = $buyAndReturnBillDetailExt->getAutoIncrementValue($DBName);
            } else if ($billSettingsData[14]->billsettingsvalue == 1 && $billSettingsData[0]->billsettingsvalue == 0) {
                //return buy bill
                $nextId = $returnBuyBillDetailExt->getAutoIncrementValue($DBName);
            }
        } elseif ($billnameAddData->ordertype == 1) { //offer
            $nextId = $buyBillOfferEX->getAutoIncrementValue($DBName);
        }
        $smarty->assign("nextId", $nextId);

        if ($offerId > 0) { //adding offer as bill
            ################################################################
            $buyBillData = $buyBillOfferDAO->load($offerId);
            $buybillsupplierid = $buyBillData->buybillsupplierid;
            $mysupplierdata = $supplierDAO->load($buybillsupplierid);
            $smarty->assign("mysupplierdata", $mysupplierdata);
            ################################################################
            //get  sell bill detales data
            $buyBillDetails = $buyBillDetailOfferEX->queryByBuybillidExt($offerId);
            if (count($buyBillDetails) > 0) {
                foreach ($buyBillDetails as $detail) {
                    $countBillDetails += $detail->buybilldetailquantity;
                }
            }
            $i = 1;
            foreach ($buyBillDetails as $mydetales) {

                $parentId = $mydetales->buybilldetailcatid;
                //names of product's parents
                $pathArr = getProductPath_recursive($parentId, $categories);

                //new product name with all path
                $mydetales->productName = $mydetales->productName . '/' . $pathArr;



                $myunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->buybilldetailproductid);
                $smarty->assign("myunitdata" . $i, $myunitdata);
                //print_r($myunitdata);
                $i++;
            }

            $smarty->assign('buyBillData', $buyBillData);

            $smarty->assign('buyBillDetails', $buyBillDetails);


            $smarty->assign('countBillDetails', count($buyBillDetails));

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

        $allCurrency = $currencyDAO->queryByConditions(0);
        $smarty->assign("allCurrency", $allCurrency);

        $userSaveData = $saveExt->queryAllEX2(" and save.saveid = " . $_SESSION['saveid'] . " ");
        $smarty->assign("userSaveData", $userSaveData[0]);
        ;

        //$productsData = getProducts();//undeleted products
        //$smarty->assign("productsData", $productsData);

        if ((int) $billnameData->ordertype == 0 && $offerId > 0) { //adding offer as bill
            //data is loaded before
        } else {
            $mysupplierdata = array();
            if (empty($usergroup->showClientAndSupplierOne)) {
                $mysupplierdata = $supplierDAO->load(1);
            }
        }
        $smarty->assign("mysupplierdata", $mysupplierdata);
        $storesData = getStoresOfUser(); //getStores(); //undeleted stores
        $smarty->assign("storesData", $storesData);

        //get product categories
        $categoriesData = getProductCatParents();
        $smarty->assign("categoriesData", $categoriesData);

        //get units
        $unitsData = getUnits();
        $smarty->assign("unitsData", $unitsData);

        $roundNumbersStatus = checkRoundNumbers();
        $smarty->assign("roundNumbersStatus", $roundNumbersStatus);

        $unique = uniqid("0");
        $smarty->assign("unique", $unique);

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

        $today = date("Y-m-d H:i:s");


        ##التصنيفات
        $catDataReport = getCategoryChilds();
        $smarty->assign("catDataReport", $catDataReport[1]);
        if ($billnameAddData->billtype2 == 1) {
            ##التصنيفات
            $catDataReport = getCategoryChilds();
            $smarty->assign("catDataReport", $catDataReport[1]);
        }
        $smarty->assign("billnameAddData", $billnameAddData);


        //
        $allSizeColor = $sizeColorDAO->queryAll();
        $smarty->assign("allSizeColor", $allSizeColor);



        $smarty->assign("today", $today);
        $smarty->assign("supplierScripts", 1);
        $smarty->assign("customBuyBill", 1);
        $smarty->assign("customBuyBillOnly", 1);
        $smarty->assign("buyBillNewProductScript", 1);

        $smarty->assign("editProuctInBuyBill", 1);


        if (isset($_SESSION["printURLBuy"])) {
            $smarty->assign("printURL", $_SESSION["printURLBuy"]);
        } else {
            $smarty->assign("printURL", "");
        }

        unset($_SESSION["printURLBuy"]);
        $smarty->display("buyBillview/add.html");
    } else {
        header("location:?do=error");
    }
} elseif ($do == "editbill") {
    include_once("../public/authentication.php");

    $ordertype = (int) $_GET['ordertype'];

    $countBillDetails = 0;
    $buyBill_Id = $_GET['id'];
    $smarty->assign('billId', $buyBill_Id);
    $allCostcenter = $CostcenterDAO->queryAll();
    $smarty->assign("allCostcenter", $allCostcenter);

    $smarty->assign("billidnor", $buyBill_Id);

    if ($ordertype == 0) { //bill
        $detailsData = showBillDetails($buyBill_Id);
        $buyBillData = $detailsData[0];
        $buyBillDetails = $detailsData[1];
    } elseif ($ordertype == 1) { //offer
        $buyBillData = $detailsData[0] = $buyBillOfferDAO->load($buyBill_Id);
        $buyBillDetails = $detailsData[1] = $buyBillDetailOfferEX->queryByBuybillidExt($buyBill_Id);
    }



    if ($buyBillData->conditions == 1) {
        $smarty->assign('urldirect', 'buyBillController.php?do=show');
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يمكن تعديل الفاتورة حيث انها محذوفة";
        } else {
            $note = "The invoice cannot be modified as it has been deleted";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
        exit();
    }


    $buybillsupplierid = $buyBillData->buybillsupplierid;
    $mysupplierdata = $supplierDAO->load($buybillsupplierid);
    $smarty->assign("mysupplierdata", $mysupplierdata);

    $myclientdata = $clientDAO->load($buyBillData->client);
    $smarty->assign("myclientdata", $myclientdata);

    $smarty->assign("controlname", 'buyBillController.php');


    $allCurrency = $currencyDAO->queryByConditions(0);
    $smarty->assign("allCurrency", $allCurrency);

    $userSaveData = $saveExt->queryAllEX2(" and save.saveid = " . $_SESSION['saveid'] . " ");
    $smarty->assign("userSaveData", $userSaveData[0]);
    $smarty->assign('billCurrData', $detailsData[2]);


    if (count($buyBillDetails) > 0) {
        foreach ($buyBillDetails as $detail) {
            $countBillDetails += $detail->buybilldetailquantity;
        }
    }
    $i = 1;
    foreach ($buyBillDetails as $mydetales) {

        $parentId = $mydetales->buybilldetailcatid;
        //names of product's parents
        $pathArr = getProductPath_recursive($parentId, $categories);

        //new product name with all path
        $mydetales->productName = $mydetales->productName . '/' . $pathArr;



        $myunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->buybilldetailproductid);
        $smarty->assign("myunitdata" . $i, $myunitdata);
        //print_r($myunitdata);
        $i++;
    }

    $smarty->assign('buyBillData', $buyBillData);

    $smarty->assign('buyBillDetails', $buyBillDetails);


    $smarty->assign('countBillDetails', count($buyBillDetails));

    $billSettingsData = loadBillProperties($detailsData[0]->billnameid);
    $smarty->assign("billsettingsData", $billSettingsData);
    $smarty->assign("billnameid", $detailsData[0]->billnameid);

    $billnameAddData = $billNameDAO->load($buyBillData->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);

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

    //saves are dropdown list
    $smarty->assign('sessionSave', $_SESSION['saveid']);
    if ($billSettingsData[87] == 1) {
        $allSaves = $mySaveRecord->queryByConditions(0);
        $smarty->assign('allSaves', $allSaves);
    }


    $billnameid = $buyBillData->billnameid;

    if (!empty($billnameid)) {
        $mysupplierdata = $supplierDAO->load($buyBillData->buybillsupplierid);
        $smarty->assign("mysupplierdata", $mysupplierdata);

        $storesData = getStores(); //undeleted stores
        $smarty->assign("storesData", $storesData);

        //get product categories
        $categoriesData = getProductCatParents();
        $smarty->assign("categoriesData", $categoriesData);

        //get units
        $unitsData = getUnits();
        $smarty->assign("unitsData", $unitsData);

        $roundNumbersStatus = checkRoundNumbers();
        $smarty->assign("roundNumbersStatus", $roundNumbersStatus);

        $unique = uniqid("0");
        $smarty->assign("unique", $unique);





        $today = date("Y-m-d H:i:s");



        $smarty->assign("today", $today);
        $smarty->assign("customeditbuylbil", 1);
        $smarty->assign("supplierScripts", 1);
        $smarty->assign("customBuyBill", 1);



        $smarty->assign("buyBillNewProductScript", 1);

        $smarty->assign("editProuctInBuyBill", 1);
        $smarty->display("buyBillview/edit.html");
    } else {
        header("location:?do=error");
    }
}

if ($do == "editreturn") {
    include_once("../public/authentication.php");
    //
    $smarty->assign("controlname", 'returnBuyBillController.php');


    $allCostcenter = $CostcenterDAO->queryAll();
    $smarty->assign("allCostcenter", $allCostcenter);


    $returnbuybillId = $_GET['id'];
    $smarty->assign('billId', $returnbuybillId);
    $smarty->assign("billidnor", $returnbuybillId);

    $detailsData = returnshowBillDetails($returnbuybillId);

    $returnbuybillData = $detailsData[0];

    if ($returnbuybillData->conditions == 1) {
        $smarty->assign('urldirect', 'returnBuyBillController.php?do=show');
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يمكن تعديل الفاتورة حيث انها محذوفة";
        } else {
            $note = "The invoice cannot be modified as it has been deleted";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
        exit();
    }
    $allCurrency = $currencyDAO->queryByConditions(0);
    $smarty->assign("allCurrency", $allCurrency);

    $userSaveData = $saveExt->queryAllEX2(" and save.saveid = " . $_SESSION['saveid'] . " ");
    $smarty->assign("userSaveData", $userSaveData[0]);
    $smarty->assign('billCurrData', $detailsData[2]);
    /* print_r('<pre>');
      print_r($returnbuybillData);
      print_r('<pre>'); */
    if (count($returnbuybillData) > 0) {
        $returnbuybilldetailData = $detailsData[1];

        //get count
        if (count($returnbuybilldetailData) > 0) {
            foreach ($returnbuybilldetailData as $detail) {
                $countBillDetails += $detail->returnbuybilldetailquantity;
            }
        }

        $smarty->assign('countBillDetails', 0);
        $i = 1;
        foreach ($returnbuybilldetailData as $mydetales) {
            $parentId = $mydetales->returnbuybilldetailcatid;

            //names of product's parents
            $pathArr = getProductPath_recursive($parentId, $categories);
            //new product name with all path
            $mydetales->productName = $mydetales->productName . '/' . $pathArr;



            $myreunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->returnbuybilldetailproductid);
            $smarty->assign("myreunitdata" . $i, $myreunitdata);
            //print_r($myunitdata);
            $i++;
        }

        $smarty->assign('returnbuybillData', $returnbuybillData);
        $smarty->assign('returnbuybilldetailData', $returnbuybilldetailData);
        $smarty->assign('countreturnBillDetails', count($returnbuybilldetailData));
    }


    $billSettingsData = loadBillProperties($detailsData[0]->billnameid);
    $smarty->assign("billnameid", $detailsData[0]->billnameid);



    $smarty->assign("billsettingsData", $billSettingsData);


    $billnameAddData = $billNameDAO->load($returnbuybillData->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);

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

    //saves are dropdown list
    $smarty->assign('sessionSave', $_SESSION['saveid']);
    if ($billSettingsData[87] == 1) {
        $allSaves = $mySaveRecord->queryByConditions(0);
        $smarty->assign('allSaves', $allSaves);
    }


    $billnameid = $returnbuybillData->billnameid;

    if (!empty($billnameid)) {
        $mysupplierdata = $supplierDAO->load($returnbuybillData->returnbuybillsupplierid);
        $smarty->assign("mysupplierdata", $mysupplierdata);

        $myclientdata = $clientDAO->load($buyBillData->client);
        $smarty->assign("myclientdata", $myclientdata);

        $storesData = getStores(); //undeleted stores
        $smarty->assign("storesData", $storesData);

        //get product categories
        $categoriesData = getProductCatParents();
        $smarty->assign("categoriesData", $categoriesData);

        //get units
        $unitsData = getUnits();
        $smarty->assign("unitsData", $unitsData);

        $roundNumbersStatus = checkRoundNumbers();
        $smarty->assign("roundNumbersStatus", $roundNumbersStatus);

        $unique = uniqid("0");
        $smarty->assign("unique", $unique);





        $today = date("Y-m-d H:i:s");



        $smarty->assign("today", $today);
        $smarty->assign("customeditbuylbil", 1);
        $smarty->assign("supplierScripts", 1);
        $smarty->assign("customBuyBill", 1);



        $smarty->assign("buyBillNewProductScript", 1);

        $smarty->assign("editProuctInBuyBill", 1);
        $smarty->display("buyBillview/edit.html");
    } else {
        header("location:?do=error");
    }
}

if ($do == "editbuyandreturnbill") {
    include_once("../public/authentication.php");
    //
    $smarty->assign("controlname", 'buyAndReturnBillController.php');

    $allCostcenter = $CostcenterDAO->queryAll();
    $smarty->assign("allCostcenter", $allCostcenter);



    $buyAndReturnBill_Id = $_GET['id'];
    $smarty->assign('billId', $buyAndReturnBill_Id);
    $smarty->assign("billidnor", $buyAndReturnBill_Id);
    $buyBillData = $buyAndReturnBillExt->loadExt($buyAndReturnBill_Id);
    $smarty->assign("buyBillData", $buyBillData);

    if ($buyBillData->conditions == 1) {
        $smarty->assign('urldirect', 'buyAndReturnBillController.php?do=show');
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يمكن تعديل الفاتورة حيث انها محذوفة";
        } else {
            $note = "The invoice cannot be modified as it has been deleted";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
        exit();
    }



    $buyBillDetails = $buyAndReturnBillDetailExt->queryByBuybillidANDType($buyAndReturnBill_Id, 0);

    // print_r($buyBillDetails);
    $buybillsupplierid = $buyBillData->buybillsupplierid;
    $mysupplierdata = $supplierDAO->load($buybillsupplierid);
    $smarty->assign("mysupplierdata", $mysupplierdata);



    $allCurrency = $currencyDAO->queryByConditions(0);
    $smarty->assign("allCurrency", $allCurrency);

    $userSaveData = $saveExt->queryAllEX2(" and save.saveid = " . $_SESSION['saveid'] . " ");
    $smarty->assign("userSaveData", $userSaveData[0]);
    $billCurrData = $buyAndRuternBillCurrEX->queryOneByBuybillid($buyAndReturnBill_Id);
    $smarty->assign('billCurrData', $billCurrData);


    if (count($buyBillDetails) > 0) {
        foreach ($buyBillDetails as $detail) {
            $countBillDetails += $detail->buybilldetailquantity;
        }
    }
    $i = 1;
    foreach ($buyBillDetails as $mydetales) {

        $parentId = $mydetales->buybilldetailcatid;
        //names of product's parents
        $pathArr = getProductPath_recursive($parentId, $categories);

        //new product name with all path
        $mydetales->productName = $mydetales->productName . '/' . $pathArr;



        $myunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->buybilldetailproductid);
        $smarty->assign("myunitdata" . $i, $myunitdata);
        //print_r($myunitdata);
        $i++;
    }

    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('buyBillDetails', $buyBillDetails);
    $smarty->assign('countBillDetails', count($buyBillDetails));


    /* ====================================== */


    $returnbuybilldetailData = $buyAndReturnBillDetailExt->queryByBuybillidANDType($buyAndReturnBill_Id, 1);

    $countreturnBillDetails = 0;

    //get count
    if (count($returnbuybilldetailData) > 0) {
        foreach ($returnbuybilldetailData as $detail) {
            $countreturnBillDetails += $detail->buybilldetailquantity;
        }
    }

    $smarty->assign('countreturnBillDetails', $countreturnBillDetails);
    $x = 1;
    foreach ($returnbuybilldetailData as $mydetalesx) {


        $parentId = $mydetalesx->buybilldetailcatid;
        //names of product's parents
        $pathArr = getProductPath_recursive($parentId, $categories);

        //new product name with all path
        $mydetalesx->productName = $mydetalesx->productName . '/' . $pathArr;



        //print_r('productunitid'.$mydetalesx->productunitid.'<br>');
        $myreunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetalesx->buybilldetailproductid);
        $smarty->assign("myreunitdata" . $x, $myreunitdata);

        $x++;
    }

    $smarty->assign('returnbuybillData', $returnbuybillData);
    $smarty->assign('returnbuybilldetailData', $returnbuybilldetailData);
    //	$smarty->assign('countreturnBillDetails',count($returnbuybilldetailData));





    /* ====================== */


    $billSettingsData = loadBillProperties($buyBillData->billnameid);
    $smarty->assign("billsettingsData", $billSettingsData);
    $smarty->assign("billnameid", $buyBillData->billnameid);

    $billnameAddData = $billNameDAO->load($buyBillData->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);

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



    //saves are dropdown list
    $smarty->assign('sessionSave', $_SESSION['saveid']);
    if ($billSettingsData[87] == 1) {
        $allSaves = $mySaveRecord->queryByConditions(0);
        $smarty->assign('allSaves', $allSaves);
    }




    if (!empty($buyBillData->billnameid)) {
        $mysupplierdata = $supplierDAO->load($buyBillData->buybillsupplierid);
        $smarty->assign("mysupplierdata", $mysupplierdata);

        $myclientdata = $clientDAO->load($buyBillData->client);
        $smarty->assign("myclientdata", $myclientdata);

        $storesData = getStores(); //undeleted stores
        $smarty->assign("storesData", $storesData);

        //get product categories
        $categoriesData = getProductCatParents();
        $smarty->assign("categoriesData", $categoriesData);

        //get units
        $unitsData = getUnits();
        $smarty->assign("unitsData", $unitsData);

        $roundNumbersStatus = checkRoundNumbers();
        $smarty->assign("roundNumbersStatus", $roundNumbersStatus);

        $unique = uniqid("0");
        $smarty->assign("unique", $unique);





        $today = date("Y-m-d H:i:s");



        $smarty->assign("today", $today);
        $smarty->assign("supplierScripts", 1);
        $smarty->assign("customBuyBill", 1);

        $smarty->assign("customeditbuylbil", 1);


        $smarty->assign("buyBillNewProductScript", 1);

        $smarty->assign("editProuctInBuyBill", 1);
        $smarty->display("buyBillview/edit.html");
    } else {
        //header("location:?do=error");
    }
} elseif ($do == "add") {
    include_once("../public/authentication.php");

    $ordertype = (int) $_POST["ordertype"];
    try {
        $billData = add();
        updateOverallAveragePriceOfProducts($billData);
        $billType = (int) $billData[0];
        $returnBuyBill_Id = $billData[1];
        $buyBill_Id = $billData[2];
        $buyAndReturnBill_Id = $billData[3];
        $billnameid = $billData[5];


        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success', 'id' => $buyBill_Id);
            echo json_encode($data);
            exit();
        }

        if ($ordertype == "1") {
            $printURL = "buyBillprintController.php?do=editprint&id=" . $buyBill_Id . "&ordertype=" . $ordertype;
            $_SESSION["printURLBuy"] = $printURL;
            header("location:buyBillController.php?do=bill&billnameid=" . $billnameid);
        } else {
            //
            $saveBtnGoesTo = (int) $_POST["saveBtnGoesTo"];
            $printURL = "";
            if ($saveBtnGoesTo == 1) {
                //save btn clicked, go to new bill after print but you need to print bill too
                switch ($billType) {
                    case 1: //ret
                        $printURL = "buyBillprintController.php?do=returneditprint1&id=" . $returnBuyBill_Id;
                        break;
                    case 2: //buy
                        $printURL = "buyBillprintController.php?do=editprint&id=" . $buyBill_Id . "&ordertype=" . $ordertype;
                        break;
                    case 3: //buy and ret
                        $printURL = "buyBillprintController.php?do=buyandreturneditprint1&id=" . $buyAndReturnBill_Id;
                        break;
                }
            }
            $_SESSION["printURLBuy"] = $printURL;

            $return_url = $_GET['return_url'];
            if (isset($return_url) && $return_url == 1 && isset($billnameid)) {
                header("location:buyBillController.php?do=bill&billnameid=" . $billnameid);
            } else {
                if ($billType == 1) {
                    header("location:returnBuyBillController.php?do=editprint&id=" . $returnBuyBill_Id . "");
                } elseif ($billType == 2) {
                    header("location:buyBillController.php?do=editprint&id=" . $buyBill_Id . "");
                } elseif ($billType == 3) {
                    header("location:buyAndReturnBillController.php?do=editprint&id=" . $buyAndReturnBill_Id . "");
                }
            }
            $smarty->assign('urldirect', $url);
            if ($_SESSION['erp_lang'] == 'ar') {
                $note = "تمت العملية بنجاح";
            } else {
                $note = "operation accomplished successfully";
            }
            $smarty->assign('msgnote', $note);
            $smarty->display("notes2.html");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            //echo $e;
            header("location:?do=error");
        }
    }
} elseif ($do == "update") {



    include_once("../public/authentication.php");



    //Transaction
    $mytransactions = new Transaction();
    try {
        $ordertype = (int) $_POST["ordertype"];

        $controlname = $_POST["controlname"];
        $billidnor = $_POST["billidnor"];
        $norbuyBillTotal = $_POST["norbuyBillTotal"];
        $norbuyBillTotal_re = $_POST["norbuyBillTotal_re"];


        if ($ordertype == 0) { //bill
            if ($controlname == "buyBillController.php") {

                deletebill($billidnor);
            } elseif ($controlname == "buyAndReturnBillController.php") {
                deletebuyruturn($billidnor);
            } elseif ($controlname == "returnBuyBillController.php") {
                deleteruturn($billidnor);
            }
        } elseif ($ordertype == 1) { //offer1254
            $buyBillOfferDAO->delete($billidnor);
            $buyBillDetailOfferDAO->deleteByBuybillid($billidnor);
        }


        $billData = addnew($controlname, $billidnor, $norbuyBillTotal, $norbuyBillTotal_re);
        updateOverallAveragePriceOfProducts($billData);


        $billType = $billData[0];
        $returnBuyBill_Id = $billData[1];
        $buyBill_Id = $billData[2];
        $buyAndReturnBill_Id = $billData[3];

        //finally update serials store
        //        if ($controlname == "buyBillController.php") {
        //            //Store
        //            if ($_POST['storeSetting'] == 0) {
        //                $storeId = $_POST['storeId'];
        //            } else {
        //                $storeId = 1;
        //            }
        //            $ProductserialEX->updateStoreByQueryString($storeId, " ,billid = $buyBill_Id ", " and billid = $billidnor and type = 0 ");
        //        }
        //commit
        $mytransactions->commit();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success', 'id' => $buyBill_Id);
            echo json_encode($data);
            exit();
        }

        $return_url = $_GET['return_url'];
        $billnameid = $_GET['billnameid'];
        if ($ordertype == 1) { //offer
            if ($_SESSION['erp_lang'] == 'ar') {
                $note = " تمت العملية بنجاح";
            } else {
                $note = "operation accomplished successfully";
            }
            $url = "buyBillController.php?do=showoffers";
            $smarty->assign('urldirect', $url);
            $smarty->assign('msgnote', $note);
            $smarty->display("notes2.html");
        } else {
            if (isset($return_url) && $return_url == 1 && isset($billnameid)) {
                header("location:buyBillController.php?do=bill&billnameid=" . $billnameid);
            } else {
                if ($billType == 1) {
                    header("location:returnBuyBillController.php?do=editprint&id=" . $returnBuyBill_Id . "");
                } elseif ($billType == 2) {
                    header("location:buyBillController.php?do=editprint&id=" . $buyBill_Id . "");
                } elseif ($billType == 3) {
                    header("location:buyAndReturnBillController.php?do=editprint&id=" . $buyAndReturnBill_Id . "");
                }
            }

            //			$smarty->assign('urldirect', $url);
            //			$note ="تمت العملية بنجاح";
            //			$smarty->assign('msgnote', $note);
            //			$smarty->display("notes2.html");
        }
    } catch (Exception $e) {
        $mytransactions->rollback();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            //   echo $e;
            header("location:?do=error");
        }
    }
}

################
elseif ($do == "details") {
    include_once("../public/authentication.php");
    $ordertype = (int) $_GET['ordertype'];

    $countBillDetails = 0;
    $buyBill_Id = $_GET['id'];

    $allCostcenter = $CostcenterDAO->queryAll();
    $smarty->assign("allCostcenter", $allCostcenter);

    $detailsData = showBillDetails($buyBill_Id, $ordertype); //, $ordertype

    $buyBillData = $detailsData[0];

    $buyBillDetails = $detailsData[1];
    $smarty->assign('ordertype', $ordertype);

    //getalldiscount
    $buybilldiscount = $detailsData[0]->buybilldiscount;
    $buybilldiscountrype = $detailsData[0]->buybilldiscountrype; //0 مباشر
    $buybilltotalbill = $detailsData[0]->buybilltotalbill;
    $buybillaftertotalbill = $detailsData[0]->buybillaftertotalbill;
    $tax = $detailsData[0]->payedtax;


    if ($buybilldiscountrype == 0) {

        //tax
        $taxvalue = $buybillaftertotalbill - ($buybilltotalbill - ($buybilldiscount));
        $discountvalue = $buybilldiscount;
    } else {
        //discount
        $discountvalue = ($buybilltotalbill / 100) * $buybilldiscount;
        //tax
        $taxvalue = $buybillaftertotalbill - ($buybilltotalbill - ($discountvalue));
        $taxvalue = round($taxvalue, 2);
        $taxvalue = ($taxvalue == -0) ? 0 : $taxvalue;
    }

    $smarty->assign('discountvalue', $discountvalue);
    $smarty->assign('taxvalue', $taxvalue);

    //get count
    if (count($buyBillDetails) > 0) {
        foreach ($buyBillDetails as $detail) {
            $countBillDetails += $detail->buybilldetailquantity;
        }
    }

    $smarty->assign('buyBillData', $buyBillData);
    //print_r($buyBillData);
    $smarty->assign('buyBillDetails', $buyBillDetails);
    $smarty->assign('countBillDetails', $countBillDetails);

    $billSettingsData = loadBillProperties($detailsData[0]->billnameid);

    $smarty->assign("billsettingsData", $billSettingsData);
    $smarty->assign("billnameid", $detailsData[0]->billnameid);

    $billnameAddData = $billNameDAO->load($buyBillData->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);

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

    $smarty->assign("customBuyBill", 1);
    $smarty->assign("buyBillNewProductScript", 1);

    //here the smarty templates
    $smarty->display("buyBillview/details.html");
}

#################
elseif ($do == "editprint") {
    include_once("../public/authentication.php");
    $countBillDetails = 0;
    $buyBill_Id = $_GET['id'];

    $allCostcenter = $CostcenterDAO->queryAll();
    $smarty->assign("allCostcenter", $allCostcenter);


    $detailsData = showBillDetails($buyBill_Id);
    if (count($detailsData) > 0) {
        $buyBillData = $detailsData[0];
        if (count($buyBillData) > 0) {
            $buyBillDetails = $detailsData[1];



            //getalldiscount
            $buybilldiscount = $detailsData[0]->buybilldiscount;
            $buybilldiscountrype = $detailsData[0]->buybilldiscountrype; //0 مباشر
            $buybilltotalbill = $detailsData[0]->buybilltotalbill;
            $buybillaftertotalbill = $detailsData[0]->buybillaftertotalbill;
            $tax = $detailsData[0]->payedtax;


            if ($buybilldiscountrype == 0) {

                //tax
                $taxvalue = $buybillaftertotalbill - ($buybilltotalbill - ($buybilldiscount));
                $discountvalue = $buybilldiscount;
            } else {
                //discount
                $discountvalue = ($buybilltotalbill / 100) * $buybilldiscount;
                //tax
                $taxvalue = $buybillaftertotalbill - ($buybilltotalbill - ($discountvalue));
            }

            $smarty->assign('discountvalue', $discountvalue);
            $smarty->assign('taxvalue', $taxvalue);


            //get count
            if (count($buyBillDetails) > 0) {
                foreach ($buyBillDetails as $detail) {
                    $countBillDetails += $detail->buybilldetailquantity;
                }
            }

            $smarty->assign('buyBillData', $buyBillData);
            $smarty->assign('buyBillDetails', $buyBillDetails);
            $smarty->assign('countBillDetails', $countBillDetails);

            $billSettingsData = loadBillProperties($detailsData[0]->billnameid);
            $smarty->assign("billsettingsData", $billSettingsData);
            $smarty->assign("billnameid", $detailsData[0]->billnameid);


            $billnameAddData = $billNameDAO->load($buyBillData->billnameid);
            $smarty->assign("billnameAddData", $billnameAddData);

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

            //$smarty->assign("customPrint",1);
            $smarty->assign("customBuyBill", 1);
            $smarty->assign("buyBillNewProductScript", 1);
        }
    }
    //here the smarty templates
    $smarty->display("buyBillview/editprint.html");
}


//add serail
elseif ($do == "addserial") {
    include_once("../public/authentication.php");

    $buyBill_Id = $_GET['id'];

    $detailsData = showBillDetails($buyBill_Id);
    $buyBillData = $detailsData[0];

    $buyBillDetails = $detailsData[1];

    $countBillDetails = count($buyBillDetails);
    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('buyBillDetails', $buyBillDetails);


    $myusedserial = $ProductserialEX->queryAllbybillandtype($buyBill_Id, 0);
    $smarty->assign('countmyusedserial', count($myusedserial));
    //print_r("<pre>");
    //	print_r($buyBillDetails);
    //	print_r("<pre>");

    $i = 1;
    foreach ($buyBillDetails as $mybuyBillDetails) {
        $productnumber = $mybuyBillDetails->productnumber;
        $buybilldetailquantity = $mybuyBillDetails->buybilldetailquantity;
        $totalproduct = $productnumber * $buybilldetailquantity;



        $smarty->assign('totalproduct' . $i . '', $totalproduct);

        if ($row->billtype != 1) {


            for ($m = 1; $m <= $totalproduct; $m++) {
                $returnedSerial = getserail(6, $mybuyBillDetails->buybilldetailproductid);
                $smarty->assign("returnedSerial" . $i . $m, $returnedSerial);
            }
        }

        $productid = $mybuyBillDetails->buybilldetailproductid;
        $buybillid = $mybuyBillDetails->buybillid;
        $buybilldetailid = $mybuyBillDetails->buybilldetailid;

        $allseraildata = $ProductserialEX->queryWithProductIdandbillid($productid, $buybillid, 0, $buybilldetailid);

        /* print_r("<pre>");
          print_r($allseraildata);
          print_r("<pre>"); */
        $smarty->assign('allseraildata' . $i . '', $allseraildata);

        $i++;
    }

    $smarty->assign('countBillDetails', $countBillDetails);

    $billSettingsData = loadBillProperties($detailsData[0]->billnameid);
    $smarty->assign("billsettingsData", $billSettingsData);
    $smarty->assign("billnameid", $detailsData[0]->billnameid);

    //$smarty->assign("customPrint",1);
    //$smarty->assign("customBuyBill",1);
    $smarty->assign("buyBillNewProductScript", 1);

    //here the smarty templates
    $smarty->display("buyBillview/addserial.html");
}



//add  one serail
elseif ($do == "addoneserial") {
    include_once("../public/authentication.php");

    $buyBill_Id = $_GET['id'];

    $detailsData = showBillDetails($buyBill_Id);
    $buyBillData = $detailsData[0];

    $buyBillDetails = $detailsData[1];

    $countBillDetails = count($buyBillDetails);
    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('buyBillDetails', $buyBillDetails);


    $myusedserial = $ProductserialEX->queryAllbybillandtype($buyBill_Id, 0);
    $smarty->assign('countmyusedserial', count($myusedserial));
    //print_r("<pre>");
    //	print_r($buyBillDetails);
    //	print_r("<pre>");

    $i = 1;
    foreach ($buyBillDetails as $mybuyBillDetails) {
        $productnumber = $mybuyBillDetails->productnumber;
        $buybilldetailquantity = $mybuyBillDetails->buybilldetailquantity;
        $totalproduct = $productnumber * $buybilldetailquantity;
        $smarty->assign('totalproduct' . $i . '', $totalproduct);
        $smarty->assign('totalproductx' . $i . '', 1);

        if ($row->billtype != 1) {

            for ($m = 1; $m <= 1; $m++) {
                $returnedSerial = getserail(6, $mybuyBillDetails->buybilldetailproductid);
                $smarty->assign("returnedSerial" . $i . $m, $returnedSerial);
            }
        }

        $productid = $mybuyBillDetails->buybilldetailproductid;
        $buybillid = $mybuyBillDetails->buybillid;
        $buybilldetailid = $mybuyBillDetails->buybilldetailid;

        $allseraildata = $ProductserialEX->queryWithProductIdandbillid($productid, $buybillid, 0, $buybilldetailid);


        $smarty->assign('allseraildata' . $i . '', $allseraildata);

        $i++;
    }

    $smarty->assign('countBillDetails', $countBillDetails);

    $billSettingsData = loadBillProperties($detailsData[0]->billnameid);
    $smarty->assign("billSettingsData", $billSettingsData);
    $smarty->assign("billnameid", $detailsData[0]->billnameid);


    //$smarty->assign("customPrint",1);
    //$smarty->assign("customBuyBill",1);
    $smarty->assign("buyBillNewProductScript", 1);

    //here the smarty templates
    $smarty->display("buyBillview/addoneseria.html");
} elseif ($do == "addpl") {
    include_once("../public/authentication.php");

    $buyBill_Id = $_GET['id'];


    $buybill = R::getRow("SELECT * FROM buybill where buybillid = ? ", [$buyBill_Id]);
    $supplier = R::getRow("SELECT * FROM supplier where supplierid = ? ", [$buybill['buybillsupplierid']]);
    $store = R::getRow("SELECT * FROM store where storeId = ? ", [$buybill['buybillstoreid']]);

    $buybilldetails = R::getAll("SELECT * FROM buybilldetail where buybillid = ? ", [$buyBill_Id]);


    $allitem = array();
    foreach ($buybilldetails as $buybilldetail) {
        $product = R::getRow("SELECT * FROM product where productId = ? ", [$buybilldetail['buybilldetailproductid']]);
        $unit = R::getRow("SELECT * FROM unit where unitId = ? ", [$buybilldetail['productunitid']]);
        $buybilldetailpls = R::getAll("SELECT * FROM buybilldetailpl where buybilldetailid = ? ", [$buybilldetail['buybilldetailid']]);
        $stayquantity = R::getcell("SELECT sum(text2) FROM buybilldetailpl where buybilldetailid = ? ", [$buybilldetail['buybilldetailid']]);
        $item = array(
            'buybilldetailid' => $buybilldetail['buybilldetailid'],
            'unitName' => $unit['unitName'],
            'buybilldetailquantity' => $buybilldetail['buybilldetailquantity'],
            'stayquantity' => $stayquantity,
            'productName' => $product['productName'],
            'weight' => $product['weight'],
            'origin' => $product['origin'],
            'hscode' => $product['hscode'],
            'buybilldetailpls' => $buybilldetailpls
        );
        array_push($allitem, $item);
    }


    // print_r($allitem);
    // exit();
    $smarty->assign('buybill', $buybill);
    $smarty->assign('supplier', $supplier);
    $smarty->assign('store', $store);
    $smarty->assign('buybilldetails', $allitem);

    $smarty->assign("buyBillNewProductScript", 1);

    //here the smarty templates
    $smarty->display("buyBillview/addpl.html");
} elseif ($do == "saveserail") {
    try {
        saveserail();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "show") {
    include_once("../public/authentication.php");

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

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

    $usergroup = $UsergroupDAO->load($_SESSION['usergroupid']);
    $smarty->assign("usergroup", $usergroup);
    //    $suppliersData = getSuppliers(); //undeleted suppliers
    //    $smarty->assign("suppliersData", $suppliersData);
    $storesData = getStores(); //undeleted stores
    $smarty->assign("storesData", $storesData);

    $billSerials = showBuyBills();
    $smarty->assign("billSerials", $billSerials);

    $supplierId = (int) $_REQUEST['supplier'];
    $store = $_REQUEST['store'];
    $serial = $_REQUEST['serial'];
    $buybillid = $_REQUEST['buybillid'];
    $from = $_REQUEST['from'];
    $to = $_REQUEST['to'];
    $hideDel = (int) $_REQUEST['hideDel'];
    $delString = '';
    if (isset($hideDel) && $hideDel == 1) {
        //$message .= "<br> اخفاء المحذوف ";
        $delString .= ' AND buybill.conditions = 0 ';
    }

    //display the converted time ##reportsPlusHours
    $Programsetting = $ProgramsettingDAO->load(1);
    if (!empty($supplierId) && $supplierId > 0 && (empty($serial) || $serial == "-1")) {
        showBySupplier($supplierId, $delString);

        $messageData = $supplierDAO->load($supplierId);
        $message = "إسم المورد: " . $messageData->suppliername;
        $smarty->assign("message", $message);
    } elseif (!empty($store) && $store != "-1") {
        showByStore($store, $delString);

        $messageData = $storeDAO->load($store);
        $message = "المخزن: " . $messageData->storeName;
        $smarty->assign("message", $message);
    } elseif (!empty($serial) && $serial != "-1" && (empty($supplierId) || $supplierId == "-1")) {
        showByBillSerial($serial, $delString);

        $message = "الرقم المتسلسل: " . $serial;
        $smarty->assign("message", $message);
    } elseif (!empty($buybillid) && $buybillid != "-1" && (empty($serial) || $serial == "-1") && (empty($supplierId) || $supplierId == "-1")) {
        showBybuybillid($buybillid, $delString);

        $message = "رقم الفاتورة: " . $buybillid;
        $smarty->assign("message", $message);
    } elseif (!empty($from) && !empty($to)) {

        if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
            $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
            $to = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($to)));
            $from = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($from)));
        } else {
            $to = $to . ' 23:59:59';
            $from = $from . " 00:00:00";
        }
        showByDate($from, $to, $delString);

        $message = "التاريخ من: " . $from . " إلى: " . $to;
        $smarty->assign("message", $message);
    } else {
        //display the converted time ##reportsPlusHours
        ################
        $today = date('Y-m-d');
        $yesterday = date("Y-m-d", strtotime('-1 days'));
        if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
            $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
            $endToday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            $startToday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            //
            $endYesterday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
            $startYesterday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
        } else {
            $endToday = $today . ' 23:59:59';
            $startToday = $today . " 00:00:00";
            //
            $endYesterday = $today . ' 23:59:59';
            $startYesterday = $today . " 00:00:00";
        }
        if (date('H') < $Programsetting->reportsPlusHours) {
            $from = $startYesterday;
            $to = $endYesterday;
        } else {
            $from = $startToday;
            $to = $endToday;
        }
        ##############
        showByDate($from, $to, $delString);
        //showAll();
    }
    //$smarty->assign("customCheck",1);
    $smarty->display("buyBillview/show.html");
} elseif ($do == "delete") {
    $ordertype = (int) $_GET['ordertype'];
    try {
        $flag = delete();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
            exit();
        }

        if ($ordertype == 0) {
            header("location:?do=sucess");
        } elseif ($ordertype == 1) {
            header("location:?do=showoffers");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            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");
}
//
elseif ($do == "excelToBill") {
    include '../library/Classes/PHPExcel/IOFactory.php';
    ## upload file
    $handle = new upload($_FILES['billAsExcelFile']);
    $excelfileName = uploadfile($handle, "../upload/products");
    $inputFileName = "../upload/products/" . $excelfileName;
    //  Read your Excel workbook
    /* //Transaction
      $mytransactions = new Transaction();
      try { */
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    //$objReader->setUTFEncoder('iconv');
    //$objReader::setOutputEncoding('UTF-8');
    $objPHPExcel = $objReader->load($inputFileName);



    //  Get worksheet dimensions
    $sheet = $objPHPExcel->getSheet(0);

    $billdate = $objPHPExcel->getActiveSheet()->getCell('G1')->getValue();

    $highestRow = $sheet->getHighestRow();
    $highestColumn = $sheet->getHighestColumn();
    $productsArr = array();
    $proExcelIds = '';
    $catExcelIds = '';
    $sizeExcelIds = '';
    $colorExcelIds = '';
    for ($row = 4; $row <= $highestRow; $row++) {
        //  Read a row of data into an array
        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
        $rowData = $rowData[0];

        ##getdata
        $proObj = new stdClass();
        $col = 0;
        $proObj->catid = $rowData[$col];
        $col++;
        $proObj->catname = $rowData[$col];
        $col++;
        $proObj->parcode = $rowData[$col];
        $col++;
        $proObj->productid = $rowData[$col];
        $col++;
        $proObj->productname = $rowData[$col];
        $col++;
        $proObj->quantity = $rowData[$col];
        $col++;
        $proObj->price = $rowData[$col];
        $col++;
        $proObj->sizeid = $rowData[$col];
        $col++;
        $proObj->colorid = $rowData[$col];
        $col++;
        $proObj->sizename = $rowData[$col];
        $col++;
        $proObj->colorname = $rowData[$col];
        array_push($productsArr, $proObj);
        $proExcelIds .= $proObj->productid . ',';
        $catExcelIds .= $proObj->catid . ',';
        $sizeExcelIds .= $proObj->sizeid . ',';
        $colorExcelIds .= $proObj->colorid . ',';
    }
    $proExcelIds = rtrim($proExcelIds, ',');
    $catExcelIds = rtrim($catExcelIds, ',');
    $sizeExcelIds = rtrim($sizeExcelIds, ',');
    $colorExcelIds = rtrim($colorExcelIds, ',');
    $existingExcelInfo_pro = array();
    if ($proExcelIds != '') {
        $excelInfo = $productExt->getExcelInfo(" where proExcelid in ($proExcelIds) ");
        foreach ($excelInfo as $val) {
            $existingExcelInfo_pro[$val->proExcelid] = $val;
        }
    }
    $existingExcelInfo_cat = array();
    if ($catExcelIds != '') {
        $excelInfoCat = $productCatExt->getExcelInfo(" where catExcelid in ($catExcelIds) ");
        foreach ($excelInfoCat as $val) {
            $existingExcelInfo_cat[$val->catExcelid] = $val;
        }
    }
    $existingExcelInfo_size = array();
    if ($sizeExcelIds != '') {
        $excelInfoSize = $sizeColorEX->getExcelInfo(" where scExcelid in ($sizeExcelIds) ");
        foreach ($excelInfoSize as $val) {
            $existingExcelInfo_size[$val->scExcelid] = $val;
        }
    }
    $existingExcelInfo_color = array();
    if ($colorExcelIds != '') {
        $excelInfoColor = $sizeColorEX->getExcelInfo(" where scExcelid in ($colorExcelIds) ");
        foreach ($excelInfoColor as $val) {
            $existingExcelInfo_color[$val->scExcelid] = $val;
        }
    }
    $smarty->assign("existingExcelInfo_pro", $existingExcelInfo_pro);
    $smarty->assign("existingExcelInfo_cat", $existingExcelInfo_cat);
    $smarty->assign("existingExcelInfo_size", $existingExcelInfo_size);
    $smarty->assign("existingExcelInfo_color", $existingExcelInfo_color);
    $smarty->assign("productsArr", $productsArr);
    $smarty->assign("billdate", $billdate);
    $smarty->display("buyBillview/linkExcelProducts.html");
    // $smarty->assign("linkExcelProducts", 1);
    unlink($inputFileName);
    /*    $mytransactions->commit();
      } catch (Exception $e) {
      $mytransactions->rollback();
      //die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
      } */
} elseif ($do == "doLinkExcelProducts") {
    $itr = (int) filter_input(INPUT_POST, 'itr');
    $billdateExcel = filter_input(INPUT_POST, 'billdateExcel');
    $flag = 1;
    $productQuantityArray = array();
    for ($i = 1; $i < $itr; $i++) {
        $catIsLinked = (int) filter_input(INPUT_POST, 'catIsLinked' . $i);
        $productIsLinked = (int) filter_input(INPUT_POST, 'productIsLinked' . $i);
        $sizeIsLinked = (int) filter_input(INPUT_POST, 'sizeIsLinked' . $i);
        $colorIsLinked = (int) filter_input(INPUT_POST, 'colorIsLinked' . $i);
        $catid_program = (int) filter_input(INPUT_POST, 'catprog' . $i);
        $productid_program = (int) filter_input(INPUT_POST, 'productprog' . $i);
        $sizeprog = (int) filter_input(INPUT_POST, 'sizeprog' . $i);
        $sizeidExcel = (int) filter_input(INPUT_POST, 'sizeidExcel' . $i);
        $colorprog = (int) filter_input(INPUT_POST, 'colorprog' . $i);
        $coloridExcel = (int) filter_input(INPUT_POST, 'coloridExcel' . $i);

        $quantity_excel = (float) filter_input(INPUT_POST, 'quantity' . $i);
        $productparcode_excel = filter_input(INPUT_POST, 'productparcode' . $i);
        $buyprice_excel = (float) filter_input(INPUT_POST, 'price' . $i);

        if ($catIsLinked == 0) {
            $catid_excel = (int) filter_input(INPUT_POST, 'catid' . $i);
            $catname_excel = filter_input(INPUT_POST, 'catname' . $i);


            if ($catid_program == -1 && !empty($catname_excel)) { //add new cat
                $checkData = $productCatDAO->queryByProductCatName($catname_excel);
                if (count($checkData) > 0) { //it does exist use it
                    $catid_program = $checkData[0]->productCatId;
                } else { //add new
                    $catDataArr = array(
                        'parent' => '-1', 'level' => 0, 'productCatName' => $catname_excel, 'inMenu' => 0, 'discounttype' => -1, 'selldiscount' => '0', 'buydiscount' => '0', 'buypricereal' => '0', 'buytotal' => '0', 'buyhalf' => '0', 'buypart' => '0', 'stopNegativeSale' => '0', 'productCatDescription' => '', 'productcatunit1' => '-1', 'cat_productnumber1' => '', 'cat_unitsItr' => '1'
                    );
                    $catid_program = CURL_IT2($catDataArr, 'productCatController.php?do=add2SimpleReturn');
                }
            }
            //now link to existing cat
            if ($catid_program > 0) {
                $productCatExt->updateExcelInfo($catid_excel, $catid_program);
            } else {
                $flag = 0;
            }
        }
        if ($productIsLinked == 0) {
            $productid_excel = (int) filter_input(INPUT_POST, 'productid' . $i);
            $productname_excel = filter_input(INPUT_POST, 'productname' . $i);

            $sellAllPrice_program = (float) filter_input(INPUT_POST, 'sellAllPrice' . $i);
            $sellHalfPrice_program = (float) filter_input(INPUT_POST, 'sellHalfPrice' . $i);
            $sellUnitPrice_program = (float) filter_input(INPUT_POST, 'sellUnitPrice' . $i);

            $hasSizeAndColor = 0;
            if ($sizeidExcel > 0 && $coloridExcel > 0) {
                $hasSizeAndColor = 1;
            }
            if ($productid_program == -1 && !empty($productname_excel) && !empty($catid_program)) { //add new product
                $checkData = $productExt->checkForProductNameInOneCategory2($productname_excel, $catid_program);
                if (count($checkData) > 0) { //it does exist use it
                    $productid_program = $checkData[0]->productId;
                } else { //add new
                    $productDataArr = array(
                        'productCatId' => $catid_program,
                        'productItr' => '2',
                        'productindextype' => '0',
                        'unitsItr1' => '0',
                        'hide_precentage' => '1',
                        'hide_realprice' => '1',
                        'hide_isCaf' => '',
                        'hide_isRestaurent' => '0',
                        'productName1' => $productname_excel,
                        'productBuyPrice1' => $buyprice_excel,
                        'productbuypricereal1' => $buyprice_excel,
                        'buypricereal_precentage1' => '0',
                        'productSellAllPrice1' => $sellAllPrice_program,
                        'buytotal_precentage1' => 0, //'10.00',
                        'productSellHalfPrice1' => $sellHalfPrice_program,
                        'buyhalf_precentage1' => 0, //'20.00',
                        'productSellUnitPrice1' => $sellUnitPrice_program,
                        'buypart_precentage1' => 0, //'30.00',
                        'productquantity1' => '0',
                        'parcode1' => '',
                        'expireDate1' => '0',
                        'productDate1' => date('Y-m-d'),
                        'limitamount1' => '0',
                        'inMenu1' => '0',
                        'type1' => '0',
                        'isservice1' => '0',
                        'productDescription1' => '',
                        'hidden_unitItr1' => '0',
                        'hasSizeAndColor1' => $hasSizeAndColor,
                    );

                    $productid_program = CURL_IT2($productDataArr, 'productController.php?do=addOneSimpleReturn');
                }
            }
            //now link to existing product
            if ($productid_program > 0) {
                if ($hasSizeAndColor == 0) {
                    $productExt->updateExcelInfo($productid_excel, $productparcode_excel, $productid_program);
                }
            } else {
                $flag = 0;
            }
        }

        if ($sizeIsLinked == 0 && $sizeidExcel > 0) {
            $sizename = filter_input(INPUT_POST, 'sizename' . $i);

            if ($sizeprog == -1 && !empty($sizename)) { //add new
                $checkData = $sizeColorDAO->queryByName($sizename);
                if (count($checkData) > 0) { //it does exist use it
                    $sizeprog = $checkData[0]->id;
                } else { //add new
                    //$productid_program = CURL_IT2($productDataArr, 'productController.php?do=addOneSimpleReturn');
                    //add in tbl
                    $sizeColor->name = $sizename;
                    $sizeColor->type = 0;
                    $sizeColor->userid = $_SESSION['userid'];
                    $sizeColor->conditions = 0;
                    $sizeColor->sysdate = date("Y-m-d");
                    $sizeColor->scExcelid = $sizeidExcel;
                    $sizeprog = $sizeColorDAO->insert($sizeColor);
                }
            }
            //now link to existing product
            if ($sizeprog > 0) {
                $sizeColorEX->updateExcelInfo($sizeidExcel, $sizeprog);
            } else {
                $flag = 0;
            }
        }
        if ($colorIsLinked == 0 && $coloridExcel > 0) {
            $colorname = filter_input(INPUT_POST, 'colorname' . $i);
            if ($colorprog == -1 && !empty($colorname)) { //add new
                $checkData = $sizeColorDAO->queryByName($colorname);
                if (count($checkData) > 0) { //it does exist use it
                    $colorprog = $checkData[0]->id;
                } else { //add new
                    //$productid_program = CURL_IT2($productDataArr, 'productController.php?do=addOneSimpleReturn');
                    //add in tbl
                    $sizeColor->name = $colorname;
                    $sizeColor->type = 1;
                    $sizeColor->userid = $_SESSION['userid'];
                    $sizeColor->conditions = 0;
                    $sizeColor->sysdate = date("Y-m-d");
                    $sizeColor->scExcelid = $coloridExcel;
                    $colorprog = $sizeColorDAO->insert($sizeColor);
                }
            }
            //now link to existing product
            if ($colorprog > 0) {
                $sizeColorEX->updateExcelInfo($coloridExcel, $colorprog);
            } else {
                $flag = 0;
            }
        }
        if (($colorIsLinked == 0 || $sizeIsLinked == 0) && $coloridExcel > 0 && $sizeidExcel > 0 && $sizeprog > 0 && $colorprog > 0) {
            $sizeColorDataArr = array(
                'productId' => $productid_program,
                'sizeColorItr' => 2,
                'size_detail1' => $sizeprog,
                'color_detail1' => $colorprog,
                'parcode_detail1' => '',
                'quantity_detail' => 0,
            );
            CURL_IT2($sizeColorDataArr, 'productController.php?do=addsizeColorToProductAjax');

            //now link to existing product
            $sizeColorStoreDetailEX->updateExcelInfo($productparcode_excel, $productid_program, $sizeprog, $colorprog, 1);
        }


        $productid_program_final = $productid_program;
        if ($sizeprog > 0 && $colorprog > 0) {
            $productid_program_final = "hasSizeColor$productid_program-$sizeprog-$colorprog";
        }
        ///////data to return
        if (isset($productQuantityArray[$productid_program_final])) {
            $productQuantityArray[$productid_program_final]->quantity += $quantity_excel;
        } else {
            $tempObj = new stdClass();
            $tempObj->price = $buyprice_excel;
            $tempObj->quantity = $quantity_excel;
            $tempObj->excelparcode = $productparcode_excel;
            $tempObj->sizeid = $sizeprog;
            $tempObj->colorid = $colorprog;
            $tempObj->productid = $productid_program;
            $productQuantityArray[$productid_program_final] = $tempObj;
        }
    }
    if ($flag == 1) {
        $_SESSION['billFromExcel_' . $_SESSION['userid']] = $productQuantityArray;
        $_SESSION['billFromExcel_date' . $_SESSION['userid']] = $billdateExcel;
        header("location:buyBillController.php?do=bill&billnameid=1");
    } else {
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لقد حدث خطأ فى الربط من فضلك حاول مرة اخرى";
        } else {
            $note = "An error occurred in the connection, please try again";
        }
        $url = "buyBillController.php?do=bill&billnameid=1";
        $smarty->assign('urldirect', $url);
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    }
} elseif ($do == "showoffers") {
    $Programsettingdata = $ProgramsettingDAO->load(1);
    $smarty->assign("Programsettingdata", $Programsettingdata);
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $usergroup = $UsergroupDAO->load($_SESSION['usergroupid']);
    $smarty->assign("usergroup", $usergroup);
    //    $suppliersData = getSuppliers(); //undeleted suppliers
    //    $smarty->assign("suppliersData", $suppliersData);

    $billSerials = showBuyBills();
    $smarty->assign("billSerials", $billSerials);

    $supplierId = (int) $_REQUEST['supplier'];
    $serial = $_REQUEST['serial'];
    $buybillid = $_REQUEST['buybillid'];
    $from = $_REQUEST['from'];
    $to = $_REQUEST['to'];
    $hideDel = (int) $_REQUEST['hideDel'];
    $delString = '';
    if (isset($hideDel) && $hideDel == 1) {
        //$message .= "<br> اخفاء المحذوف ";
        $delString .= ' AND buybilloffer.conditions = 0 ';
    }

    //display the converted time ##reportsPlusHours
    $Programsetting = $ProgramsettingDAO->load(1);
    if (!empty($supplierId) && $supplierId > 0 && (empty($serial) || $serial == "-1")) {
        showBySupplierOffer($supplierId, $delString);

        $messageData = $supplierDAO->load($supplierId);
        $message = "إسم المورد: " . $messageData->suppliername;
        $smarty->assign("message", $message);
    } elseif (!empty($serial) && $serial != "-1" && (empty($supplierId) || $supplierId == "-1")) {
        showByBillSerialOffer($serial, $delString);

        $message = "الرقم المتسلسل: " . $serial;
        $smarty->assign("message", $message);
    } elseif (!empty($buybillid) && $buybillid != "-1" && (empty($serial) || $serial == "-1") && (empty($supplierId) || $supplierId == "-1")) {
        showBybuybillidOffer($buybillid, $delString);

        $message = "رقم الفاتورة: " . $buybillid;
        $smarty->assign("message", $message);
    } elseif (!empty($from) && !empty($to)) {

        if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
            $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
            $to = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($to)));
            $from = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($from)));
        } else {
            $to = $to . ' 23:59:59';
            $from = $from . " 00:00:00";
        }
        showByDateOffer($from, $to, $delString);

        $message = "التاريخ من: " . $from . " إلى: " . $to;
        $smarty->assign("message", $message);
    } else {
        //display the converted time ##reportsPlusHours
        ################
        $today = date('Y-m-d');
        $yesterday = date("Y-m-d", strtotime('-1 days'));
        if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
            $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
            $endToday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            $startToday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            //
            $endYesterday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
            $startYesterday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
        } else {
            $endToday = $today . ' 23:59:59';
            $startToday = $today . " 00:00:00";
            //
            $endYesterday = $today . ' 23:59:59';
            $startYesterday = $today . " 00:00:00";
        }
        if (date('H') < $Programsetting->reportsPlusHours) {
            $from = $startYesterday;
            $to = $endYesterday;
        } else {
            $from = $startToday;
            $to = $endToday;
        }
        ##############
        showByDateOffer($from, $to, $delString);
        //showAll();
    }
    //$smarty->assign("customCheck",1);
    $smarty->assign("customBuyBill", 1);
    $smarty->display("buyBillview/showoffers.html");
} elseif ($do == "saveOfferAsBill") {
    $offerId = (int) $_GET['offerId'];
    $buyBilldata = $buyBillOfferDAO->load($offerId);
    if ($offerId > 0 && $buyBilldata->orderSavedBillId == 0) {

        ####### 1- set some required post values
        $buybillDetails = $buyBillDetailOfferDAO->queryByBuybillid($offerId);
        $supplierData = $supplierDAO->load($buyBilldata->buybillsupplierid);

        $_POST = array(
            'offerId' => $offerId,
            'scunitnamevalue' => $Programsettingdata->scunitname,
            'usedParcode' => $Programsettingdata->usedParcode,
            'valueaddedbuy' => $Programsettingdata->valueaddedbuy,
            'billtype2' => 0,
            'ordertype' => 0,
            'billnameid' => 1,
            'returnBillSetting' => 0,
            'storeSetting' => 0,
            'dateSetting' => '0',
            'saveBtnGoesTo' => '0',
            'Costcenter' => -1,
            'pay_num' => uniqid("0"),
            'bn' => date('Y-m-d H:i:s'),
            'supplier' => $buyBilldata->buybillsupplierid,
            'hidden_debt' => $supplierData->suppliercurrentDebt,
            'storeId' => $buyBilldata->buybillstoreid,
            'currencyId' => $buyBilldata->currencyId,
            //'cFactor' => $buyBilldata->,
            'comment' => $buyBilldata->comment,
            'hidden_itr' => count($buybillDetails),
            'hidden_itr_re' => 0,
            'totalbeforediscount' => $buyBilldata->buybilltotalbill,
            'discount_type' => $buyBilldata->buybilldiscountrype,
            'gendis' => $buyBilldata->buybilldiscount,
            'taxOfDiscountPercentage' => $buyBilldata->taxOfDiscountPer,
            'taxOfDiscountVal' => $buyBilldata->taxOfDiscountVal,
            'payedtax' => $buyBilldata->payedtax,
            'totalafterdiscount' => $buyBilldata->buybillaftertotalbill,
            'genpay' => $buyBilldata->buybilltotalpayed,
            'delbyuserid' => 0,
            'saveid' => $buyBilldata->buybillsaveid,
                //'totalBuyBill' => $buyBilldata->,
        );
        $i = 1;
        $totalBuyBill = 0;
        foreach ($buybillDetails as $value) {
            $_POST['parcode' . $i] = $value->parcode;
            $_POST['product' . $i] = $value->buybilldetailproductid;
            $_POST['note' . $i] = $value->note;
            $_POST['unitId' . $i] = $value->productunitid;
            $_POST['pronum' . $i] = $value->buybilldetailquantity;
            $_POST['scunitname' . $i] = $value->otherdetailquantity;
            $_POST['proprice' . $i] = $value->buybilldetailprice;
            $_POST['prodis' . $i] = $value->discountvalue;
            $_POST['discounttype' . $i] = $value->discounttype;
            $_POST['hidden_prototal' . $i] = $value->buybilldetailtotalprice;

            $totalBuyBill += $value->buybilldetailtotalprice;
            $i++;
        }
        $_POST['totalBuyBill'] = $totalBuyBill;
        ###### 2- do as do="add"
        $billData = add();
        updateOverallAveragePriceOfProducts($billData);
        $billType = (int) $billData[0];
        $returnBuyBill_Id = $billData[1];
        $buyBill_Id = $billData[2];
        $buyAndReturnBill_Id = $billData[3];

        //
        $saveBtnGoesTo = (int) $_POST["saveBtnGoesTo"];
        $printURL = "";
        if ($saveBtnGoesTo == 1) {
            //save btn clicked, go to new bill after print but you need to print bill too
            switch ($billType) {
                case 1: //ret
                    $printURL = "buyBillprintController.php?do=returneditprint1&id=" . $returnBuyBill_Id;
                    break;
                case 2: //buy
                    $printURL = "buyBillprintController.php?do=editprint&id=" . $buyBill_Id . "&ordertype=" . $ordertype;
                    break;
                case 3: //buy and ret
                    $printURL = "buyBillprintController.php?do=buyandreturneditprint1&id=" . $buyAndReturnBill_Id;
                    break;
            }
        }
        $_SESSION["printURLBuy"] = $printURL;

        $return_url = $_GET['return_url'];
        $billnameid = $_GET['billnameid'];
        if (isset($return_url) && $return_url == 1 && isset($billnameid)) {
            header("location:buyBillController.php?do=bill&billnameid=" . $billnameid);
        } else {
            if ($billType == 1) {
                header("location:returnBuyBillController.php?do=editprint&id=" . $returnBuyBill_Id . "");
            } elseif ($billType == 2) {
                header("location:buyBillController.php?do=editprint&id=" . $buyBill_Id . "");
            } elseif ($billType == 3) {
                header("location:buyAndReturnBillController.php?do=editprint&id=" . $buyAndReturnBill_Id . "");
            }
        }
        $smarty->assign('urldirect', $url);
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "تمت العملية بنجاح";
        } else {
            $note = "operation accomplished successfully";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    }
}
$smarty->assign("linkExcelProducts", 1);
//here the global templates
$smarty->assign("customValidation", 1);
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

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

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

function getBuyBillNames() {
    global $billNameDAO;
    global $billNameExt;
    $type = 1;
    // get all not deleted
    $billNameData = $billNameExt->queryByType($type);
    return $billNameData;
}

function loadBillProperties($billnameid) {
    global $billSettingExt;

    // select all data from Billname
    $billSettingsData = $billSettingExt->queryWithBillnameId($billnameid);

    return $billSettingsData;
}

function getProducts() {
    global $productExt;
    global $productCatDAO;
    global $smarty;
    $categories;
    $productsData = $productExt->queryAllExt();
    if (count($productsData) > 0) {
        $i = 0;
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //print("parentId: ".$parentId."");
            $pathArr = fetch_recursive($parentId, $categories);
            $smarty->assign("names" . $i, $pathArr);
            $i++;
        }
    }
    return $productsData;
}

function fetch_recursive($parentid, $categories) {
    global $productCatExt;
    $catData = $productCatExt->getCategoryAndParentByCatId($parentid);
    //print_r($catData);
    if (count($catData) > 0) {
        $categories .= $catData->productCatName . '/';
        //print("<br>categories: ".$categories."<br>");
        //print_r($catData);
        $newParentId = $catData->productCatParent;
        //print("newParentId: ".$newParentId."<br><br>");
        if ($newParentId != 0 && count($catData) > 0) {
            $newParentName = $catData->parentName;
            $categories .= $newParentName . '/';
            fetch_recursive($newParentId, $categories);
        }
    }
    return $categories;
}

function getSuppliers() {
    global $supplierDAO;
    $suppliersData = $supplierDAO->queryByCondition(0);
    return $suppliersData;
}

function getUnits() {
    global $unitDAO;

    $unitsData = $unitDAO->queryByCondition(0);
    return $unitsData;
}

function getStores() {
    global $storeDAO;
    $storesData = $storeDAO->queryByConditions(0);
    return $storesData;
}

function getStoresOfUser() {
    global $storeExt;
    global $userdata;

    if ($userdata->userstoreid > 0) {
        $storesData = $storeExt->queryByConditions(' and storeId = ' . $userdata->userstoreid);
    } else {
        if ($userdata->storeids == 0) {
            $storesData = $storeExt->queryByConditions();
        } else {
            $storesData = $storeExt->queryByConditions(' and storeId in (' . $userdata->storeids . ')');
        }
    }

    return $storesData;
}

function getProductCatParents() {
    global $productCatExt;
    global $productExt;

    $allParents = $productExt->queryAllCategories(); //$productCatExt->queryAllChildrenExt();
    return $allParents;
}

function checkRoundNumbers() {
    global $programSettingExt;
    $roundNumbersStatus = $programSettingExt->getRoundNumbersStatus();

    return $roundNumbersStatus;
}

function loadSupplierDataById($supplierid) {
    global $supplierDAO;

    //load client by Id tbl
    $supplierData = $supplierDAO->load($supplierid);
    return $supplierData;
}

function addnew($controlname, $oldbuyid, $norbuyBillTotal, $norbuyBillTotal_re) {


    //print_r('<br> in add new');

    global $buyBillExt;
    global $returnBuyBillExt;
    global $buyAndReturnBillExt;
    global $buyBill;
    global $buyBillDAO;
    global $buyBillExt;
    global $buyBillDetail;
    global $buyBillDetailDAO;
    global $buyBillDetailExt;
    global $returnBuyBill;
    global $returnBuyBillDAO;
    global $returnBuyBillDetail;
    global $returnBuyBillDetailDAO;
    global $buyAndReturnBill;
    global $buyAndReturnBillDAO;
    global $buyAndReturnBillDetail;
    global $buyAndReturnBillDetailDAO;
    global $buyAndReturnBillDetailExt;
    //
    global $buyBillCurr;
    global $buyBillCurrDAO;
    global $buyBillCurrEX;
    global $buyAndRuternBillCurr;
    global $buyAndRuternBillCurrDAO;
    global $buyAndRuternBillCurrEX;
    global $returnBuyBllCurr;
    global $returnBuyBllCurrDAO;
    global $returnBuyBllCurrEX;
    global $saveExt;
    //
    global $supplierDAO;
    global $ProgramsettingDAO;
    global $productExt;

    global $CostcenterdetailDAO;
    global $Costcenterdetail;

    global $supplierDAO;
    global $supplierExt;
    global $accountsTreeDAO;
    global $accountsTree;

    global $accountsTreeDAO2;
    global $accountsTree2;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;
    global $dailyEntryCreditorDAO;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor2;
    global $dailyEntryCreditorDAO2;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;

    global $today;

    global $mySave;
    global $mySaveRecord;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;
    //
    global $buyPricesHistoryBookDAO;
    global $buyPricesHistoryBookEX;
    //
    global $ProductserialDAO;
    global $ProductserialEX;

    global $buyBillOfferDAO;
    global $buyBillOfferEX;
    global $buyBillDetailOfferDAO;
    global $buyBillDetailOfferEX;

    global $noOfDecimalPlaces;

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

    $Programsettingdata = $ProgramsettingDAO->load(1);
    $billnameId = $_POST['billnameid'];
    $saveid = (int) $_POST['saveid'];
    if (!isset($_POST['saveid']) || empty($saveid)) {
        $saveid = $_SESSION['saveid'];
    }
    $client = (int) $_POST['client'];

    //settings
    $returnBillSetting = $_POST['returnBillSetting'];
    $storeSetting = $_POST['storeSetting'];
    $dateSetting = $_POST['dateSetting'];
    $noteSetting = $_POST['noteSetting'];
    $productDiscountSetting = $_POST['productDiscountSetting'];
    $Costcenterid = isset($_POST["Costcenter"]) ? $_POST["Costcenter"] : -1;
    //
    $currencyId = (int) $_POST["currencyId"];
    $cFactor = (float) $_POST["cFactor"];
    //
    $dailyentryid = $_POST["dailyentryid"];
    $buybillsupplierid = $_POST["buybillsupplierid"];

    $returndailyEntryId = filter_input(INPUT_POST, 'returndailyEntryId');
    //Date
    if ($dateSetting == 0) {
        $buybillDate = $_POST['bn'];
    } else {
        $buybillDate = date("Y-m-d H:i:s");
    }

    //Store
    if ($storeSetting == 0) {

        $storeId = $_POST['storeId'];
    } else {
        $storeId = 1;
    }

    //post variables

    $pay_num = $_POST['pay_num'];
    $supplierId = $_POST['supplier'];
    $supdata = $supplierDAO->load($supplierId); // رصيد المورد

    $totaldeptbefore = $supdata->suppliercurrentDebtInCurrency; //$_POST['hidden_debt'];
    $totaldeptbeforeInMainCurr = $supdata->suppliercurrentDebt; //$_POST['hidden_debt'];
    //print_r('totaldeptbefore'.$totaldeptbefore.'<br>');
    $pay_num_optional = $_POST['pay_num_optional'];
    $comment = $_POST['comment'];

    $totalbill = $_POST['totalbeforediscount']; //إجمالي الفاتورة
    $discount_type = $_POST['discount_type']; //نوع الخصم
    $addition_type = $_POST['addition_type']; //نوع الاضافة
    $genaddition = $_POST['genaddition']; //قيمة الاضافة
    $gendis = $_POST['gendis']; //قيمة الخصم
    $taxOfDiscountPer = (float) $_POST['taxOfDiscountPercentage'];
    $taxOfDiscountVal = (float) $_POST['taxOfDiscountVal'];
    $aftertotalbill = $_POST['totalafterdiscount']; // المتبقى


    $payedtax = $_POST['payedtax']; //المدفوع$noOfDecimalPlaces
    $taxVal = $_POST['taxVal'];

    $totalpayed = $_POST['genpay']; //المدفوع
    $remin = $aftertotalbill - $totalpayed;
    ##curr conversion
    $reminInMainCurrency = $remin;
    if ($currencyId > 1) {
        $reminInMainCurrency = $remin / $cFactor;
    }

    $totaldeptafter = $totaldeptbefore + $remin; //$_POST['supplierdebtafter']; //إجمالي المديونية
    $totaldeptafterInMainCurr = $totaldeptbeforeInMainCurr + $reminInMainCurrency; //$_POST['supplierdebtafter']; //إجمالي المديونية
    //print_r('totaldeptafter'.$totaldeptafter.'<br>');
    //print_r('totaldeptafter'.$totaldeptafter.'<br>');
    ## values needed for mean and last buy price with discount #############
    ##get $billTotalBeforeDiscount
    $billTotalBeforeDiscount = $totalbill;
    ##get $billDiscountVal
    $billDiscountVal = $gendis;
    if ($discount_type == "1") {
        $billDiscountVal = ($gendis / 100) * $billTotalBeforeDiscount;
        $billDiscountVal = round($billDiscountVal, $noOfDecimalPlaces);
    }
    ##get addition val
    $billAdditionVal = $genaddition;
    if ($addition_type == "1") {
        $billAdditionVal = ($genaddition / 100) * $billTotalBeforeDiscount;
        $billAdditionVal = round($billAdditionVal, $noOfDecimalPlaces);
    }
//        //to affect price
//        //$billDiscountVal -= $billAdditionVal;
    ########################################################################

    $tabelname = '';
    $islast = 0;
    if ($controlname == "buyBillController.php") {
        $tabelname = 'buybill';
        $xid = $buyBillExt->querylastid($tabelname);
        if ($xid->buybillid == $oldbuyid) {
            $islast = 1;
        }
    } elseif ($controlname == "buyAndReturnBillController.php") {
        $tabelname = 'buyandruternbill';
        $xid = $buyBillExt->querylastid($tabelname);
        if ($xid->buybillid == $oldbuyid) {
            $islast = 1;
        }
    }
    /* 	print_r('<br>xid'.$xid->buybillid);
      print_r('<br>oldbuyid'.$oldbuyid);
      print_r('<br>islast'.$islast); */
    $finalbill;
    if ($aftertotalbill > 0) {
        $finalbill = $aftertotalbill - $totalpayed; // المتبقي
    } else {
        $finalbill = $aftertotalbill + $totalpayed; // المتبقي
    }

    if (empty($pay_num)) {
        $serial = $pay_num_optional;
    } else {
        $serial = $pay_num;
    }


    $buyItr = $_POST['hidden_itr']; //buy bill iteration
    $returnBuyItr = $_POST['hidden_itr_re'];

    $buyBillFlag = 0;
    $returnBuyBillFlag = 0;

    for ($i = 1; $i <= $buyItr; $i++) {
        $productIdxxx = $_POST['product' . $i];
        if (strpos($productIdxxx, "hasSizeColor") !== false) {
            $productIdxxx = 1; //this shows there is product
        }
        $proprice = $_POST['proprice' . $i];
        if ($productIdxxx > 0) {
            $buyBillFlag += 1;
        }
    }

    for ($i = 1; $i <= $returnBuyItr; $i++) {
        $productIdxxx = $_POST['product_re' . $i];
        if (strpos($productIdxxx, "hasSizeColor") !== false) {
            $productIdxxx = 1; //this shows there is product
        }
        $proprice = $_POST['proprice_re' . $i];
        if ($productIdxxx > 0) {
            $returnBuyBillFlag += 1;
        }
    }

    ##curr conversion
    $billCurrInsertId = 0;
    $saveData = $saveExt->loadForUpdateEx($saveid);
    $saveConversionFactor = $saveData->conversionFactor;
    $buybilldiscountC = $gendis;
    $genadditionC = $genaddition;
    $buybilltotalbillC = $totalbill;
    $buybillaftertotalbillC = $aftertotalbill;
    $buybilltotalpayedC = $totalpayed;
    $buybillfinalbillC = $finalbill;
    $buybilldirectpaymentC = 1;
    $payedtaxC = $payedtax;
    if ($currencyId > 1) {
        $gendis = $gendis / $cFactor;
        $genaddition = $genaddition / $cFactor;
        $totalbill = $totalbill / $cFactor;
        $aftertotalbill = $aftertotalbill / $cFactor;
        $totalpayed = $totalpayed / $cFactor;
        $finalbill = $finalbill / $cFactor;
        $buybilldirectpaymentC = 1;
        //$payedtax = $payedtax / $cFactor;
    }
    ###################################################
    //($controlname,$oldbuyid,$norbuyBillTotal,$norbuyBillTotal_re)
    if ($ordertype == 0) { //bill
        if ($norbuyBillTotal_re > 0 && $norbuyBillTotal > 0) {

            print_r('in if <br>');
            if (!empty($buyItr) && $buyItr != 0 && $buyBillFlag != 0 && !empty($returnBuyItr) && $returnBuyItr != 0 && $returnBuyBillFlag != 0) {
                ##fatma
                if ($aftertotalbill < 0) { //return part is more
                    $reminInMainCurrency = $aftertotalbill + $totalpayed;
                    ##curr conversion
                    $remin = $reminInMainCurrency;
                    if ($currencyId > 1) {
                        $remin = $reminInMainCurrency * $cFactor;
                    }

                    $totaldeptafter = $totaldeptbefore + $remin; //$_POST['supplierdebtafter']; //إجمالي المديونية
                    $totaldeptafterInMainCurr = $totaldeptbeforeInMainCurr + $reminInMainCurrency; //$_POST['supplierdebtafter']; //إجمالي المديونية
                }

                //buyAndReturnBill
                $billType = 3;
                //print("<br>buyAndReturnBill<br>");
                //                try {
                //insert into buybill tbl
                $buyAndReturnBill->billnameid = $billnameId;
                $buyAndReturnBill->buybillaftertotalbill = $aftertotalbill;
                $buyAndReturnBill->buybilldate = $buybillDate;
                $buyAndReturnBill->userid = $_SESSION['userid'];
                $buyAndReturnBill->buybillclientname = "";
                $buyAndReturnBill->buybilldirectpayment = 1;
                $buyAndReturnBill->buybilldiscount = $gendis;
                $buyAndReturnBill->buybilldiscountrype = $discount_type;
                $buyAndReturnBill->buybillfinalbill = $finalbill;
                $buyAndReturnBill->buybillsaveid = $saveid;
                $buyAndReturnBill->buybillSerial = $serial;
                $buyAndReturnBill->buybillstoreid = $storeId;
                $buyAndReturnBill->buybillsupplierid = $supplierId;
                $buyAndReturnBill->buybillsysdate = $today;
                $buyAndReturnBill->buybilltotalbill = $totalbill;
                $buyAndReturnBill->buybilltotaldeptafter = $totaldeptafter;
                $buyAndReturnBill->buybilltotaldeptbefor = $totaldeptbefore;
                $buyAndReturnBill->buybilltotalpayed = $totalpayed;
                $buyAndReturnBill->conditions = 0;
                $buyAndReturnBill->deletedbuyid = $oldbuyid;
                $buyAndReturnBill->controlname = $controlname;
                $buyAndReturnBill->payedtax = $payedtax;
                $buyAndReturnBill->taxOfDiscountPer = $taxOfDiscountPer;
                $buyAndReturnBill->taxOfDiscountVal = $taxOfDiscountVal;
                $buyAndReturnBill->costcenterid = $Costcenterid;
                $buyAndReturnBill->dailyentryid = 0;
                $buyAndReturnBill->comment = $comment;
                $buyAndReturnBill->currencyId = $currencyId;
                $buyAndReturnBill->client = $client;
                $buyAndReturnBill->buybilladdition = $genaddition;
                $buyAndReturnBill->buybilladditiontrype = $addition_type;



                $buyAndReturnBill_Id = $buyAndReturnBillExt->insertEX($buyAndReturnBill);
                ##curr conversion
                if ($currencyId > 1) {
                    $buyAndRuternBillCurr->buybillid = $buyAndReturnBill_Id;
                    $buyAndRuternBillCurr->conversionFactor = $cFactor;
                    $buyAndRuternBillCurr->buybilldiscountC = $buybilldiscountC;
                    $buyAndRuternBillCurr->buybilltotalbillC = $buybilltotalbillC;
                    $buyAndRuternBillCurr->buybillaftertotalbillC = $buybillaftertotalbillC;
                    $buyAndRuternBillCurr->buybilltotalpayedC = $buybilltotalpayedC;
                    $buyAndRuternBillCurr->buybillfinalbillC = $buybillfinalbillC;
                    $buyAndRuternBillCurr->buybilldirectpaymentC = $buybilldirectpaymentC;
                    $buyAndRuternBillCurr->payedtaxC = $payedtaxC;
                    $buyAndRuternBillCurr->saveConversionFactor = $saveConversionFactor;
                    $buyAndRuternBillCurr->buybilladditionC = $genadditionC;
                    $billCurrInsertId = $buyAndRuternBillCurrDAO->insert($buyAndRuternBillCurr);
                }


                $Costcenterdetail->costamount = $aftertotalbill;
                $Costcenterdetail->costcenterid = $Costcenterid;
                $Costcenterdetail->costdate = date('Y-m-d');
                $Costcenterdetail->del = 0;
                $Costcenterdetail->modelid = $buyAndReturnBill_Id;
                $Costcenterdetail->processname = 'فاتوره مشتريات ومردودات';
                $Costcenterdetail->tablename = 'buyAndReturnBillController.php';
                $Costcenterdetail->type = 5;
                $Costcenterdetail->uesrid = $_SESSION['userid'];

                if ($Costcenterid != -1 && $Costcenterid != '-1') {
                    $CostcenterdetailDAO->insert($Costcenterdetail);
                }



                for ($j = 1; $j <= $buyItr; $j++) {
                    $parcode = $_POST['parcode' . $j];
                    $prstorid = $_POST['prstorid' . $j];
                    if (isset($prstorid) && $prstorid != -1 && (int) $prstorid > 0) {
                        $storeId = $prstorid;
                    } else {
                        $storeId = $_POST['storeId'];
                    }
                    $productId = $_POST['product' . $j];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeId, $sizeId, $colorId);
                    }
                    $unitId = $_POST['unitId' . $j];
                    $proprice = $_POST['proprice' . $j];
                    $pronum = $_POST['pronum' . $j];
                    $prototal = $_POST['hidden_prototal' . $j];
                    $note = $_POST['note' . $j];
                    $prodis = $_POST['prodis' . $j];
                    $discounttype = $_POST['discounttype' . $j];
                    $rowtaxper = $_POST['rowtaxper' . $j];
                    $rowtaxval = $_POST['rowtaxval' . $j];
                    $scunitname = $_POST['scunitname' . $j];


                    if (!empty($productId) && $productId != '-1') {
                        $catId = getProductCatId($productId);


                        if (!empty($buyAndReturnBill_Id)) {
                            $buyAndReturnBillDetail->billtype = 0;
                            $buyAndReturnBillDetail->buybilldetailcatid = $catId;
                            $buyAndReturnBillDetail->buybilldetaildate = $today;
                            $buyAndReturnBillDetail->buybillid = $buyAndReturnBill_Id;
                            $buyAndReturnBillDetail->buybilldetailprice = $proprice;
                            $buyAndReturnBillDetail->buybilldetailquantity = $pronum;
                            $buyAndReturnBillDetail->buybilldetailproductid = $productId;
                            $buyAndReturnBillDetail->buybilldetailtotalprice = $prototal;
                            $buyAndReturnBillDetail->discountvalue = $prodis;
                            $buyAndReturnBillDetail->discounttype = $discounttype;
                            $buyAndReturnBillDetail->note = $note;
                            $buyAndReturnBillDetail->parcode = $parcode;
                            $buyAndReturnBillDetail->productunitid = $unitId;
                            $buyAndReturnBillDetail->otherdetailquantity = $scunitname;
                            $buyAndReturnBillDetail->sizeid = $sizeId;
                            $buyAndReturnBillDetail->colorid = $colorId;
                            $buyAndReturnBillDetail->rowtaxper = $rowtaxper;
                            $buyAndReturnBillDetail->rowtaxval = $rowtaxval;
                            $buyAndReturnBillDetail->storeid = $storeId;
                            ##curr conversion
                            $buyAndReturnBillDetail->buybilldetailpriceC = $buyAndReturnBillDetail->buybilldetailprice;
                            $buyAndReturnBillDetail->buybilldetailtotalpriceC = $buyAndReturnBillDetail->buybilldetailtotalprice;
                            $buyAndReturnBillDetail->discountvalueC = $buyAndReturnBillDetail->discountvalue;
                            if ($currencyId > 1) {
                                $proprice = $proprice / $cFactor;
                                $prototal = $prototal / $cFactor;
                                $prodis = $prodis / $cFactor;
                                $buyAndReturnBillDetail->buybilldetailprice = $proprice;
                                $buyAndReturnBillDetail->buybilldetailtotalprice = $prototal;
                                $buyAndReturnBillDetail->discountvalue = $prodis;
                            }
                            ##############################################

                            $detailId = $buyAndReturnBillDetailDAO->insert($buyAndReturnBillDetail);
                        }


                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            $productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
                            $productnumber = $productunitData->productnumber;
                            $finalquantity = $pronum * $productnumber;


                            $issold = $ProductserialEX->queryallisdSerial($productId, $parcode, " and sizeid=$sizeId and colorid=$colorId ");
                            if (count($issold) > 0) {
                                $myProductserial->productserailid = $issold->productserailid;
                                $myProductserial->don = $issold->don + $finalquantity;
                                $ProductserialEX->updateDon($myProductserial);
                            }

                            //
                            $prototalWithDiscount = $prototal - ($billDiscountVal * ($prototal / $billTotalBeforeDiscount));
                            $buyPrice = round(($prototalWithDiscount / $finalquantity), $noOfDecimalPlaces); //$buyAndReturnBillDetail->buybilldetailprice / $productnumber; //$buyBillDetail->buybilldetailtotalprice/$finalquantity;
                            increaseBuyPricesHistoryBookBuyQuantity($buyAndReturnBill->buybilldate, $buyAndReturnBill->buybillstoreid, $buyAndReturnBillDetail->buybilldetailproductid, $buyAndReturnBillDetail->sizeid, $buyAndReturnBillDetail->colorid, $buyPrice, $finalquantity);

                            if ($islast > 0) {
                                if ($Programsettingdata->updateproductprice == 0) {
                                    $finalprice = $prototal / $finalquantity;
                                    updateproductpriceFunc($productId, $finalprice);
                                }
                            }
                            //****************** Update product quantity in store ************************//
                            //get store productquantity before change
                            $storeDetailData = getStoreDetails($storeId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

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

                            $buyAndReturnBillDetailExt->updatequantityBefore($productQuantityBefore, $detailId);

                            if (count($allStoredetailData) > 0) {
                                //update productquantity in storedetail
                                $productQuantityAfter = increaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity, $proprice, $productnumber, "buybilldetailid", $detailId, $productId, "buyandruternbilldetail", $operation, $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId, $rowtaxval, $payedtax, $cFactor);

                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 0, $buyAndReturnBill_Id, "اضافة فاتورة مشتريات ومردودات", "buyAndReturnBillController.php", $buybillDate, $sizeId, $colorId);
                            } else {
                                //insert in storedetail tbl
                                insertStoredetailupdate($storeId, $productId, $finalquantity, $buybillDate, $sizeColorStoreDetailId, $sizeId, $colorId, $proprice, $productnumber, "buybilldetailid", $detailId, "buyandruternbilldetail", $operation, $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $rowtaxval, $payedtax, $cFactor);

                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, $finalquantity, 0, $finalquantity, 0, $buyAndReturnBill_Id, "اضافة فاتورة مشتريات ومردودات", "buyAndReturnBillController.php", $buybillDate, $sizeId, $colorId);
                            }


                            $allStoredetailData2 = getStoreDetails($storeId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                            $allStoredetailDataother = $allStoredetailData2[0];
                            $storeDetailIdother = $allStoredetailData2[1];
                            $productQuantityBeforeother = $allStoredetailData2[2];



                            if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                //update productquantity in storedetail
                                print_r('in if');
                                $finalquantityother = $productQuantityBeforeother + $scunitname;
                                $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                //insert in storereport
                                insertStorereportupdate2($productId, $storeId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $buyAndReturnBill_Id, "اضافة فاتورة  مشتريات ومردودات", "buyAndReturnBillController.php", $buybillDate, 1);
                            } else {
                                //insert in storedetail tbl
                                if ($scunitname > 0) {
                                    insertStoredetailupdate2($storeId, $productId, $scunitname, $buybillDate, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $storeId, $scunitname, 0, $scunitname, 0, $buyAndReturnBill_Id, "اضافة فاتورة  مشتريات ومردودات", "buyAndReturnBillController.php", $buybillDate, 1);
                                }
                            }
                        }
                    }
                }

                for ($y = 1; $y <= $returnBuyItr; $y++) {
                    $parcode = $_POST['parcode_re' . $y];
                    $prstorid = $_POST['reprstorid' . $j];
                    if (isset($prstorid) && $prstorid != -1 && (int) $prstorid > 0) {
                        $storeId = $prstorid;
                    } else {
                        $storeId = $_POST['storeId'];
                    }
                    $productId = $_POST['product_re' . $y];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeId, $sizeId, $colorId);
                    }
                    $unitId = $_POST['unitId_re' . $y];
                    $proprice = $_POST['proprice_re' . $y];
                    $pronum = $_POST['pronum_re' . $y];
                    $prototal = $_POST['hidden_prototal_re' . $y];
                    $note = $_POST['note_re' . $y];
                    $prodis = $_POST['prodis_re' . $y];
                    $discounttype = $_POST['discounttype_re' . $y];
                    $rowtaxper = $_POST['rowtaxper_re' . $y];
                    $rowtaxval = $_POST['rowtaxval_re' . $y];
                    $scunitname = $_POST['scunitname_re' . $y];


                    if (!empty($productId) && $productId != '-1') {
                        $catId = getProductCatId($productId);

                        if (!empty($buyAndReturnBill_Id)) {
                            $buyAndReturnBillDetail->billtype = 1;
                            $buyAndReturnBillDetail->buybilldetailcatid = $catId;
                            $buyAndReturnBillDetail->buybilldetaildate = $today;
                            $buyAndReturnBillDetail->buybillid = $buyAndReturnBill_Id;
                            $buyAndReturnBillDetail->buybilldetailprice = $proprice;
                            $buyAndReturnBillDetail->buybilldetailquantity = $pronum;
                            $buyAndReturnBillDetail->buybilldetailproductid = $productId;
                            $buyAndReturnBillDetail->buybilldetailtotalprice = $prototal;
                            $buyAndReturnBillDetail->discountvalue = $prodis;
                            $buyAndReturnBillDetail->discounttype = $discounttype;
                            $buyAndReturnBillDetail->productunitid = $unitId;
                            $buyAndReturnBillDetail->note = $note;
                            $buyAndReturnBillDetail->parcode = $parcode;
                            $buyAndReturnBillDetail->otherdetailquantity = $scunitname;
                            $buyAndReturnBillDetail->sizeid = $sizeId;
                            $buyAndReturnBillDetail->colorid = $colorId;
                            $buyAndReturnBillDetail->rowtaxper = $rowtaxper;
                            $buyAndReturnBillDetail->rowtaxval = $rowtaxval;
                            $buyAndReturnBillDetail->storeid = $storeId;
                            ##curr conversion
                            $buyAndReturnBillDetail->buybilldetailpriceC = $buyAndReturnBillDetail->buybilldetailprice;
                            $buyAndReturnBillDetail->buybilldetailtotalpriceC = $buyAndReturnBillDetail->buybilldetailtotalprice;
                            $buyAndReturnBillDetail->discountvalueC = $buyAndReturnBillDetail->discountvalue;
                            if ($currencyId > 1) {
                                $proprice = $proprice / $cFactor;
                                $prototal = $prototal / $cFactor;
                                $prodis = $prodis / $cFactor;
                                $buyAndReturnBillDetail->buybilldetailprice = $proprice;
                                $buyAndReturnBillDetail->buybilldetailtotalprice = $prototal;
                                $buyAndReturnBillDetail->discountvalue = $prodis;
                            }
                            ######################################

                            $detailId = $buyAndReturnBillDetailDAO->insert($buyAndReturnBillDetail);
                        }

                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            //****************** Update product quantity in store ************************//
                            //get store productquantity before change
                            $storeDetailData = getStoreDetails($storeId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

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


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

                            $issold = $ProductserialEX->queryallisdSerial($productId, $parcode, " and sizeid=$sizeId and colorid=$colorId ");
                            if (count($issold) > 0) {
                                $myProductserial->productserailid = $issold->productserailid;
                                $myProductserial->don = $issold->don - $finalquantity;
                                $ProductserialEX->updateDon($myProductserial);
                            }

                            if (count($allStoredetailData) > 0) {

                                $productQuantityAfter = decreaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity, $proprice, $productnumber, "buybilldetailid", $detailId, $productId, "buyandruternbilldetail", "addnew", $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId, $rowtaxval, $payedtax, $cFactor);
                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 1, $buyAndReturnBill_Id, "اضافة فاتورة مشتريات ومردودات", "buyAndReturnBillController.php", $buybillDate, $sizeId, $colorId);
                            } else {
                                //insert in storedetail tbl
                                insertStoredetailupdate($storeId, $productId, (abs($finalquantity) * -1), $buybillDate, $sizeColorStoreDetailId, $sizeId, $colorId, $proprice, $productnumber, "buybilldetailid", $detailId, "buyandruternbilldetail", "addnew", $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $rowtaxval, $payedtax, $cFactor);

                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, (abs($finalquantity) * -1), 0, (abs($finalquantity) * -1), 1, $buyAndReturnBill_Id, "اضافة فاتورة مشتريات ومردودات", "buyAndReturnBillController.php", $buybillDate, $sizeId, $colorId);
                            }

                            $allStoredetailData2 = getStoreDetails($storeId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                            $allStoredetailDataother = $allStoredetailData2[0];
                            $storeDetailIdother = $allStoredetailData2[1];
                            $productQuantityBeforeother = $allStoredetailData2[2];



                            if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                //update productquantity in storedetail
                                print_r('in if');
                                $finalquantityother = $productQuantityBeforeother - $scunitname;
                                $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                //insert in storereport
                                insertStorereportupdate2($productId, $storeId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $buyAndReturnBill_Id, "اضافة فاتورة  مشتريات ومردودات", "buyAndReturnBillController.php", $buybillDate, 1);
                            } else {
                                //insert in storedetail tbl
                                if ($scunitname > 0) {
                                    insertStoredetailupdate2($storeId, $productId, ($scunitname) * -1, $buybillDate, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $storeId, $scunitname, 0, ($scunitname) * -1, 0, $buyAndReturnBill_Id, "اضافة فاتورة  مشتريات ومردودات", "buyAndReturnBillController.php", $buybillDate, 1);
                                }
                            }
                        }
                    }
                }

                //****************** Update supplier dept ************************//
                //check if supplier deptAfter change from  supplier deptBefore
                //if($totaldeptafter != $totaldeptbefore)
                //{
                //update supplierdebt
                updateSupplierDebt($supplierId, $totaldeptafter, $totaldeptafterInMainCurr);
                if ($buyAndReturnBill->buybilltotalbill > 0) {
                    insertSupplierDebtChange($supplierId, $totaldeptbefore, $totaldeptbeforeInMainCurr, $finalbill, $buybillfinalbillC, 0, "اضافة فاتورة مشتريات ومردودات مشتريات", $buyAndReturnBill_Id, $totaldeptafter, $totaldeptafterInMainCurr, "buyAndReturnBillController.php", "اضافة فاتورة مشتريات ومردودات مشتريات", $buybillDate);
                } else {
                    insertSupplierDebtChange($supplierId, $totaldeptbefore, $totaldeptbeforeInMainCurr, abs($finalbill), abs($buybillfinalbillC), 1, "اضافة فاتورة مشتريات ومردودات مشتريات", $buyAndReturnBill_Id, $totaldeptafter, $totaldeptafterInMainCurr, "buyAndReturnBillController.php", "اضافة فاتورة مشتريات ومردودات مشتريات", $buybillDate);
                }
                //}
                //****************** Update save value ************************//
                //check if payed or not to change the save value
                //if($totalpayed > 0)
                //{
                if ($aftertotalbill > 0) {
                    //get saveValue before and saveValue after minus totalPayed
                    $saveData = getSaveValueAndMins($saveid, $totalpayed, $saveConversionFactor);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];
                    ##curr conversion
                    $totalpayedSaveCurr = $saveData[3];
                    $saveConversionFactor = $saveData[4];
                    if ($currencyId > 1 && $billCurrInsertId > 0) {
                        $buyAndRuternBillCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                    }

                    //update saveFrom value after add transfer
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from savefrom
                    $_SESSION['client_id'] = $supplierId;
                    insertSavedailyupdate($saveValuebefore, $totalpayedSaveCurr, 1, $saveId, "اضافة فاتورة مشتريات ومردودات مشتريات", $buyAndReturnBill_Id, $saveValueafter, "buyAndReturnBillController.php", $buybillDate);
                    unset($_SESSION['client_id']);
                } else {
                    //get saveValue before and saveValue after plus totalPayed
                    $saveData = getSaveValueAndPlus($saveid, $totalpayed, $saveConversionFactor);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];
                    ##curr conversion
                    $totalpayedSaveCurr = $saveData[3];
                    $saveConversionFactor = $saveData[4];
                    if ($currencyId > 1 && $billCurrInsertId > 0) {
                        $buyAndRuternBillCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                    }

                    //update saveFrom value after add transfer
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from savefrom
                    $_SESSION['client_id'] = $supplierId;
                    insertSavedailyupdate($saveValuebefore, $totalpayedSaveCurr, 0, $saveId, "اضافة فاتورة مشتريات ومردودات مشتريات", $buyAndReturnBill_Id, $saveValueafter, "buyAndReturnBillController.php", $buybillDate);
                    unset($_SESSION['client_id']);
                }

                //}
                //                } catch (Exception $e) {
                //                    //	header("location:?do=error");
                //                    //echo $e;
                //                }
            }
        }


        //return buy bill only
        if ($norbuyBillTotal_re > 0 && (!isset($norbuyBillTotal) || $norbuyBillTotal == 0)) {


            if ($buyItr == 0 || $buyBillFlag == 0) { //return buy bill only
                ##fatma
                $reminInMainCurrency = $aftertotalbill + $totalpayed;
                ##curr conversion
                $remin = $reminInMainCurrency;
                if ($currencyId > 1) {
                    $remin = $reminInMainCurrency * $cFactor;
                }

                $totaldeptafter = $totaldeptbefore + $remin; //$_POST['supplierdebtafter']; //إجمالي المديونية
                $totaldeptafterInMainCurr = $totaldeptbeforeInMainCurr + $reminInMainCurrency; //$_POST['supplierdebtafter']; //إجمالي المديونية

                $billType = 1;
//                print_r('<br>return buy bill only');
                //                try {
                //insert into returnbuybill tbl
                $returnBuyBill->billnameid = $billnameId;
                $returnBuyBill->conditions = 0;
                $returnBuyBill->returnbuybillaftertotalbill = $aftertotalbill;
                $returnBuyBill->returnbuybilldate = $buybillDate;
                $returnBuyBill->returnbuybilldirectpayment = 1;
                $returnBuyBill->returnbuybilldiscountrype = $discount_type;
                $returnBuyBill->returnbuybilldiscount = $gendis;
                $returnBuyBill->returnbuybillfinalbill = $finalbill;
                $returnBuyBill->returnbuybillsaveid = $saveid;
                $returnBuyBill->returnbuybillSerial = $serial;
                $returnBuyBill->returnbuybillstoreid = $storeId;
                $returnBuyBill->returnbuybillsupplierid = $supplierId;
                $returnBuyBill->returnbuybillsysdate = $today;
                $returnBuyBill->returnbuybilltotalbill = $totalbill;
                $returnBuyBill->returnbuybilltotaldeptafter = $totaldeptafter;
                $returnBuyBill->returnbuybilltotaldeptbefor = $totaldeptbefore;
                $returnBuyBill->returnbuybilltotalpayed = $totalpayed;
                $returnBuyBill->userid = $_SESSION['userid'];
                $returnBuyBill->payedtax = $payedtax;
                $returnBuyBill->taxOfDiscountPer = $taxOfDiscountPer;
                $returnBuyBill->taxOfDiscountVal = $taxOfDiscountVal;
                $returnBuyBill->dailyentryid = $dailyentryid;



                $returnBuyBill->deletedbuyid = $oldbuyid;
                $returnBuyBill->controlname = $controlname;
                $returnBuyBill->costcenterid = $Costcenterid;
                $returnBuyBill->comment = $comment;
                $returnBuyBill->currencyId = $currencyId;
                $returnBuyBill->client = $client;
                $returnBuyBill->returnbuybilladdition = $genaddition;
                $returnBuyBill->returnbuybilladditiontrype = $addition_type;

                $returnBuyBill_Id = $returnBuyBillExt->insertEX($returnBuyBill);
                ##curr conversion
                if ($currencyId > 1) {
                    $returnBuyBllCurr->buybillid = $returnBuyBill_Id;
                    $returnBuyBllCurr->conversionFactor = $cFactor;
                    $returnBuyBllCurr->returnbuybilldiscountC = $buybilldiscountC;
                    $returnBuyBllCurr->returnbuybilltotalbillC = $buybilltotalbillC;
                    $returnBuyBllCurr->returnbuybillaftertotalbillC = $buybillaftertotalbillC;
                    $returnBuyBllCurr->returnbuybilltotalpayedC = $buybilltotalpayedC;
                    $returnBuyBllCurr->returnbuybillfinalbillC = $buybillfinalbillC;
                    $returnBuyBllCurr->returnbuybilldirectpaymentC = $buybilldirectpaymentC;
                    $returnBuyBllCurr->returnpayedtaxC = $payedtaxC;
                    $returnBuyBllCurr->saveConversionFactor = $saveConversionFactor;
                    $returnBuyBllCurr->returnbuybilladditionC = $genadditionC;
                    $billCurrInsertId = $returnBuyBllCurrDAO->insert($returnBuyBllCurr);
                }
                print_r($returnBuyBill_Id . 'ddddddddddddddd');
                $Costcenterdetail->costamount = $aftertotalbill;
                $Costcenterdetail->costcenterid = $Costcenterid;
                $Costcenterdetail->costdate = date('Y-m-d');
                $Costcenterdetail->del = 0;
                $Costcenterdetail->modelid = $returnBuyBill_Id;
                $Costcenterdetail->processname = 'فاتوره مردودات مشتريات';
                $Costcenterdetail->tablename = 'returnBuyBillController.php';
                $Costcenterdetail->type = 4;
                $Costcenterdetail->uesrid = $_SESSION['userid'];

                if ($Costcenterid != -1 && $Costcenterid != '-1') {
                    $CostcenterdetailDAO->insert($Costcenterdetail);
                }


                //   print_r($returnBuyBill);
                for ($j = 1; $j <= $returnBuyItr; $j++) {
                    $parcode = $_POST['parcode_re' . $j];
                    $prstorid = $_POST['reprstorid' . $j];
                    if (isset($prstorid) && $prstorid != -1 && (int) $prstorid > 0) {
                        $storeId = $prstorid;
                    } else {
                        $storeId = $_POST['storeId'];
                    }
                    $productId = $_POST['product_re' . $j];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeId, $sizeId, $colorId);
                    }
                    $unitId = $_POST['unitId_re' . $j];
                    $proprice = $_POST['proprice_re' . $j];
                    $pronum = $_POST['pronum_re' . $j];
                    $prototal = $_POST['hidden_prototal_re' . $j];
                    $note = $_POST['note_re' . $j];
                    $prodis = $_POST['prodis_re' . $j];
                    $discounttype = $_POST['discounttype_re' . $j];
                    $rowtaxper = $_POST['rowtaxper_re' . $j];
                    $rowtaxval = $_POST['rowtaxval_re' . $j];
                    $scunitname = $_POST['scunitname_re' . $j];


                    if (!empty($productId) && $productId != '-1') {
                        $catId = getProductCatId($productId);

                        if (!empty($returnBuyBill_Id)) {
                            $returnBuyBillDetail->discountvalue = $prodis;
                            $returnBuyBillDetail->discounttype = $discounttype;
                            $returnBuyBillDetail->note = $note;
                            $returnBuyBillDetail->parcode = $parcode;
                            $returnBuyBillDetail->returnbuybilldetailcatid = $catId;
                            $returnBuyBillDetail->returnbuybilldetailprice = $proprice;
                            $returnBuyBillDetail->returnbuybilldetailproductid = $productId;
                            $returnBuyBillDetail->returnbuybilldetailquantity = $pronum;
                            $returnBuyBillDetail->returnbuybilldetailtotalprice = $prototal;
                            $returnBuyBillDetail->returnbuybillid = $returnBuyBill_Id;
                            $returnBuyBillDetail->productunitid = $unitId;
                            $returnBuyBillDetail->otherdetailquantity = $scunitname;
                            $returnBuyBillDetail->sizeid = $sizeId;
                            $returnBuyBillDetail->colorid = $colorId;
                            $returnBuyBillDetail->rowtaxper = $rowtaxper;
                            $returnBuyBillDetail->rowtaxval = $rowtaxval;
                            $returnBuyBillDetail->storeid = $storeId;
                            ##curr conversion
                            $returnBuyBillDetail->returnbuybilldetailpriceC = $returnBuyBillDetail->returnbuybilldetailprice;
                            $returnBuyBillDetail->returnbuybilldetailtotalpriceC = $returnBuyBillDetail->returnbuybilldetailtotalprice;
                            $returnBuyBillDetail->discountvalueC = $returnBuyBillDetail->discountvalue;
                            if ($currencyId > 1) {
                                $proprice = $proprice / $cFactor;
                                $prototal = $prototal / $cFactor;
                                $prodis = $prodis / $cFactor;
                                $returnBuyBillDetail->returnbuybilldetailprice = $proprice;
                                $returnBuyBillDetail->returnbuybilldetailtotalprice = $prototal;
                                $returnBuyBillDetail->discountvalue = $prodis;
                            }
                            ##########################################

                            $detailId = $returnBuyBillDetailDAO->insert($returnBuyBillDetail);
                        }


                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            //****************** Update product quantity in store ************************//
                            //get store productquantity before change
                            $storeDetailData = getStoreDetails($storeId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

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


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

                            $issold = $ProductserialEX->queryallisdSerial($productId, $parcode, " and sizeid=$sizeId and colorid=$colorId ");
                            if (count($issold) > 0) {
                                $myProductserial->productserailid = $issold->productserailid;
                                $myProductserial->don = $issold->don - $finalquantity;
                                $ProductserialEX->updateDon($myProductserial);
                            }

                            if (count($allStoredetailData) > 0) {
                                //update productquantity in storedetail
                                print_r('<pre>');
                                print_r('2222222222222222222222');
                                print_r('<pre>');
                                $productQuantityAfter = decreaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity, $proprice, $productnumber, "returnbuybilldetailid", $detailId, $productId, "returnbuybilldetail", "addnew", $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId, $rowtaxval, $payedtax, $cFactor);

                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 1, $returnBuyBill_Id, "اضافة فاتورة مردودات مشتريات", "returnBuyBillController.php", $buybillDate, $sizeId, $colorId);
                            } else {
                                //insert in storedetail tbl
                                insertStoredetailupdate($storeId, $productId, (abs($finalquantity) * -1), $buybillDate, $sizeColorStoreDetailId, $sizeId, $colorId, $proprice, $productnumber, "returnbuybilldetailid", $detailId, "returnbuybilldetail", "addnew", $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $rowtaxval, $payedtax, $cFactor);

                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, (abs($finalquantity) * -1), 0, (abs($finalquantity) * -1), 1, $returnBuyBill_Id, "اضافة فاتورة مردودات مشتريات", "returnBuyBillController.php", $buybillDate, $sizeId, $colorId);
                            }




                            $allStoredetailData2 = getStoreDetails($storeId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                            $allStoredetailDataother = $allStoredetailData2[0];
                            $storeDetailIdother = $allStoredetailData2[1];
                            $productQuantityBeforeother = $allStoredetailData2[2];



                            if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                //update productquantity in storedetail
                                print_r('in if');
                                $finalquantityother = $productQuantityBeforeother - $scunitname;
                                $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                //insert in storereport
                                insertStorereportupdate2($productId, $storeId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $returnBuyBill_Id, "اضافة فاتورة  مردودات شراء", "returnBuyBillController.php", $buybillDate, 1);
                            } else {
                                //insert in storedetail tbl
                                if ($scunitname > 0) {
                                    insertStoredetailupdate2($storeId, $productId, ($scunitname) * -1, $buybillDate, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $storeId, ($scunitname), 0, ($scunitname) * -1, 0, $returnBuyBill_Id, "اضافة فاتورة  مردودات شراء", "returnBuyBillController.php", $buybillDate, 1);
                                }
                            }
                        }
                    }
                }

                //****************** Update supplier dept ************************//
                //check if supplier deptAfter change from  supplier deptBefor
                //if($totaldeptafter != $totaldeptbefore)
                //{
                //update supplierdebt
                updateSupplierDebt($supplierId, $totaldeptafter, $totaldeptafterInMainCurr);

                insertSupplierDebtChangeupdate($supplierId, $totaldeptbefore, $totaldeptbeforeInMainCurr, abs($finalbill), abs($buybillfinalbillC), 1, "اضافة فاتورة مردوات مشتريات", $returnBuyBill_Id, $totaldeptafter, $totaldeptafterInMainCurr, "returnBuyBillController.php", "اضافة فاتورة مردوات مشتريات", $buybillDate);
                //}
                //****************** Update save value ************************//
                //check if payed or not to change the save value
                //if($totalpayed > 0)
                //{
                //print($totalpayed);
                $totalpayed = abs($totalpayed);
                //get saveValue before and saveValue after plus totalPayed
                $saveData = getSaveValueAndPlus($saveid, $totalpayed, $saveConversionFactor);
                $saveId = $saveData[0];
                $saveValuebefore = $saveData[1];
                $saveValueafter = $saveData[2];
                ##curr conversion
                $totalpayedSaveCurr = $saveData[3];
                $saveConversionFactor = $saveData[4];
                if ($currencyId > 1 && $billCurrInsertId > 0) {
                    $returnBuyBllCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                }

                //update saveFrom value after add transfer
                updateSave($saveId, $saveValueafter);

                //insert into savedaily tbl from savefrom
                $_SESSION['client_id'] = $supplierId;
                insertSavedailyupdate($saveValuebefore, $totalpayedSaveCurr, 0, $saveId, "اضافة فاتورة مردوات مشتريات", $returnBuyBill_Id, $saveValueafter, "returnBuyBillController.php", $buybillDate);
                unset($_SESSION['client_id']);

                //}
                //                } catch (Exception $e) {
                //                    //header("location:?do=error");
                //                    echo $e;
                //                }
            }
        }

        //buy bill only
        if ($norbuyBillTotal > 0 && (!isset($norbuyBillTotal_re) || $norbuyBillTotal_re == 0)) {
            if ($returnBuyItr == 0 || $returnBuyBillFlag == 0) {

//                print_r('<br>buy bill only');

                $billType = 2;
                //print("<br>buyBill<br>");
                //                try {
                //insert into buybill tbl
                $buyBill->billnameid = $billnameId;
                $buyBill->conditions = 0;
                $buyBill->buybillaftertotalbill = $aftertotalbill;
                $buyBill->buybilldate = $buybillDate;
                $buyBill->buybilldirectpayment = 1;
                $buyBill->buybilldiscountrype = $discount_type;
                $buyBill->buybilldiscount = $gendis;
                $buyBill->buybillfinalbill = $finalbill;
                $buyBill->buybillsaveid = $saveid;
                $buyBill->buybillSerial = $serial;
                $buyBill->buybillstoreid = $storeId;
                $buyBill->buybillsupplierid = $supplierId;
                $buyBill->buybillsysdate = $today;
                $buyBill->buybilltotalbill = $totalbill;
                $buyBill->buybilltotaldeptafter = $totaldeptafter;
                $buyBill->buybilltotaldeptbefor = $totaldeptbefore;
                $buyBill->buybilltotalpayed = $totalpayed;
                $buyBill->userid = $_SESSION['userid'];
                $buyBill->payedtax = $payedtax;
                $buyBill->taxOfDiscountPer = $taxOfDiscountPer;
                $buyBill->taxOfDiscountVal = $taxOfDiscountVal;
                $buyBill->dailyentryid = 0;


                $buyBill->deletedbuyid = $oldbuyid;
                $buyBill->controlname = $controlname;
                $buyBill->costcenterid = $Costcenterid;
                $buyBill->comment = $comment;
                $buyBill->currencyId = $currencyId;
                $buyBill->client = $client;
                $buyBill->buybilladdition = $genaddition;
                $buyBill->buybilladditiontrype = $addition_type;
                $buyBill->totalBuyDiscountVal = (float) $_POST['totalBuyDiscountVal_hidden'];
                $buyBill->webApiId = (int) $_POST['webApiId'];
                $buyBill->files = $_POST['oldFiles'];
                if (isset($_FILES['files']) && !empty($_FILES['files'])) {
                    $namesArr = uploadfileMultiple('files', '../upload/buyBillFiles', explode(',', $buyBill->files));
                    $buyBill->files = implode(',', $namesArr);
                }

                $buyBill_Id = $buyBillExt->insertEX($buyBill);
                ##curr conversion
                if ($currencyId > 1) {
                    $buyBillCurr->buybillid = $buyBill_Id;
                    $buyBillCurr->conversionFactor = $cFactor;
                    $buyBillCurr->buybilldiscountC = $buybilldiscountC;
                    $buyBillCurr->buybilltotalbillC = $buybilltotalbillC;
                    $buyBillCurr->buybillaftertotalbillC = $buybillaftertotalbillC;
                    $buyBillCurr->buybilltotalpayedC = $buybilltotalpayedC;
                    $buyBillCurr->buybillfinalbillC = $buybillfinalbillC;
                    $buyBillCurr->buybilldirectpaymentC = $buybilldirectpaymentC;
                    $buyBillCurr->payedtaxC = $payedtaxC;
                    $buyBillCurr->saveConversionFactor = $saveConversionFactor;
                    $buyBillCurr->buybilladditionC = $genadditionC;
                    $billCurrInsertId = $buyBillCurrDAO->insert($buyBillCurr);
                }

                $Costcenterdetail->costamount = $aftertotalbill;
                $Costcenterdetail->costcenterid = $Costcenterid;
                $Costcenterdetail->costdate = date('Y-m-d');
                $Costcenterdetail->del = 0;
                $Costcenterdetail->modelid = $buyBill_Id;
                $Costcenterdetail->processname = 'فاتوره مشتريات';
                $Costcenterdetail->tablename = 'buybillController.php';
                $Costcenterdetail->type = 3;
                $Costcenterdetail->uesrid = $_SESSION['userid'];

                if ($Costcenterid != -1 && $Costcenterid != '-1') {
                    $CostcenterdetailDAO->insert($Costcenterdetail);
                }

                for ($j = 1; $j <= $buyItr; $j++) {
                    $parcode = $_POST['parcode' . $j];
                    $prstorid = $_POST['prstorid' . $j];
                    if (isset($prstorid) && $prstorid != -1 && (int) $prstorid > 0) {
                        $storeId = $prstorid;
                    } else {
                        $storeId = $_POST['storeId'];
                    }
                    $productId = $_POST['product' . $j];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeId, $sizeId, $colorId);
                    }
                    $unitId = $_POST['unitId' . $j];
                    $proprice = $_POST['proprice' . $j];
                    $pronum = $_POST['pronum' . $j];
                    $prototal = $_POST['hidden_prototal' . $j];
                    $note = $_POST['note' . $j];
                    $prodis = $_POST['prodis' . $j];
                    $discounttype = $_POST['discounttype' . $j];
                    $rowtaxper = $_POST['rowtaxper' . $j];
                    $rowtaxval = $_POST['rowtaxval' . $j];
                    $scunitname = $_POST['scunitname' . $j];
                    $probuyDiscountPer = $_POST['probuyDiscountPer' . $j];


                    if (!empty($productId) && $productId != '-1') {
                        $catId = getProductCatId($productId);


//                        print($productId . "<br>scunitname: " . $scunitname . "<br>");


                        if (!empty($buyBill_Id)) {
                            $buyBillDetail->discountvalue = $prodis;
                            $buyBillDetail->discounttype = $discounttype;
                            $buyBillDetail->note = $note;
                            $buyBillDetail->parcode = $parcode;
                            $buyBillDetail->buybilldetailcatid = $catId;
                            $buyBillDetail->buybilldetailprice = $proprice;
                            $buyBillDetail->buybilldetailproductid = $productId;
                            $buyBillDetail->buybilldetailquantity = $pronum;
                            $buyBillDetail->buybilldetailtotalprice = $prototal;
                            $buyBillDetail->buybillid = $buyBill_Id;
                            $buyBillDetail->buybilldetaildate = $today;
                            $buyBillDetail->productunitid = $unitId;
                            $buyBillDetail->otherdetailquantity = $scunitname;
                            $buyBillDetail->sizeid = $sizeId;
                            $buyBillDetail->colorid = $colorId;
                            $buyBillDetail->rowtaxper = $rowtaxper;
                            $buyBillDetail->rowtaxval = $rowtaxval;
                            $buyBillDetail->probuyDiscountPer = $probuyDiscountPer;
                            $buyBillDetail->storeid = $storeId;
                            ##curr conversion
                            $buyBillDetail->buybilldetailpriceC = $buyBillDetail->buybilldetailprice;
                            $buyBillDetail->buybilldetailtotalpriceC = $buyBillDetail->buybilldetailtotalprice;
                            $buyBillDetail->discountvalueC = $buyBillDetail->discountvalue;
                            if ($currencyId > 1) {
                                $proprice = $proprice / $cFactor;
                                $prototal = $prototal / $cFactor;
                                $prodis = $prodis / $cFactor;
                                $buyBillDetail->buybilldetailprice = $proprice;
                                $buyBillDetail->buybilldetailtotalprice = $prototal;
                                $buyBillDetail->discountvalue = $prodis;
                            }
                            ##############################
                            $detailId = $buyBillDetailDAO->insert($buyBillDetail);
                        }



                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            $productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
                            $productnumber = $productunitData->productnumber;
                            $finalquantity = $pronum * $productnumber;

                            //
                            $prototalWithDiscount = $prototal - ($billDiscountVal * ($prototal / $billTotalBeforeDiscount));
                            $buyPrice = round(($prototalWithDiscount / $finalquantity), $noOfDecimalPlaces); //$buyBillDetail->buybilldetailprice / $productnumber; //$buyBillDetail->buybilldetailtotalprice/$finalquantity;
                            increaseBuyPricesHistoryBookBuyQuantity($buyBill->buybilldate, $buyBill->buybillstoreid, $buyBillDetail->buybilldetailproductid, $buyBillDetail->sizeid, $buyBillDetail->colorid, $buyPrice, $finalquantity);

                            //$oldbuyid
                            $queryString = " and billid=$oldbuyid and productid=$productId and sizeid=$sizeId and colorid=$colorId and type=0 and del = 1 order by productserailid asc ";
                            $allSerials = $ProductserialEX->queryAllByQueryString($queryString);
                            if (count($allSerials) > 0) {
                                foreach ($allSerials as $productSerial) {
                                    $ProductserialDAO->delete($productSerial->productserailid);
                                    $productSerial->del = 0;
                                    $productSerial->storeid = $buyBill->buybillstoreid;
                                    $productSerial->billid = $buyBillDetail->buybillid;
                                    $productSerial->buybilldetailid = $detailId;
                                    //$oldDON = $productSerial->don;
                                    //$productSerial->don = $oldDON;//($finalquantity >= $oldDON ) ? $finalquantity : $oldDON;
                                    $ProductserialDAO->insert($productSerial, $productSerial->comment);
                                }
                            }


                            if ($Programsettingdata->updateproductprice == 0) {

                                $finalprice = $prototal / $finalquantity;
                                updateproductpriceFunc($productId, $finalprice);
                            }
                            //****************** Update product quantity in store ************************//
                            //get store productquantity before change
                            $storeDetailData = getStoreDetails($storeId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

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

                            $buyBillDetailExt->updatequantityBefore($productQuantityBefore, $detailId);
                            //print_r($allStoredetailData);

                            if (count($allStoredetailData) > 0) {
                                //update productquantity in storedetail
                                $productQuantityAfter = increaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity, $proprice, $productnumber, "buybilldetailid", $detailId, $productId, "buybilldetail", $operation, $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId, $rowtaxval, $payedtax, $cFactor);
                                //print_r('finalquantity'.$finalquantity.'<br>');
                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 0, $buyBill_Id, "اضافة فاتورة مشتريات", "buyBillController.php", $buybillDate, $sizeId, $colorId);
                            } else {

                                //insert in storedetail tbl
                                insertStoredetailupdate($storeId, $productId, $finalquantity, $buybillDate, $sizeColorStoreDetailId, $sizeId, $colorId, $proprice, $productnumber, "buybilldetailid", $detailId, "buybilldetail", $operation, $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $rowtaxval, $payedtax, $cFactor);

                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, $finalquantity, 0, $finalquantity, 0, $buyBill_Id, "اضافة فاتورة مشتريات", "buyBillController.php", $buybillDate, $sizeId, $colorId);
                            }



                            $allStoredetailData2 = getStoreDetails($storeId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                            $allStoredetailDataother = $allStoredetailData2[0];
                            $storeDetailIdother = $allStoredetailData2[1];
                            $productQuantityBeforeother = $allStoredetailData2[2];



                            if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                //update productquantity in storedetail
                                print_r('in if');
                                $finalquantityother = $productQuantityBeforeother + $scunitname;
                                $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                //insert in storereport
                                insertStorereportupdate2($productId, $storeId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $buyBill_Id, "اضافة فاتورة  مشتريات", "buyBillController.php", $buybillDate, 1);
                            } else {
                                //insert in storedetail tbl
                                if ($scunitname > 0) {
                                    insertStoredetailupdate2($storeId, $productId, $scunitname, $buybillDate, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $storeId, $scunitname, 0, $scunitname, 0, $buyBill_Id, "اضافة فاتورة  مشتريات", "buyBillController.php", $buybillDate, 1);
                                }
                            }
                        }
                    }
                }
                //mark product serials as del
                $ProductserialEX->deleteBybillid($oldbuyid, 0, '');

                //****************** Update supplier dept ************************//
                //check if supplier deptAfter change from  supplier deptBefor
                //if($totaldeptafter != $totaldeptbefore)
                //{
                //update supplierdebt
                updateSupplierDebt($supplierId, $totaldeptafter, $totaldeptafterInMainCurr);

                insertSupplierDebtChange($supplierId, $totaldeptbefore, $totaldeptbeforeInMainCurr, $finalbill, $buybillfinalbillC, 0, "اضافة فاتورة مشتريات", $buyBill_Id, $totaldeptafter, $totaldeptafterInMainCurr, "buyBillController.php", "اضافة فاتورة مشتريات");
                //}
                //****************** Update save value ************************//
                //check if payed or not to change the save value
                if ($totalpayed > 0) {
                    //get saveValue before and saveValue after plus totalPayed
                    $saveData = getSaveValueAndMins($saveid, $totalpayed, $saveConversionFactor);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];
                    ##curr conversion
                    $totalpayedSaveCurr = $saveData[3];
                    $saveConversionFactor = $saveData[4];
                    if ($currencyId > 1 && $billCurrInsertId > 0) {
                        $buyBillCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                    }

                    //update saveFrom value after add transfer
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from savefrom
                    $_SESSION['client_id'] = $supplierId;
                    insertSavedailyupdate($saveValuebefore, $totalpayedSaveCurr, 1, $saveId, "اضافة فاتورة مشتريات", $buyBill_Id, $saveValueafter, "buyBillController.php", $buybillDate);
                    unset($_SESSION['client_id']);
                }
                //                } catch (Exception $e) {
                //                    header("location:?do=error");
                //                    //echo $e;
                //                }
            }
        }
        //قيود اليومية
        foreach (explode(',', $dailyentryid) as $entryid) {
            reverseEntryWithItsID($entryid, 1);
        }
        foreach (explode(',', $returndailyEntryId) as $entryid) {
            reverseEntryWithItsID($entryid, 1);
        }
        doBillDailyEntry($billType, $buyBill_Id, $returnBuyBill_Id, $buyAndReturnBill_Id, $billTotalBeforeDiscount, $storeId, $taxVal, $totalpayed, $saveId, $remin, $supdata, $billDiscountVal, $taxOfDiscountVal, $billAdditionVal);
    } elseif ($ordertype == 1) {
//        print_r('<br>buy bill only');

        $billType = 2;
        //print("<br>buyBill<br>");
        //                try {
        //insert into buybill tbl
        $buyBill->billnameid = $billnameId;
        $buyBill->conditions = 0;
        $buyBill->buybillaftertotalbill = $aftertotalbill;
        $buyBill->buybilldate = $buybillDate;
        $buyBill->buybilldirectpayment = 1;
        $buyBill->buybilldiscountrype = $discount_type;
        $buyBill->buybilldiscount = $gendis;
        $buyBill->buybillfinalbill = $finalbill;
        $buyBill->buybillsaveid = $saveid;
        $buyBill->buybillSerial = $serial;
        $buyBill->buybillstoreid = $storeId;
        $buyBill->buybillsupplierid = $supplierId;
        $buyBill->buybillsysdate = $today;
        $buyBill->buybilltotalbill = $totalbill;
        $buyBill->buybilltotaldeptafter = $totaldeptafter;
        $buyBill->buybilltotaldeptbefor = $totaldeptbefore;
        $buyBill->buybilltotalpayed = $totalpayed;
        $buyBill->userid = $_SESSION['userid'];
        $buyBill->payedtax = $payedtax;
        $buyBill->taxOfDiscountPer = $taxOfDiscountPer;
        $buyBill->taxOfDiscountVal = $taxOfDiscountVal;
        $buyBill->dailyentryid = 0;


        $buyBill->deletedbuyid = $oldbuyid;
        $buyBill->controlname = $controlname;
        $buyBill->costcenterid = $Costcenterid;
        $buyBill->comment = $comment;
        $buyBill->currencyId = $currencyId;
        $buyBill->buybilladdition = $genaddition;
        $buyBill->buybilladditiontrype = $addition_type;


        $buyBill_Id = $buyBillOfferEX->insertEX($buyBill);

        for ($j = 1; $j <= $buyItr; $j++) {
            $parcode = $_POST['parcode' . $j];
            $productId = $_POST['product' . $j];
            $sizeId = 0;
            $colorId = 0;
            $sizeColorStoreDetailId = 0;
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
                $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeId, $sizeId, $colorId);
            }
            $unitId = $_POST['unitId' . $j];
            $proprice = $_POST['proprice' . $j];
            $pronum = $_POST['pronum' . $j];
            $prototal = $_POST['hidden_prototal' . $j];
            $note = $_POST['note' . $j];
            $prodis = $_POST['prodis' . $j];
            $discounttype = $_POST['discounttype' . $j];
            $scunitname = $_POST['scunitname' . $j];


            if (!empty($productId) && $productId != '-1') {
                $catId = getProductCatId($productId);


//                print($productId . "<br>scunitname: " . $scunitname . "<br>");


                if (!empty($buyBill_Id)) {
                    $buyBillDetail->discountvalue = $prodis;
                    $buyBillDetail->discounttype = $discounttype;
                    $buyBillDetail->note = $note;
                    $buyBillDetail->parcode = $parcode;
                    $buyBillDetail->buybilldetailcatid = $catId;
                    $buyBillDetail->buybilldetailprice = $proprice;
                    $buyBillDetail->buybilldetailproductid = $productId;
                    $buyBillDetail->buybilldetailquantity = $pronum;
                    $buyBillDetail->buybilldetailtotalprice = $prototal;
                    $buyBillDetail->buybillid = $buyBill_Id;
                    $buyBillDetail->buybilldetaildate = $today;
                    $buyBillDetail->productunitid = $unitId;
                    $buyBillDetail->otherdetailquantity = $scunitname;
                    $buyBillDetail->sizeid = $sizeId;
                    $buyBillDetail->colorid = $colorId;
                    ##curr conversion
                    $buyBillDetail->buybilldetailpriceC = $buyBillDetail->buybilldetailprice;
                    $buyBillDetail->buybilldetailtotalpriceC = $buyBillDetail->buybilldetailtotalprice;
                    $buyBillDetail->discountvalueC = $buyBillDetail->discountvalue;
                    if ($currencyId > 1) {
                        $proprice = $proprice / $cFactor;
                        $prototal = $prototal / $cFactor;
                        $prodis = $prodis / $cFactor;
                        $buyBillDetail->buybilldetailprice = $proprice;
                        $buyBillDetail->buybilldetailtotalprice = $prototal;
                        $buyBillDetail->discountvalue = $prodis;
                    }
                    ##############################
                    $detailId = $buyBillDetailOfferDAO->insert($buyBillDetail);
                }
            }
        }
    }
    //        if ($_GET['do'] != "update") {
    //            $mytransactions->commit();
    //        }
    //    } catch (Exception $ex) {
    //        if ($_GET['do'] != "update") {
    //            $mytransactions->rollback();
    //        }
    //    }
    return array($billType, $returnBuyBill_Id, $buyBill_Id, $buyAndReturnBill_Id, $ordertype, $billnameId);
}

function add() {
    global $productDAO;
    global $productExt;

    global $buyBill;
    global $buyBillDAO;
    global $buyBillExt;
    global $buyBillDetail;
    global $buyBillDetailDAO;
    global $buyBillDetailExt;
    global $returnBuyBill;
    global $returnBuyBillDAO;
    global $returnBuyBillDetail;
    global $returnBuyBillDetailDAO;
    global $buyAndReturnBill;
    global $buyAndReturnBillDAO;
    global $buyAndReturnBillDetail;
    global $buyAndReturnBillDetailDAO;
    global $buyAndReturnBillDetailExt;
    //
    global $buyBillCurr;
    global $buyBillCurrDAO;
    global $buyBillCurrEX;
    global $buyAndRuternBillCurr;
    global $buyAndRuternBillCurrDAO;
    global $buyAndRuternBillCurrEX;
    global $returnBuyBllCurr;
    global $returnBuyBllCurrDAO;
    global $returnBuyBllCurrEX;
    global $saveExt;

    global $supplierDAO;

    global $Entryproductspurchased;
    global $EntryproductspurchasedDAO;
    global $EntryproductspurchasedEX;

    global $CostcenterEX;
    global $CostcenterDAO;
    global $Costcenter;

    global $CostcenterdetailDAO;
    global $Costcenterdetail;

    global $mySave;
    global $mySaveRecord;


    global $ProgramsettingDAO;
    global $today;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;
    global $dailyEntryCreditorDAO;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor2;
    global $dailyEntryCreditorDAO2;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor2;
    global $dailyEntryDebtorDAO2;

    global $accountsTreeDAO;
    global $accountsTree;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    global $buyBillOfferDAO;
    global $buyBillOfferEX;
    global $buyBillDetailOfferDAO;

    global $myProductserialEx;

    global $noOfDecimalPlaces;

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

        $ordertype = (int) $_POST["ordertype"]; //0 bill , 1 offfer
        $offerId = (int) $_POST["offerId"]; //0 bill , 1 offfer

        $billnameId = $_POST['billnameid'];
        $saveid = (int) $_POST['saveid'];
        if (!isset($_POST['saveid']) || empty($saveid)) {
            $saveid = $_SESSION['saveid'];
        }
        $client = (int) $_POST['client'];
        //settings
        $returnBillSetting = $_POST['returnBillSetting'];
        $storeSetting = $_POST['storeSetting'];
        $dateSetting = $_POST['dateSetting'];
        $noteSetting = $_POST['noteSetting'];
        $productDiscountSetting = $_POST['productDiscountSetting'];
        $totalBuyBill = $_POST['totalBuyBill'];
        $returnBuyBillTotal = $_POST['returnBuyBillTotal'];
        $Programsettingdata = $ProgramsettingDAO->load(1);

        //$smarty->assign("Programsettingdata",$Programsettingdata);
        //Date
        if ($dateSetting == 0) {
            $buybillDate = $_POST['bn'];
        } else {
            $buybillDate = date("Y-m-d H:i:s");
        }

        //Store
        if ($storeSetting == 0) {
            $storeId = $_POST['storeId'];
        } else {
            $storeId = 1;
        }

        //post variables
        $supplierId = $_POST['supplier'];
        $pay_num = $_POST['pay_num'];
        //	$totaldeptbefore = $_POST['hidden_debt'];
        $pay_num_optional = $_POST['pay_num_optional'];
        $comment = $_POST['comment'];

        $totalbill = $_POST['totalbeforediscount']; //إجمالي الفاتورة
        $discount_type = $_POST['discount_type']; //نوع الخصم
        $gendis = $_POST['gendis']; //قيمة الخصم
        $addition_type = $_POST['addition_type']; //نوع الاضافة
        $genaddition = $_POST['genaddition']; //قيمة الاضافة
        $taxOfDiscountPer = (float) $_POST['taxOfDiscountPercentage'];
        $taxOfDiscountVal = (float) $_POST['taxOfDiscountVal'];
        $aftertotalbill = $_POST['totalafterdiscount'];
        $totalpayed = $_POST['genpay']; //المدفوع
        $payedtax = $_POST['payedtax'];
        $taxVal = $_POST['taxVal'];
        $Costcenterid = isset($_POST["Costcenter"]) ? $_POST["Costcenter"] : -1;
        $currencyId = (int) $_POST["currencyId"];
        $cFactor = (float) $_POST["cFactor"];
        //  print_r($totalpayed . 'aaaaaaaaaaaaaaaaaaaaaa');
        //	$totaldeptafter = $_POST['supplierdebtafter']; //إجمالي المديونية
        ## values needed for mean and last buy price with discount #############
        ##get $billTotalBeforeDiscount
        $billTotalBeforeDiscount = $totalbill;
        ##get $billDiscountVal
        $billDiscountVal = $gendis;
        if ($discount_type == "1") {
            $billDiscountVal = ($gendis / 100) * $billTotalBeforeDiscount;
            $billDiscountVal = round($billDiscountVal, $noOfDecimalPlaces);
        }
        ##get addition val
        $billAdditionVal = $genaddition;
        if ($addition_type == "1") {
            $billAdditionVal = ($genaddition / 100) * $billTotalBeforeDiscount;
            $billAdditionVal = round($billAdditionVal, $noOfDecimalPlaces);
        }
//        //to affect price
//        //$billDiscountVal -= $billAdditionVal;
        ########################################################################
        if ($aftertotalbill > 0) {
            $remin = $aftertotalbill - $totalpayed;
        } else {
            //return is more
            $remin = $aftertotalbill + $totalpayed;
        }

        ##curr conversion
        $reminInMainCurrency = $remin;
        if ($currencyId > 1) {
            $reminInMainCurrency = $remin / $cFactor;
        }
        $supplierId = $_POST['supplier'];
        $supdata = $supplierDAO->load($supplierId);

        $totaldeptbefore = $supdata->suppliercurrentDebtInCurrency; //$_POST['hidden_debt'];
        $totaldeptbeforeInMainCurr = $supdata->suppliercurrentDebt; //$_POST['hidden_debt'];
        $totaldeptafter = $totaldeptbefore + $remin;
        $totaldeptafterInMainCurr = $totaldeptbeforeInMainCurr + $reminInMainCurrency; //$_POST['supplierdebtafter']; //إجمالي المديونية

        $finalbill;
        if ($aftertotalbill > 0) {
            $finalbill = $aftertotalbill - $totalpayed; // المتبقي
        } else {
            $finalbill = $aftertotalbill + $totalpayed; // المتبقي
        }

        if (empty($pay_num)) {
            $serial = $pay_num_optional;
        } else {
            $serial = $pay_num;
        }


        $buyItr = $_POST['hidden_itr']; //buy bill iteration
        $returnBuyItr = $_POST['hidden_itr_re'];

        $buyBillFlag = 0;
        $returnBuyBillFlag = 0;

        for ($i = 1; $i <= $buyItr; $i++) {
            $productIdxxx = $_POST['product' . $i];
            if (strpos($productIdxxx, "hasSizeColor") !== false) {
                $productIdxxx = 1; //this shows there is product
            }
            $proprice = $_POST['proprice' . $i];
            if ($productIdxxx > 0) {
                $buyBillFlag += 1;
            }
        }

        for ($i = 1; $i <= $returnBuyItr; $i++) {
            $productIdxxx = $_POST['product_re' . $i];
            if (strpos($productIdxxx, "hasSizeColor") !== false) {
                $productIdxxx = 1; //this shows there is product
            }
            $proprice = $_POST['proprice_re' . $i];
            if ($productIdxxx > 0) {
                $returnBuyBillFlag += 1;
            }
        }



        ##curr conversion
        $billCurrInsertId = 0;
        $saveData = $saveExt->loadForUpdateEx($saveid);
        $saveConversionFactor = $saveData->conversionFactor;
        $buybilldiscountC = $gendis;
        $genadditionC = $genaddition;
        $buybilltotalbillC = $totalbill;
        $buybillaftertotalbillC = $aftertotalbill;
        $buybilltotalpayedC = $totalpayed;
        $buybillfinalbillC = $finalbill;
        $buybilldirectpaymentC = 1;
        $payedtaxC = $payedtax;
        if ($currencyId > 1) {
            $gendis = $gendis / $cFactor;
            $genaddition = $genaddition / $cFactor;
            $totalbill = $totalbill / $cFactor;
            $aftertotalbill = $aftertotalbill / $cFactor;
            $totalpayed = $totalpayed / $cFactor;
            $finalbill = $finalbill / $cFactor;
            $buybilldirectpaymentC = 1;
            //$payedtax = $payedtax / $cFactor;
        }
        ###################################################
        if ($ordertype == 0) { //bill
            //return buy bill only
            if ($buyItr == 0 || $buyBillFlag == 0) { //return buy bill only
                $billType = 1;
                //            try {
                //insert into returnbuybill tbl
                $returnBuyBill->billnameid = $billnameId;
                $returnBuyBill->conditions = 0;
                $returnBuyBill->returnbuybillaftertotalbill = $aftertotalbill;
                $returnBuyBill->returnbuybilldate = $buybillDate;
                $returnBuyBill->returnbuybilldirectpayment = 1;
                $returnBuyBill->returnbuybilldiscountrype = $discount_type;
                $returnBuyBill->returnbuybilldiscount = $gendis;
                $returnBuyBill->returnbuybillfinalbill = $finalbill;
                $returnBuyBill->returnbuybillsaveid = $saveid;
                $returnBuyBill->returnbuybillSerial = $serial;
                $returnBuyBill->returnbuybillstoreid = $storeId;
                $returnBuyBill->returnbuybillsupplierid = $supplierId;
                $returnBuyBill->returnbuybillsysdate = $today;
                $returnBuyBill->returnbuybilltotalbill = $totalbill;
                $returnBuyBill->returnbuybilltotaldeptafter = $totaldeptafter;
                $returnBuyBill->returnbuybilltotaldeptbefor = $totaldeptbefore;
                $returnBuyBill->returnbuybilltotalpayed = $totalpayed;
                $returnBuyBill->payedtax = $payedtax;
                $returnBuyBill->taxOfDiscountPer = $taxOfDiscountPer;
                $returnBuyBill->taxOfDiscountVal = $taxOfDiscountVal;
                $returnBuyBill->userid = $_SESSION['userid'];
                $returnBuyBill->costcenterid = $Costcenterid;
                $returnBuyBill->dailyentryid = 0;
                $returnBuyBill->comment = $comment;
                $returnBuyBill->currencyId = $currencyId;
                $returnBuyBill->client = $client;
                $returnBuyBill->returnbuybilladdition = $genaddition;
                $returnBuyBill->returnbuybilladditiontrype = $addition_type;

                $returnBuyBill_Id = $returnBuyBillDAO->insert($returnBuyBill);
                ##curr conversion
                if ($currencyId > 1) {
                    $returnBuyBllCurr->buybillid = $returnBuyBill_Id;
                    $returnBuyBllCurr->conversionFactor = $cFactor;
                    $returnBuyBllCurr->returnbuybilldiscountC = $buybilldiscountC;
                    $returnBuyBllCurr->returnbuybilltotalbillC = $buybilltotalbillC;
                    $returnBuyBllCurr->returnbuybillaftertotalbillC = $buybillaftertotalbillC;
                    $returnBuyBllCurr->returnbuybilltotalpayedC = $buybilltotalpayedC;
                    $returnBuyBllCurr->returnbuybillfinalbillC = $buybillfinalbillC;
                    $returnBuyBllCurr->returnbuybilldirectpaymentC = $buybilldirectpaymentC;
                    $returnBuyBllCurr->returnpayedtaxC = $payedtaxC;
                    $returnBuyBllCurr->saveConversionFactor = $saveConversionFactor;
                    $returnBuyBllCurr->returnbuybilladditionC = $genadditionC;
                    $billCurrInsertId = $returnBuyBllCurrDAO->insert($returnBuyBllCurr);
                }

                $Costcenterdetail->costamount = $aftertotalbill;
                $Costcenterdetail->costcenterid = $Costcenterid;
                $Costcenterdetail->costdate = date('Y-m-d');
                $Costcenterdetail->del = 0;
                $Costcenterdetail->modelid = $returnBuyBill_Id;
                $Costcenterdetail->processname = 'فاتوره مردودات مشتريات';
                $Costcenterdetail->tablename = 'returnBuyBillController.php';
                $Costcenterdetail->type = 4;
                $Costcenterdetail->uesrid = $_SESSION['userid'];

                if ($Costcenterid != -1 && $Costcenterid != '-1') {
                    $CostcenterdetailDAO->insert($Costcenterdetail);
                }



                for ($j = 1; $j <= $returnBuyItr; $j++) {
                    $parcode = $_POST['parcode_re' . $j];
                    $prstorid = $_POST['reprstorid' . $j];
                    if (isset($prstorid) && $prstorid != -1 && (int) $prstorid > 0) {
                        $storeId = $prstorid;
                    } else {
                        $storeId = $_POST['storeId'];
                    }
                    $productId = $_POST['product_re' . $j];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeId, $sizeId, $colorId);
                    }
                    $unitId = $_POST['unitId_re' . $j];
                    $proprice = $_POST['proprice_re' . $j];
                    $pronum = $_POST['pronum_re' . $j];
                    $prototal = $_POST['hidden_prototal_re' . $j];
                    $note = $_POST['note_re' . $j];
                    $prodis = $_POST['prodis_re' . $j];
                    $discounttype = $_POST['discounttype_re' . $j];
                    $rowtaxper = $_POST['rowtaxper_re' . $j];
                    $rowtaxval = $_POST['rowtaxval_re' . $j];
                    $scunitname = $_POST['scunitname_re' . $j];

                    if (!empty($productId) && $productId != '-1') {
                        $catId = getProductCatId($productId);

                        if (!empty($returnBuyBill_Id)) {
                            $returnBuyBillDetail->discountvalue = $prodis;
                            $returnBuyBillDetail->discounttype = $discounttype;
                            $returnBuyBillDetail->note = $note;
                            $returnBuyBillDetail->parcode = $parcode;
                            $returnBuyBillDetail->returnbuybilldetailcatid = $catId;
                            $returnBuyBillDetail->returnbuybilldetailprice = $proprice;
                            $returnBuyBillDetail->returnbuybilldetailproductid = $productId;
                            $returnBuyBillDetail->returnbuybilldetailquantity = $pronum;
                            $returnBuyBillDetail->returnbuybilldetailtotalprice = $prototal;
                            $returnBuyBillDetail->returnbuybillid = $returnBuyBill_Id;
                            $returnBuyBillDetail->productunitid = $unitId;
                            $returnBuyBillDetail->otherdetailquantity = $scunitname;
                            $returnBuyBillDetail->sizeid = $sizeId;
                            $returnBuyBillDetail->colorid = $colorId;
                            $returnBuyBillDetail->rowtaxper = $rowtaxper;
                            $returnBuyBillDetail->rowtaxval = $rowtaxval;
                            $returnBuyBillDetail->storeid = $storeId;
                            ##curr conversion
                            $returnBuyBillDetail->returnbuybilldetailpriceC = $returnBuyBillDetail->returnbuybilldetailprice;
                            $returnBuyBillDetail->returnbuybilldetailtotalpriceC = $returnBuyBillDetail->returnbuybilldetailtotalprice;
                            $returnBuyBillDetail->discountvalueC = $returnBuyBillDetail->discountvalue;
                            if ($currencyId > 1) {
                                $proprice = $proprice / $cFactor;
                                $prototal = $prototal / $cFactor;
                                $prodis = $prodis / $cFactor;
                                $returnBuyBillDetail->returnbuybilldetailprice = $proprice;
                                $returnBuyBillDetail->returnbuybilldetailtotalprice = $prototal;
                                $returnBuyBillDetail->discountvalue = $prodis;
                            }
                            ##################################

                            $detailId = $returnBuyBillDetailDAO->insert($returnBuyBillDetail);
                        }


                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            //****************** Update product quantity in store ************************//
                            //get store productquantity before change
                            $storeDetailData = getStoreDetails($storeId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

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



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

                            $issold = $myProductserialEx->queryallisdSerial($productId, $parcode, " and sizeid=$sizeId and colorid=$colorId ");
                            if (count($issold) > 0) {
                                $productserailId = $issold->productserailid;
                                //updateSerailDon($productserailId, 1, $sellbillId);
                                updateSerailQty($productserailId, $finalquantity);
                            }

                            if (count($allStoredetailData) > 0) {
                                //update productquantity in storedetail

                                $productQuantityAfter = decreaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity, $proprice, $productnumber, "returnbuybilldetailid", $detailId, $productId, "returnbuybilldetail", "add", $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId, $rowtaxval, $payedtax, $cFactor);

                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 1, $returnBuyBill_Id, "اضافة فاتورة مردودات مشتريات", "returnBuyBillController.php", $buybillDate, $sizeId, $colorId);
                            } else {
                                //insert in storedetail tbl
                                insertStoredetailupdate($storeId, $productId, (abs($finalquantity) * -1), $buybillDate, $sizeColorStoreDetailId, $sizeId, $colorId, $proprice, $productnumber, "returnbuybilldetailid", $detailId, "returnbuybilldetail", "add", $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $rowtaxval, $payedtax, $cFactor);

                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, (abs($finalquantity) * -1), 0, (abs($finalquantity) * -1), 1, $returnBuyBill_Id, "اضافة فاتورة مردودات مشتريات", "returnBuyBillController.php", $buybillDate, $sizeId, $colorId);
                            }


                            $allStoredetailData2 = getStoreDetails($storeId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                            $allStoredetailDataother = $allStoredetailData2[0];
                            $storeDetailIdother = $allStoredetailData2[1];
                            $productQuantityBeforeother = $allStoredetailData2[2];



                            if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                //update productquantity in storedetail
                                print_r('in if');
                                $finalquantityother = $productQuantityBeforeother - $scunitname;
                                $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                //insert in storereport
                                insertStorereportupdate2($productId, $storeId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $returnBuyBill_Id, "اضافة فاتورة  مردودات شراء", "returnBuyBillController.php", $buybillDate, 1);
                            } else {
                                //insert in storedetail tbl
                                if ($scunitname > 0) {
                                    insertStoredetailupdate2($storeId, $productId, ($scunitname) * -1, $buybillDate, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $storeId, ($scunitname), 0, ($scunitname) * -1, 0, $returnBuyBill_Id, "اضافة فاتورة  مردودات شراء", "returnBuyBillController.php", $buybillDate, 1);
                                }
                            }
                        }
                    }
                }

                //****************** Update supplier dept ************************//
                //check if supplier deptAfter change from  supplier deptBefor
                //if($totaldeptafter != $totaldeptbefore)
                //{
                //update supplierdebt
                updateSupplierDebt($supplierId, $totaldeptafter, $totaldeptafterInMainCurr);

                insertSupplierDebtChangeupdate($supplierId, $totaldeptbefore, $totaldeptbeforeInMainCurr, abs($finalbill), abs($buybillfinalbillC), 1, "اضافة فاتورة مردوات مشتريات", $returnBuyBill_Id, $totaldeptafter, $totaldeptafterInMainCurr, "returnBuyBillController.php", "اضافة فاتورة مردوات مشتريات", $buybillDate);
                //}
                //****************** Update save value ************************//
                //check if payed or not to change the save value
                if ($totalpayed > 0) {
                    $totalpayed = $totalpayed * (-1);
                    //get saveValue before and saveValue after plus totalPayed
                    $saveData = getSaveValueAndPlus($saveid, abs($totalpayed), $saveConversionFactor);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];
                    ##curr conversion
                    $totalpayedSaveCurr = $saveData[3];
                    $saveConversionFactor = $saveData[4];
                    if ($currencyId > 1 && $billCurrInsertId > 0) {
                        $returnBuyBllCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                    }

                    //update saveFrom value after add transfer
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from savefrom
                    $_SESSION['client_id'] = $supplierId;
                    insertSavedailyupdate($saveValuebefore, $totalpayedSaveCurr, 0, $saveId, "اضافة فاتورة مردوات مشتريات", $returnBuyBill_Id, $saveValueafter, "returnBuyBillController.php", $buybillDate);
                    unset($_SESSION['client_id']);
                }
                //            } catch (Exception $e) {
                //                // print_r($e);
                //                header("location:?do=error");
                //                //echo $e;
                //            }
            } else if ($returnBuyItr == 0 || $returnBuyBillFlag == 0) {
                //buy bill only

                $billType = 2;
                //print("<br>buyBill<br>");
                //            try {
                //print_r(1111);
                //insert into buybill tbl
                $buyBill->billnameid = $billnameId;
                $buyBill->conditions = 0;
                $buyBill->buybillaftertotalbill = $aftertotalbill;
                $buyBill->buybilldate = $buybillDate;
                $buyBill->buybilldirectpayment = 1;
                $buyBill->buybilldiscountrype = $discount_type;
                $buyBill->buybilldiscount = $gendis;
                $buyBill->buybillfinalbill = $finalbill;
                $buyBill->buybillsaveid = $saveid;
                $buyBill->buybillSerial = $serial;
                $buyBill->buybillstoreid = $storeId;
                $buyBill->buybillsupplierid = $supplierId;
                $buyBill->buybillsysdate = $today;
                $buyBill->buybilltotalbill = $totalbill;
                $buyBill->buybilltotaldeptafter = $totaldeptafter;
                $buyBill->buybilltotaldeptbefor = $totaldeptbefore;
                $buyBill->buybilltotalpayed = $totalpayed;
                $buyBill->userid = $_SESSION['userid'];
                $buyBill->payedtax = $payedtax;
                $buyBill->taxOfDiscountPer = $taxOfDiscountPer;
                $buyBill->taxOfDiscountVal = $taxOfDiscountVal;
                $buyBill->costcenterid = $Costcenterid;
                $buyBill->dailyentryid = 0;
                $buyBill->comment = $comment;
                $buyBill->currencyId = $currencyId;
                $buyBill->client = $client;
                $buyBill->buybilladdition = $genaddition;
                $buyBill->buybilladditiontrype = $addition_type;
                $buyBill->totalBuyDiscountVal = (float) $_POST['totalBuyDiscountVal_hidden'];
                $buyBill->webApiId = (int) $_POST['webApiId'];
                $namesArr = uploadfileMultiple('files', '../upload/buyBillFiles');
                $buyBill->files = implode(',', $namesArr);
                //print_r($buyBill);
                $buyBill_Id = $buyBillDAO->insert($buyBill);
                if ($offerId > 0) {
                    $buyBillOfferEX->updateOrderSavedBillId($buyBill_Id, $offerId);
                }
                //print_r('<br>' . $buyBill_Id);
                ##curr conversion
                if ($currencyId > 1) {
                    $buyBillCurr->buybillid = $buyBill_Id;
                    $buyBillCurr->conversionFactor = $cFactor;
                    $buyBillCurr->buybilldiscountC = $buybilldiscountC;
                    $buyBillCurr->buybilltotalbillC = $buybilltotalbillC;
                    $buyBillCurr->buybillaftertotalbillC = $buybillaftertotalbillC;
                    $buyBillCurr->buybilltotalpayedC = $buybilltotalpayedC;
                    $buyBillCurr->buybillfinalbillC = $buybillfinalbillC;
                    $buyBillCurr->buybilldirectpaymentC = $buybilldirectpaymentC;
                    $buyBillCurr->payedtaxC = $payedtaxC;
                    $buyBillCurr->saveConversionFactor = $saveConversionFactor;
                    $buyBillCurr->buybilladditionC = $genadditionC;
                    $billCurrInsertId = $buyBillCurrDAO->insert($buyBillCurr);
                }


                $Costcenterdetail->costamount = $aftertotalbill;
                $Costcenterdetail->costcenterid = $Costcenterid;
                $Costcenterdetail->costdate = date('Y-m-d');
                $Costcenterdetail->del = 0;
                $Costcenterdetail->modelid = $buyBill_Id;
                $Costcenterdetail->processname = 'فاتوره مشتريات';
                $Costcenterdetail->tablename = 'buybillController.php';
                $Costcenterdetail->type = 3;
                $Costcenterdetail->uesrid = $_SESSION['userid'];

                if ($Costcenterid != -1 && $Costcenterid != '-1') {
                    $CostcenterdetailDAO->insert($Costcenterdetail);
                }
                //print($productId . "<br>catId: " . $buyBill_Id . "<br>");


                for ($j = 1; $j <= $buyItr; $j++) {
                    $parcode = $_POST['parcode' . $j];
                    $prstorid = $_POST['prstorid' . $j];
                    if (isset($prstorid) && $prstorid != -1 && (int) $prstorid > 0) {
                        $storeId = $prstorid;
                    } else {
                        $storeId = $_POST['storeId'];
                    }
                    $productId = $_POST['product' . $j];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeId, $sizeId, $colorId);
                    }
                    $unitId = $_POST['unitId' . $j];
                    $proprice = $_POST['proprice' . $j];
                    $pronum = $_POST['pronum' . $j];
                    $prototal = $_POST['hidden_prototal' . $j];
                    $note = $_POST['note' . $j];
                    $prodis = $_POST['prodis' . $j];
                    $discounttype = $_POST['discounttype' . $j];
                    $rowtaxper = $_POST['rowtaxper' . $j];
                    $rowtaxval = $_POST['rowtaxval' . $j];
                    $scunitname = $_POST['scunitname' . $j];
                    $probuyDiscountPer = $_POST['probuyDiscountPer' . $j];


                    if (!empty($productId) && $productId != '-1') {
                        $catId = getProductCatId($productId);




                        if (!empty($buyBill_Id)) {
                            $buyBillDetail->discountvalue = $prodis;
                            $buyBillDetail->discounttype = $discounttype;
                            $buyBillDetail->note = $note;
                            $buyBillDetail->parcode = $parcode;
                            $buyBillDetail->buybilldetailcatid = $catId;
                            $buyBillDetail->buybilldetailprice = $proprice;
                            $buyBillDetail->buybilldetailproductid = $productId;
                            $buyBillDetail->buybilldetailquantity = $pronum;
                            $buyBillDetail->buybilldetailtotalprice = $prototal;
                            $buyBillDetail->buybillid = $buyBill_Id;
                            $buyBillDetail->buybilldetaildate = $today;
                            $buyBillDetail->productunitid = $unitId;
                            $buyBillDetail->otherdetailquantity = $scunitname;
                            $buyBillDetail->sizeid = $sizeId;
                            $buyBillDetail->colorid = $colorId;
                            $buyBillDetail->rowtaxper = $rowtaxper;
                            $buyBillDetail->rowtaxval = $rowtaxval;
                            $buyBillDetail->probuyDiscountPer = $probuyDiscountPer;
                            $buyBillDetail->storeid = $storeId;
                            ##curr conversion
                            $buyBillDetail->buybilldetailpriceC = $buyBillDetail->buybilldetailprice;
                            $buyBillDetail->buybilldetailtotalpriceC = $buyBillDetail->buybilldetailtotalprice;
                            $buyBillDetail->discountvalueC = $buyBillDetail->discountvalue;
                            if ($currencyId > 1) {
                                $proprice = $proprice / $cFactor;
                                $prototal = $prototal / $cFactor;
                                $prodis = $prodis / $cFactor;
                                $buyBillDetail->buybilldetailprice = $proprice;
                                $buyBillDetail->buybilldetailtotalprice = $prototal;
                                $buyBillDetail->discountvalue = $prodis;
                            }

                            $buyBillDetailid = $buyBillDetailDAO->insert($buyBillDetail);
                            $detailId = $buyBillDetailid;
                        }



                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            $productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
                            $productnumber = $productunitData->productnumber;
                            $finalquantity = $pronum * $productnumber;

                            //
                            $prototalWithDiscount = $prototal - ($billDiscountVal * ($prototal / $billTotalBeforeDiscount));
                            $buyPrice = round(($prototalWithDiscount / $finalquantity), $noOfDecimalPlaces); //$buyBillDetail->buybilldetailprice / $productnumber; //$buyBillDetail->buybilldetailtotalprice/$finalquantity;
                            increaseBuyPricesHistoryBookBuyQuantity($buyBill->buybilldate, $buyBill->buybillstoreid, $buyBillDetail->buybilldetailproductid, $buyBillDetail->sizeid, $buyBillDetail->colorid, $buyPrice, $finalquantity);

                            $Entryproductspurchased->del = 0;
                            $Entryproductspurchased->expirationDate = "";
                            $Entryproductspurchased->modelid = $buyBillDetailid;
                            $Entryproductspurchased->price = $proprice;
                            $Entryproductspurchased->priority = 0;

                            $Entryproductspurchased->productquantity = $finalquantity;
                            $Entryproductspurchased->soldquantity = 0;
                            $Entryproductspurchased->tablename = 'buyBillController.php';
                            $Entryproductspurchased->productid = $productId;

                            //   print_r($Entryproductspurchased);
                            $EntryproductspurchasedDAO->insert($Entryproductspurchased);

                            if ($Programsettingdata->updateproductprice == 0) {

                                $finalprice = $prototal / $finalquantity;
                                updateproductpriceFunc($productId, $finalprice);
                            }


                            //****************** Update product quantity in store ************************//
                            //get store productquantity before change
                            $storeDetailData = getStoreDetails($storeId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

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

                            //print_r($allStoredetailData);

                            $buyBillDetailExt->updatequantityBefore($productQuantityBefore, $detailId);
                            if (count($allStoredetailData) > 0) {
                                //update productquantity in storedetail
                                $probuyDiscountPer = (($finalquantity * $proprice) - $prodis) * $probuyDiscountPer / 100;

                                $productQuantityAfter = increaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity, $proprice, $productnumber, "buybilldetailid", $detailId, $productId, "buybilldetail", $operation, $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId, $rowtaxval, $payedtax, $cFactor, $probuyDiscountPer);

                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 0, $buyBill_Id, "اضافة فاتورة مشتريات", "buyBillController.php", $buybillDate, $sizeId, $colorId);
                            } else {

                                //insert in storedetail tbl
                                insertStoredetailupdate($storeId, $productId, $finalquantity, $buybillDate, $sizeColorStoreDetailId, $sizeId, $colorId, $proprice, $productnumber, "buybilldetailid", $detailId, "buybilldetail", $operation, $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $rowtaxval, $payedtax, $cFactor, $probuyDiscountPer);

                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, $finalquantity, 0, $finalquantity, 0, $buyBill_Id, "اضافة فاتورة مشتريات", "buyBillController.php", $buybillDate, $sizeId, $colorId);
                            }


                            $allStoredetailData2 = getStoreDetails($storeId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                            $allStoredetailDataother = $allStoredetailData2[0];
                            $storeDetailIdother = $allStoredetailData2[1];
                            $productQuantityBeforeother = $allStoredetailData2[2];



                            if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                //update productquantity in storedetail
                                print_r('in if');
                                $finalquantityother = $productQuantityBeforeother + $scunitname;
                                $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                //insert in storereport
                                insertStorereportupdate2($productId, $storeId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $buyBill_Id, "اضافة فاتورة  مشتريات", "buyBillController.php", $buybillDate, 1);
                            } else {
                                //insert in storedetail tbl
                                if ($scunitname > 0) {
                                    insertStoredetailupdate2($storeId, $productId, $scunitname, $buybillDate, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $storeId, $scunitname, 0, $scunitname, 0, $buyBill_Id, "اضافة فاتورة  مشتريات", "buyBillController.php", $buybillDate, 1);
                                }
                            }
                        }
                    }
                }

                //****************** Update supplier dept ************************//
                //check if supplier deptAfter change from  supplier deptBefor
                //if($totaldeptafter != $totaldeptbefore)
                //{
                //update supplierdebt
                updateSupplierDebt($supplierId, $totaldeptafter, $totaldeptafterInMainCurr);

                insertSupplierDebtChangeupdate($supplierId, $totaldeptbefore, $totaldeptbeforeInMainCurr, $finalbill, $buybillfinalbillC, 0, "اضافة فاتورة مشتريات", $buyBill_Id, $totaldeptafter, $totaldeptafterInMainCurr, "buyBillController.php", "اضافة فاتورة مشتريات", $buybillDate);
                //}
                //****************** Update save value ************************//
                //check if payed or not to change the save value
                $saveId = $saveid;
                if ($totalpayed > 0) {
                    //get saveValue before and saveValue after plus totalPayed
                    $saveData = getSaveValueAndMins($saveid, $totalpayed, $saveConversionFactor);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];
                    ##curr conversion
                    $totalpayedSaveCurr = $saveData[3];
                    $saveConversionFactor = $saveData[4];
                    if ($currencyId > 1 && $billCurrInsertId > 0) {
                        $buyBillCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                    }

                    //update saveFrom value after add transfer
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from savefrom
                    $_SESSION['client_id'] = $supplierId;
                    insertSavedailyupdate($saveValuebefore, $totalpayedSaveCurr, 1, $saveId, "اضافة فاتورة مشتريات", $buyBill_Id, $saveValueafter, "buyBillController.php", $buybillDate);
                    unset($_SESSION['client_id']);
                }
                //            } catch (Exception $e) {
                //                //  print_r($e);
                //                header("location:?do=error");
                //            }
            } elseif (!empty($buyItr) && $buyItr != 0 && $buyBillFlag != 0 && !empty($returnBuyItr) && $returnBuyItr != 0 && $returnBuyBillFlag != 0) {
                $billType = 3;
                //            try {
                //insert into buybill tbl
                $buyAndReturnBill->billnameid = $billnameId;
                $buyAndReturnBill->buybillaftertotalbill = $aftertotalbill;
                $buyAndReturnBill->buybilldate = $buybillDate;
                $buyAndReturnBill->userid = $_SESSION['userid'];
                $buyAndReturnBill->buybillclientname = "";
                $buyAndReturnBill->buybilldirectpayment = 1;
                $buyAndReturnBill->buybilldiscount = $gendis;
                $buyAndReturnBill->buybilldiscountrype = $discount_type;
                $buyAndReturnBill->buybillfinalbill = $finalbill;
                $buyAndReturnBill->buybillsaveid = $saveid;
                $buyAndReturnBill->buybillSerial = $serial;
                $buyAndReturnBill->buybillstoreid = $storeId;
                $buyAndReturnBill->buybillsupplierid = $supplierId;
                $buyAndReturnBill->buybillsysdate = $today;
                $buyAndReturnBill->buybilltotalbill = $totalbill;
                $buyAndReturnBill->buybilltotaldeptafter = $totaldeptafter;
                $buyAndReturnBill->buybilltotaldeptbefor = $totaldeptbefore;
                $buyAndReturnBill->buybilltotalpayed = $totalpayed;
                $buyAndReturnBill->conditions = 0;
                $buyAndReturnBill->payedtax = $payedtax;
                $buyAndReturnBill->taxOfDiscountPer = $taxOfDiscountPer;
                $buyAndReturnBill->taxOfDiscountVal = $taxOfDiscountVal;
                $buyAndReturnBill->costcenterid = $Costcenterid;
                $buyAndReturnBill->dailyentryid = 0;
                $buyAndReturnBill->comment = $comment;
                $buyAndReturnBill->currencyId = $currencyId;
                $buyAndReturnBill->client = $client;
                $buyAndReturnBill->buybilladdition = $genaddition;
                $buyAndReturnBill->buybilladditiontrype = $addition_type;



                $buyAndReturnBill_Id = $buyAndReturnBillDAO->insert($buyAndReturnBill);
                ##curr conversion
                if ($currencyId > 1) {
                    $buyAndRuternBillCurr->buybillid = $buyAndReturnBill_Id;
                    $buyAndRuternBillCurr->conversionFactor = $cFactor;
                    $buyAndRuternBillCurr->buybilldiscountC = $buybilldiscountC;
                    $buyAndRuternBillCurr->buybilltotalbillC = $buybilltotalbillC;
                    $buyAndRuternBillCurr->buybillaftertotalbillC = $buybillaftertotalbillC;
                    $buyAndRuternBillCurr->buybilltotalpayedC = $buybilltotalpayedC;
                    $buyAndRuternBillCurr->buybillfinalbillC = $buybillfinalbillC;
                    $buyAndRuternBillCurr->buybilldirectpaymentC = $buybilldirectpaymentC;
                    $buyAndRuternBillCurr->payedtaxC = $payedtaxC;
                    $buyAndRuternBillCurr->saveConversionFactor = $saveConversionFactor;
                    $buyAndRuternBillCurr->buybilladditionC = $genadditionC;
                    $billCurrInsertId = $buyAndRuternBillCurrDAO->insert($buyAndRuternBillCurr);
                }

                $Costcenterdetail->costamount = $aftertotalbill;
                $Costcenterdetail->costcenterid = $Costcenterid;
                $Costcenterdetail->costdate = date('Y-m-d');
                $Costcenterdetail->del = 0;
                $Costcenterdetail->modelid = $buyAndReturnBill_Id;
                $Costcenterdetail->processname = 'فاتوره مشتريات ومردودات';
                $Costcenterdetail->tablename = 'buyAndReturnBillController.php';
                $Costcenterdetail->type = 5;
                $Costcenterdetail->uesrid = $_SESSION['userid'];

                if ($Costcenterid != -1 && $Costcenterid != '-1') {
                    $CostcenterdetailDAO->insert($Costcenterdetail);
                }




                for ($j = 1; $j <= $buyItr; $j++) {
                    $parcode = $_POST['parcode' . $j];
                    $prstorid = $_POST['prstorid' . $j];
                    if (isset($prstorid) && $prstorid != -1 && (int) $prstorid > 0) {
                        $storeId = $prstorid;
                    } else {
                        $storeId = $_POST['storeId'];
                    }
                    $productId = $_POST['product' . $j];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeId, $sizeId, $colorId);
                    }
                    $unitId = $_POST['unitId' . $j];
                    $proprice = $_POST['proprice' . $j];
                    $pronum = $_POST['pronum' . $j];
                    $prototal = $_POST['hidden_prototal' . $j];
                    $note = $_POST['note' . $j];
                    $prodis = $_POST['prodis' . $j];
                    $discounttype = $_POST['discounttype' . $j];
                    $rowtaxper = $_POST['rowtaxper' . $j];
                    $rowtaxval = $_POST['rowtaxval' . $j];
                    $scunitname = $_POST['scunitname' . $j];


                    if (!empty($productId) && $productId != '-1') {
                        $catId = getProductCatId($productId);


                        if (!empty($buyAndReturnBill_Id)) {
                            $buyAndReturnBillDetail->billtype = 0;
                            $buyAndReturnBillDetail->buybilldetailcatid = $catId;
                            $buyAndReturnBillDetail->buybilldetaildate = $today;
                            $buyAndReturnBillDetail->buybillid = $buyAndReturnBill_Id;
                            $buyAndReturnBillDetail->buybilldetailprice = $proprice;
                            $buyAndReturnBillDetail->buybilldetailquantity = $pronum;
                            $buyAndReturnBillDetail->buybilldetailproductid = $productId;
                            $buyAndReturnBillDetail->buybilldetailtotalprice = $prototal;
                            $buyAndReturnBillDetail->discountvalue = $prodis;
                            $buyAndReturnBillDetail->discounttype = $discounttype;
                            $buyAndReturnBillDetail->note = $note;
                            $buyAndReturnBillDetail->parcode = $parcode;
                            $buyAndReturnBillDetail->productunitid = $unitId;
                            $buyAndReturnBillDetail->otherdetailquantity = $scunitname;
                            $buyAndReturnBillDetail->sizeid = $sizeId;
                            $buyAndReturnBillDetail->colorid = $colorId;
                            $buyAndReturnBillDetail->rowtaxper = $rowtaxper;
                            $buyAndReturnBillDetail->rowtaxval = $rowtaxval;
                            $buyAndReturnBillDetail->storeid = $storeId;
                            ##curr conversion
                            $buyAndReturnBillDetail->buybilldetailpriceC = $buyAndReturnBillDetail->buybilldetailprice;
                            $buyAndReturnBillDetail->buybilldetailtotalpriceC = $buyAndReturnBillDetail->buybilldetailtotalprice;
                            $buyAndReturnBillDetail->discountvalueC = $buyAndReturnBillDetail->discountvalue;
                            if ($currencyId > 1) {
                                $proprice = $proprice / $cFactor;
                                $prototal = $prototal / $cFactor;
                                $prodis = $prodis / $cFactor;
                                $buyAndReturnBillDetail->buybilldetailprice = $proprice;
                                $buyAndReturnBillDetail->buybilldetailtotalprice = $prototal;
                                $buyAndReturnBillDetail->discountvalue = $prodis;
                            }
                            #############################################

                            $detailId = $buyAndReturnBillDetailDAO->insert($buyAndReturnBillDetail);
                        }


                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            $productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
                            $productnumber = $productunitData->productnumber;
                            $finalquantity = $pronum * $productnumber;


                            //
                            $prototalWithDiscount = $prototal - ($billDiscountVal * ($prototal / $billTotalBeforeDiscount));
                            $buyPrice = round(($prototalWithDiscount / $finalquantity), $noOfDecimalPlaces); //$buyAndReturnBillDetail->buybilldetailprice / $productnumber; //$buyBillDetail->buybilldetailtotalprice/$finalquantity;
                            increaseBuyPricesHistoryBookBuyQuantity($buyAndReturnBill->buybilldate, $buyAndReturnBill->buybillstoreid, $buyAndReturnBillDetail->buybilldetailproductid, $buyAndReturnBillDetail->sizeid, $buyAndReturnBillDetail->colorid, $buyPrice, $finalquantity);

                            if ($Programsettingdata->updateproductprice == 0) {

                                $finalprice = $prototal / $finalquantity;
                                updateproductpriceFunc($productId, $finalprice);
                            }
                            //****************** Update product quantity in store ************************//
                            //get store productquantity before change
                            $storeDetailData = getStoreDetails($storeId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                            $allStoredetailData = $storeDetailData[0];
                            $storeDetailId = $storeDetailData[1];
                            $productQuantityBefore = $storeDetailData[2];
                            $buyAndReturnBillDetailExt->updatequantityBefore($productQuantityBefore, $detailId);

                            if (count($allStoredetailData) > 0) {
                                //update productquantity in storedetail
                                $productQuantityAfter = increaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity, $proprice, $productnumber, "buybilldetailid", $detailId, $productId, "buyandruternbilldetail", $operation, $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId, $rowtaxval, $payedtax, $cFactor);

                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 0, $buyAndReturnBill_Id, "اضافة فاتورة مشتريات ومردودات", "buyAndReturnBillController.php", $buybillDate, $sizeId, $colorId);
                            } else {
                                //insert in storedetail tbl
                                insertStoredetailupdate($storeId, $productId, $finalquantity, $buybillDate, $sizeColorStoreDetailId, $sizeId, $colorId, $proprice, $productnumber, "buybilldetailid", $detailId, "buyandruternbilldetail", $operation, $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $rowtaxval, $payedtax, $cFactor);

                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, $finalquantity, 0, $finalquantity, 0, $buyAndReturnBill_Id, "اضافة فاتورة مشتريات ومردودات", "buyAndReturnBillController.php", $buybillDate, $sizeId, $colorId);
                            }



                            $allStoredetailData2 = getStoreDetails($storeId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                            $allStoredetailDataother = $allStoredetailData2[0];
                            $storeDetailIdother = $allStoredetailData2[1];
                            $productQuantityBeforeother = $allStoredetailData2[2];



                            if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                //update productquantity in storedetail
                                print_r('in if');
                                $finalquantityother = $productQuantityBeforeother + $scunitname;
                                $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                //insert in storereport
                                insertStorereportupdate2($productId, $storeId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $buyAndReturnBill_Id, "اضافة فاتورة  مشتريات ومردودات", "buyAndReturnBillController.php", $buybillDate, 1);
                            } else {
                                //insert in storedetail tbl
                                if ($scunitname > 0) {
                                    insertStoredetailupdate2($storeId, $productId, $scunitname, $buybillDate, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $storeId, $scunitname, 0, $scunitname, 0, $buyAndReturnBill_Id, "اضافة فاتورة  مشتريات ومردودات", "buyAndReturnBillController.php", $buybillDate, 1);
                                }
                            }
                        }
                    }
                }



                for ($y = 1; $y <= $returnBuyItr; $y++) {
                    $parcode = $_POST['parcode_re' . $y];
                    $prstorid = $_POST['reprstorid' . $j];
                    if (isset($prstorid) && $prstorid != -1 && (int) $prstorid > 0) {
                        $storeId = $prstorid;
                    } else {
                        $storeId = $_POST['storeId'];
                    }
                    $productId = $_POST['product_re' . $y];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeId, $sizeId, $colorId);
                    }
                    $unitId = $_POST['unitId_re' . $y];
                    $proprice = $_POST['proprice_re' . $y];
                    $pronum = $_POST['pronum_re' . $y];
                    $prototal = $_POST['hidden_prototal_re' . $y];
                    $note = $_POST['note_re' . $y];
                    $prodis = $_POST['prodis_re' . $y];
                    $discounttype = $_POST['discounttype_re' . $y];
                    $rowtaxper = $_POST['rowtaxper_re' . $y];
                    $rowtaxval = $_POST['rowtaxval_re' . $y];
                    $scunitname = $_POST['scunitname_re' . $y];


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

                        print_r('<br>555==' . $scunitname . '<br>');
                        $catId = getProductCatId($productId);

                        if (!empty($buyAndReturnBill_Id)) {
                            print_r('<br>555<br>');
                            $buyAndReturnBillDetail->billtype = 1;
                            $buyAndReturnBillDetail->buybilldetailcatid = $catId;
                            $buyAndReturnBillDetail->buybilldetaildate = $today;
                            $buyAndReturnBillDetail->buybillid = $buyAndReturnBill_Id;
                            $buyAndReturnBillDetail->buybilldetailprice = $proprice;
                            $buyAndReturnBillDetail->buybilldetailquantity = $pronum;
                            $buyAndReturnBillDetail->buybilldetailproductid = $productId;
                            $buyAndReturnBillDetail->buybilldetailtotalprice = $prototal;
                            $buyAndReturnBillDetail->discountvalue = $prodis;
                            $buyAndReturnBillDetail->discounttype = $discounttype;
                            $buyAndReturnBillDetail->productunitid = $unitId;
                            $buyAndReturnBillDetail->note = $note;
                            $buyAndReturnBillDetail->parcode = $parcode;
                            $buyAndReturnBillDetail->otherdetailquantity = $scunitname;
                            $buyAndReturnBillDetail->sizeid = $sizeId;
                            $buyAndReturnBillDetail->colorid = $colorId;
                            $buyAndReturnBillDetail->rowtaxper = $rowtaxper;
                            $buyAndReturnBillDetail->rowtaxval = $rowtaxval;
                            $buyAndReturnBillDetail->storeid = $storeId;
                            ##curr conversion
                            $buyAndReturnBillDetail->buybilldetailpriceC = $buyAndReturnBillDetail->buybilldetailprice;
                            $buyAndReturnBillDetail->buybilldetailtotalpriceC = $buyAndReturnBillDetail->buybilldetailtotalprice;
                            $buyAndReturnBillDetail->discountvalueC = $buyAndReturnBillDetail->discountvalue;
                            if ($currencyId > 1) {
                                $proprice = $proprice / $cFactor;
                                $prototal = $prototal / $cFactor;
                                $prodis = $prodis / $cFactor;
                                $buyAndReturnBillDetail->buybilldetailprice = $proprice;
                                $buyAndReturnBillDetail->buybilldetailtotalprice = $prototal;
                                $buyAndReturnBillDetail->discountvalue = $prodis;
                            }
                            ########################################

                            $buyBillDetailid = $buyAndReturnBillDetailDAO->insert($buyAndReturnBillDetail);
                            $detailId = $buyBillDetailid;
                        }

                        $isService = isService($productId);
                        if ($isService == 0) { //if product
                            //****************** Update product quantity in store ************************//
                            //get store productquantity before change
                            $storeDetailData = getStoreDetails($storeId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

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


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


                            $Entryproductspurchased->del = 0;
                            $Entryproductspurchased->expirationDate = "";
                            $Entryproductspurchased->modelid = $buyBillDetailid;
                            $Entryproductspurchased->price = $proprice;
                            $Entryproductspurchased->productquantity = $finalquantity;
                            $Entryproductspurchased->soldquantity = 0;
                            $Entryproductspurchased->priority = 0;
                            $Entryproductspurchased->tablename = 'buyAndReturnBillController.php';
                            $Entryproductspurchased->productid = $productId;


                            $EntryproductspurchasedDAO->insert($Entryproductspurchased);


                            if (count($allStoredetailData) > 0) {
                                //update productquantity in storedetail
                                print_r('<pre>');
                                print_r('4444444444444444444444444');
                                print_r('<pre>');
                                $productQuantityAfter = decreaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity, $proprice, $productnumber, "buybilldetailid", $detailId, $productId, "buyandruternbilldetail", "add", $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId, $rowtaxval, $payedtax, $cFactor);

                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 1, $buyAndReturnBill_Id, "اضافة فاتورة مردودات مشتريات", "buyAndReturnBillController.php", $buybillDate, $sizeId, $colorId);
                            } else {
                                //insert in storedetail tbl
                                insertStoredetailupdate($storeId, $productId, (abs($finalquantity) * -1), $buybillDate, $sizeColorStoreDetailId, $sizeId, $colorId, $proprice, $productnumber, "buybilldetailid", $detailId, "buyandruternbilldetail", "add", $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $rowtaxval, $payedtax, $cFactor);

                                //insert in storereport
                                insertStorereportupdate($productId, $storeId, (abs($finalquantity) * -1), 0, (abs($finalquantity) * -1), 1, $buyAndReturnBill_Id, "اضافة فاتورة مردودات مشتريات", "buyAndReturnBillController.php", $buybillDate, $sizeId, $colorId);
                            }


                            $allStoredetailData2 = getStoreDetails($storeId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                            $allStoredetailDataother = $allStoredetailData2[0];
                            $storeDetailIdother = $allStoredetailData2[1];
                            $productQuantityBeforeother = $allStoredetailData2[2];



                            if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                //update productquantity in storedetail
                                print_r('in if');
                                $finalquantityother = $productQuantityBeforeother - $scunitname;
                                $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                //insert in storereport
                                insertStorereportupdate2($productId, $storeId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $buyAndReturnBill_Id, "اضافة فاتورة  مشتريات ومردودات", "buyAndReturnBillController.php", $buybillDate, 1);
                            } else {
                                //insert in storedetail tbl
                                if ($scunitname > 0) {
                                    insertStoredetailupdate2($storeId, $productId, ($scunitname) * -1, $buybillDate, 1);

                                    //insert in storereport
                                    insertStorereportupdate2($productId, $storeId, $scunitname, 0, ($scunitname) * -1, 0, $buyAndReturnBill_Id, "اضافة فاتورة  مشتريات ومردودات", "buyAndReturnBillController.php", $buybillDate, 1);
                                }
                            }
                        }
                    }
                }

                //****************** Update supplier dept ************************//
                //check if supplier deptAfter change from  supplier deptBefore
                //if($totaldeptafter != $totaldeptbefore)
                //{
                //update supplierdebt
                updateSupplierDebt($supplierId, $totaldeptafter, $totaldeptafterInMainCurr);

                if ($buyAndReturnBill->buybilltotalbill > 0) {
                    insertSupplierDebtChange($supplierId, $totaldeptbefore, $totaldeptbeforeInMainCurr, $finalbill, $buybillfinalbillC, 0, "اضافة فاتورة مشتريات ومردودات مشتريات", $buyAndReturnBill_Id, $totaldeptafter, $totaldeptafterInMainCurr, "buyAndReturnBillController.php", "اضافة فاتورة مشتريات ومردودات مشتريات", $buybillDate);
                } else {
                    insertSupplierDebtChange($supplierId, $totaldeptbefore, $totaldeptbeforeInMainCurr, abs($finalbill), abs($buybillfinalbillC), 1, "اضافة فاتورة مشتريات ومردودات مشتريات", $buyAndReturnBill_Id, $totaldeptafter, $totaldeptafterInMainCurr, "buyAndReturnBillController.php", "اضافة فاتورة مشتريات ومردودات مشتريات", $buybillDate);
                }

                //}
                //****************** Update save value ************************//
                //check if payed or not to change the save value
                if ($totalpayed > 0) {
                    if ($aftertotalbill > 0) {
                        //get saveValue before and saveValue after minus totalPayed
                        $saveData = getSaveValueAndMins($saveid, $totalpayed, $saveConversionFactor);
                        $saveId = $saveData[0];
                        $saveValuebefore = $saveData[1];
                        $saveValueafter = $saveData[2];
                        ##curr conversion
                        $totalpayedSaveCurr = $saveData[3];
                        $saveConversionFactor = $saveData[4];
                        if ($currencyId > 1 && $billCurrInsertId > 0) {
                            $buyAndRuternBillCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                        }

                        //update saveFrom value after add transfer
                        updateSave($saveId, $saveValueafter);

                        //insert into savedaily tbl from savefrom
                        $_SESSION['client_id'] = $supplierId;
                        insertSavedailyupdate($saveValuebefore, $totalpayedSaveCurr, 1, $saveId, "اضافة فاتورة مشتريات ومردودات مشتريات", $buyAndReturnBill_Id, $saveValueafter, "buyAndReturnBillController.php", $buybillDate);
                        unset($_SESSION['client_id']);
                    } else {
                        //get saveValue before and saveValue after plus totalPayed
                        $saveData = getSaveValueAndPlus($saveid, $totalpayed, $saveConversionFactor);
                        $saveId = $saveData[0];
                        $saveValuebefore = $saveData[1];
                        $saveValueafter = $saveData[2];
                        ##curr conversion
                        $totalpayedSaveCurr = $saveData[3];
                        $saveConversionFactor = $saveData[4];
                        if ($currencyId > 1 && $billCurrInsertId > 0) {
                            $buyAndRuternBillCurrEX->updateSaveConversionFactor($saveConversionFactor, $billCurrInsertId);
                        }

                        //update saveFrom value after add transfer
                        updateSave($saveId, $saveValueafter);

                        //insert into savedaily tbl from savefrom
                        $_SESSION['client_id'] = $supplierId;
                        insertSavedailyupdate($saveValuebefore, $totalpayedSaveCurr, 0, $saveId, "اضافة فاتورة مشتريات ومردودات مشتريات", $buyAndReturnBill_Id, $saveValueafter, "buyAndReturnBillController.php", $buybillDate);
                        unset($_SESSION['client_id']);
                    }
                }
                //            } catch (Exception $e) {
                //                //print_r($e);
                //
                //                header("location:?do=error");
                //                //echo $e;
                //            }
            }
            doBillDailyEntry($billType, $buyBill_Id, $returnBuyBill_Id, $buyAndReturnBill_Id, $billTotalBeforeDiscount, $storeId, $taxVal, $totalpayed, $saveId, $remin, $supdata, $billDiscountVal, $taxOfDiscountVal, $billAdditionVal);
        } elseif ($ordertype == 1) { //its an offer not bill
            //buy bill only
            $billType = 2;

            //insert into buybill tbl
            $buyBill->billnameid = $billnameId;
            $buyBill->conditions = 0;
            $buyBill->buybillaftertotalbill = $aftertotalbill;
            $buyBill->buybilldate = $buybillDate;
            $buyBill->buybilldirectpayment = 1;
            $buyBill->buybilldiscountrype = $discount_type;
            $buyBill->buybilldiscount = $gendis;
            $buyBill->buybillfinalbill = $finalbill;
            $buyBill->buybillsaveid = $saveid;
            $buyBill->buybillSerial = $serial;
            $buyBill->buybillstoreid = $storeId;
            $buyBill->buybillsupplierid = $supplierId;
            $buyBill->buybillsysdate = $today;
            $buyBill->buybilltotalbill = $totalbill;
            $buyBill->buybilltotaldeptafter = $totaldeptafter;
            $buyBill->buybilltotaldeptbefor = $totaldeptbefore;
            $buyBill->buybilltotalpayed = $totalpayed;
            $buyBill->userid = $_SESSION['userid'];
            $buyBill->payedtax = $payedtax;
            $buyBill->taxOfDiscountPer = $taxOfDiscountPer;
            $buyBill->taxOfDiscountVal = $taxOfDiscountVal;
            $buyBill->costcenterid = $Costcenterid;
            $buyBill->dailyentryid = 0;
            $buyBill->comment = $comment;
            $buyBill->currencyId = $currencyId;
            $buyBill->delbyuserid = 0;
            $buyBill->webApiId = (int) $_POST['webApiId'];
            $buyBill->buybilladdition = $genaddition;
            $buyBill->buybilladditiontrype = $addition_type;


            $buyBill_Id = $buyBillOfferDAO->insert($buyBill);

            for ($j = 1; $j <= $buyItr; $j++) {
                $parcode = $_POST['parcode' . $j];
                $productId = $_POST['product' . $j];
                $sizeId = 0;
                $colorId = 0;
                $sizeColorStoreDetailId = 0;
                if (strpos($productId, "hasSizeColor") !== false) {
                    $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                    $productId = $productIdComplex[0];
                    $sizeId = $productIdComplex[1];
                    $colorId = $productIdComplex[2];
                }
                $unitId = $_POST['unitId' . $j];
                $proprice = $_POST['proprice' . $j];
                $pronum = $_POST['pronum' . $j];
                $prototal = $_POST['hidden_prototal' . $j];
                $note = $_POST['note' . $j];
                $prodis = $_POST['prodis' . $j];
                $discounttype = $_POST['discounttype' . $j];
                $scunitname = $_POST['scunitname' . $j];


                if (!empty($productId) && $productId != '-1') {
                    $catId = getProductCatId($productId);


                    if (!empty($buyBill_Id)) {
                        $buyBillDetail->discountvalue = $prodis;
                        $buyBillDetail->discounttype = $discounttype;
                        $buyBillDetail->note = $note;
                        $buyBillDetail->parcode = $parcode;
                        $buyBillDetail->buybilldetailcatid = $catId;
                        $buyBillDetail->buybilldetailprice = $proprice;
                        $buyBillDetail->buybilldetailproductid = $productId;
                        $buyBillDetail->buybilldetailquantity = $pronum;
                        $buyBillDetail->buybilldetailtotalprice = $prototal;
                        $buyBillDetail->buybillid = $buyBill_Id;
                        $buyBillDetail->buybilldetaildate = $today;
                        $buyBillDetail->productunitid = $unitId;
                        $buyBillDetail->otherdetailquantity = $scunitname;
                        $buyBillDetail->sizeid = $sizeId;
                        $buyBillDetail->colorid = $colorId;
                        ##curr conversion
                        $buyBillDetail->buybilldetailpriceC = $buyBillDetail->buybilldetailprice;
                        $buyBillDetail->buybilldetailtotalpriceC = $buyBillDetail->buybilldetailtotalprice;
                        $buyBillDetail->discountvalueC = $buyBillDetail->discountvalue;
                        if ($currencyId > 1) {
                            $proprice = $proprice / $cFactor;
                            $prototal = $prototal / $cFactor;
                            $prodis = $prodis / $cFactor;
                            $buyBillDetail->buybilldetailprice = $proprice;
                            $buyBillDetail->buybilldetailtotalprice = $prototal;
                            $buyBillDetail->discountvalue = $prodis;
                        }

                        $buyBillDetailid = $buyBillDetailOfferDAO->insert($buyBillDetail);
                        $detailId = $buyBillDetailid;
                    }
                }
            }
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
    return array($billType, $returnBuyBill_Id, $buyBill_Id, $buyAndReturnBill_Id, $ordertype, $billnameId);
}

function getProductCatId($productId) {
    global $productExt;
    $catId = $productExt->getProductCatId($productId);
    return $catId;
}

function showBillDetails($buyBill_Id, $ordertype = 0) {
    global $buyBillExt;
    global $buyBillDetailExt;
    global $buyBillCurrEX;
    global $buyBillOfferEX;
    global $buyBillDetailOfferEX;


    if ($ordertype == 0) { //bill
        $buyBillData = $buyBillExt->loadExt($buyBill_Id);
        $buyBillDetails = $buyBillDetailExt->queryByBuybillidExt($buyBill_Id);
        $billCurrData = $buyBillCurrEX->queryOneByBuybillid($buyBill_Id);

        $buyBillData->filesArr = explode(',', $buyBillData->files);
    } elseif ($ordertype == 1) { //offer
        $buyBillData = $buyBillOfferEX->loadExt($buyBill_Id);
        $buyBillDetails = $buyBillDetailOfferEX->queryByBuybillidExt($buyBill_Id);
    }

    ##use currency values
    if (isset($billCurrData) && $_GET['do'] == "editprint") {
        $buyBillData->buybilldiscount = $billCurrData->buybilldiscountC;
        $buyBillData->buybilltotalbill = $billCurrData->buybilltotalbillC;
        $buyBillData->buybillaftertotalbill = $billCurrData->buybillaftertotalbillC;
        $buyBillData->buybilltotalpayed = $billCurrData->buybilltotalpayedC;
        $buyBillData->buybillfinalbill = $billCurrData->buybillfinalbillC;
        $buyBillData->buybilldirectpayment = $billCurrData->buybilldirectpaymentC;
        $buyBillData->payedtax = $billCurrData->payedtaxC;
        ##
        $buyBillData->buybilltotaldeptbefor = $buyBillData->buybilltotaldeptbefor * $billCurrData->conversionFactor;
        $buyBillData->buybilltotaldeptafter = $buyBillData->buybilltotaldeptafter * $billCurrData->conversionFactor;
        foreach ($buyBillDetails as $value) {
            $value->buybilldetailprice = $value->buybilldetailpriceC;
            $value->buybilldetailtotalprice = $value->buybilldetailtotalpriceC;
            $value->discountvalue = $value->discountvalueC;
        }
    }

    return array($buyBillData, $buyBillDetails, $billCurrData);
}

function showBuyBills() {
    global $buyBillExt;
    $buyBills = $buyBillExt->queryAllSerialsNotDeleted();
    return $buyBills;
}

function showAll() {
    global $buyBillExt;
    global $smarty;
    $totalBills = 0;
    $buyBillData = $buyBillExt->queryByConditionExt(0);
    if (count($buyBillData) > 0) {
        foreach ($buyBillData as $bill) {
            if ($bill->conditions == 0) {
                $totalBills += $bill->buybillaftertotalbill;
            }
        }
    }
    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('totalBills', $totalBills);
}

function showByDate($from, $to, $delString) {
    global $buyBillExt;
    global $smarty;
    global $buyBillDetailExt;
    global $ProductserialEX;


    $totalBills = 0;
    $buyBillData = $buyBillExt->queryByDateExt($from, $to, $delString);
    if (count($buyBillData) > 0) {
        foreach ($buyBillData as $bill) {
            $parcode = '';
            $buyBilldetailData = $ProductserialEX->getbuybilldetail($bill->buybillid);
            foreach ($buyBilldetailData as $details) {
                $parcode .= $details->serialnumber . ' / ';
            }
            $bill->parcodepro = $parcode;

            if ($bill->conditions == 0) {
                $totalBills += $bill->buybillaftertotalbill;
            }
        }
    }
    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('totalBills', $totalBills);
}

function showBySupplier($supplierId, $delString) {
    global $buyBillExt;
    global $smarty;


    $totalBills = 0;
    $buyBillData = $buyBillExt->queryBySupplierId($supplierId, $delString);
    if (count($buyBillData) > 0) {
        foreach ($buyBillData as $bill) {
            if ($bill->conditions == 0) {
                $totalBills += $bill->buybillaftertotalbill;
            }
        }
    }
    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('totalBills', $totalBills);
}

function showByStore($store, $delString) {
    global $buyBillExt;
    global $smarty;


    $totalBills = 0;
    $buyBillData = $buyBillExt->queryByStoreId($store, $delString);
    if (count($buyBillData) > 0) {
        foreach ($buyBillData as $bill) {
            if ($bill->conditions == 0) {
                $totalBills += $bill->buybillaftertotalbill;
            }
        }
    }
    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('totalBills', $totalBills);
}

function showByBillSerial($serial, $delString) {
    global $buyBillExt;
    global $smarty;
    $totalBills = 0;
    $buyBillData = $buyBillExt->queryBySerial($serial, $delString);
    if (count($buyBillData) > 0) {
        foreach ($buyBillData as $bill) {
            if ($bill->conditions == 0) {
                $totalBills += $bill->buybillaftertotalbill;
            }
        }
    }
    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('totalBills', $totalBills);
}

function showBybuybillid($buybillid, $delString) {
    global $buyBillExt;
    global $smarty;
    $totalBills = 0;
    $buyBillData = $buyBillExt->loadExt2($buybillid, $delString);
    if (count($buyBillData) > 0) {
        foreach ($buyBillData as $bill) {
            if ($bill->conditions == 0) {
                $totalBills += $bill->buybillaftertotalbill;
            }
        }
    }
    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('totalBills', $totalBills);
}

function showByDateOffer($from, $to, $delString) {
    global $buyBillOfferEX;
    global $smarty;
    global $ProductserialEX;


    $totalBills = 0;
    $buyBillData = $buyBillOfferEX->queryByDateExt($from, $to, $delString);
    if (count($buyBillData) > 0) {
        foreach ($buyBillData as $bill) {
            if ($bill->conditions == 0) {
                $totalBills += $bill->buybillaftertotalbill;
            }
        }
    }
    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('totalBills', $totalBills);
}

function showBySupplierOffer($supplierId, $delString) {
    global $buyBillOfferEX;
    global $smarty;


    $totalBills = 0;
    $buyBillData = $buyBillOfferEX->queryBySupplierId($supplierId, $delString);
    if (count($buyBillData) > 0) {
        foreach ($buyBillData as $bill) {
            if ($bill->conditions == 0) {
                $totalBills += $bill->buybillaftertotalbill;
            }
        }
    }
    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('totalBills', $totalBills);
}

function showByBillSerialOffer($serial, $delString) {
    global $buyBillOfferEX;
    global $smarty;
    $totalBills = 0;
    $buyBillData = $buyBillOfferEX->queryBySerial($serial, $delString);
    if (count($buyBillData) > 0) {
        foreach ($buyBillData as $bill) {
            if ($bill->conditions == 0) {
                $totalBills += $bill->buybillaftertotalbill;
            }
        }
    }
    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('totalBills', $totalBills);
}

function showBybuybillidOffer($buybillid, $delString) {
    global $buyBillOfferEX;
    global $smarty;
    $totalBills = 0;
    $buyBillData = $buyBillOfferEX->loadExt2($buybillid, $delString);
    if (count($buyBillData) > 0) {
        foreach ($buyBillData as $bill) {
            if ($bill->conditions == 0) {
                $totalBills += $bill->buybillaftertotalbill;
            }
        }
    }
    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('totalBills', $totalBills);
}

function delete() {
    global $buyBill;
    global $buyBillDAO;
    global $buyBillExt;
    global $buyBillDetail;
    global $buyBillDetailDAO;
    global $buyBillDetailExt;
    global $supplierDAO;
    //
    global $buyBillCurr;
    global $buyBillCurrDAO;
    global $buyBillCurrEX;

    global $CostcenterdetailDAO;
    global $Costcenterdetail;
    global $CostcenterdetailEX;
    global $sizeColorStoreDetailEX;
    //
    global $buyBillOfferDAO;
    global $buyBillDetailOfferDAO;

    global $ProductserialEX;

    global $today;
    global $smarty;

    global $noOfDecimalPlaces;

    //Transaction
    $mytransactions = new Transaction();
    $ordertype = (int) $_GET['ordertype'];
    try {
        //print_r('in delete');
        $buyBill_Id_one = $_GET['id'];
        if (isset($buyBill_Id_one)) { //if user choosed one buy bill
            $buyBill_Id = $buyBill_Id_one;
            if (isset($buyBill_Id)) {
                if ($ordertype == 0) { //bill
                    $buyBillData = $buyBillDAO->load($buyBill_Id);
                    if (count($buyBillData) > 0 && $buyBillData->conditions == 0) {
                        $deleteOrNot = $buyBillData->conditions;
                        if (isset($deleteOrNot) && $deleteOrNot == 0) {

                            $CostcenterdetailEX->updatedellbytypeandmodelid(3, $buyBill_Id, 1);
                            $totaldeptafter = $buyBillData->buybilltotaldeptafter;
                            $totaldeptbefore = $buyBillData->buybilltotaldeptbefor;
                            $totalpayed = $buyBillData->buybilltotalpayed;
                            $finalbill = $buybillfinalbillC = $buyBillData->buybillfinalbill;
                            
                            $cFactor = 1;
                            if($buyBillData->currencyId > 1)
                            {
                                $billCurrData = $buyBillCurrEX->queryOneByBuybillid($buyBill_Id);
                                $buybillfinalbillC = $billCurrData->buybillfinalbillC;
                                $cFactor = $billCurrData->conversionFactor;
                            }
                            
                            $storeId = $buyBillData->buybillstoreid;
                            $supplierId = $buyBillData->buybillsupplierid;
                            $saveId = $buyBillData->buybillsaveid;
                            $currencyId = $buyBillData->currencyId;
                            $dailyentryid = $buyBillData->dailyentryid;
                            $payedtax = $buyBillData->payedtax;


                            $ProductserialEX->updateDelBybillid($buyBill_Id, 0, 1); //deleteBybillid
                            ## values needed for mean and last buy price with discount #############
                            ##get $billTotalBeforeDiscount
                            $billTotalBeforeDiscount = $buyBillData->buybillaftertotalbill;
                            ##get $billDiscountVal
                            $billDiscountVal = $buyBillData->buybilldiscount;
                            if ($buyBillData->buybilldiscountrype == "1") {
                                $billDiscountVal = ($buyBillData->buybilldiscount / 100) * $billTotalBeforeDiscount;
                                $billDiscountVal = round($billDiscountVal, $noOfDecimalPlaces);
                            }
                            ########################################################################
                            /////////////////check save value before //////////////
                            //get save value
                            $saveValueBefore = getSaveValueBefore($saveId);
                            $saveValueafterValid = $saveValueBefore + $totalpayed;

                            $buyBill->conditions = 1;
                            $buyBill->buybillsysdate = $today;
                            //$buyBill->userid = $_SESSION['userid'];
                            $buyBill->userid = $buyBillData->userid;
                            $buyBill->delbyuserid = $_SESSION['userid'];
                            $buyBill->buybillid = $buyBill_Id;

                            $buyBillExt->updateConditions($buyBill);

                            //buybilldetails
                            $buyBillDetailsData = $buyBillDetailDAO->queryByBuybillid($buyBill_Id);
                            if (count($buyBillDetailsData) > 0) {
                                foreach ($buyBillDetailsData as $data) {
                                    $detailId = $data->buybilldetailid;
                                    $proprice = $data->buybilldetailprice;
                                    $productId = $data->buybilldetailproductid;
                                    $sizeId = $data->sizeid;
                                    $colorId = $data->colorid;
                                    $rowtaxval = $data->rowtaxval;
                                    $unitId = $data->productunitid;

                                    if ($data->storeid > 0) {
                                        $storeId = $data->storeid;
                                    } else {
                                        $storeId = $buyBill->buybillstoreid;
                                    }

                                    $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeId, $sizeId, $colorId);

                                    $pronum = $data->buybilldetailquantity;
                                    $scunitname = $data->otherdetailquantity;
                                    $prototal = $data->buybilldetailtotalprice;
                                    $prodis = $data->discountvalue;
                                    $productunitId = $data->productunitid;

                                    if (isset($productId)) {


                                        $isService = isService($productId);
                                        if ($isService == 0) { //if product
                                            $productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
                                            //print_r($productunitData);
                                            $productnumber = $productunitData->productnumber;
                                            $finalquantity = $pronum * $productnumber;

                                            //
                                            $prototalWithDiscount = $prototal - ($billDiscountVal * ($prototal / $billTotalBeforeDiscount));
                                            $buyPrice = round(($prototalWithDiscount / $finalquantity), $noOfDecimalPlaces); //$data->buybilldetailprice / $productnumber; //$data->buybilldetailtotalprice/$finalquantity;
                                            decreaseBuyPricesHistoryBookBuyQuantity($buyBillData->buybilldate, $storeId, $data->buybilldetailproductid, $data->sizeid, $data->colorid, $buyPrice, $finalquantity);

                                            //print_r('<br>'.$finalquantity);

                                            $storeDetailData = getStoreDetails($storeId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);
                                            $allStoredetailData = $storeDetailData[0];
                                            $storeDetailId = $storeDetailData[1];
                                            $productQuantityBefore = $storeDetailData[2];

                                            //print_r($allStoredetailData);

                                            if (count($allStoredetailData) > 0) {
                                                //update productquantity in storedetail
                                                $billnameId = $buyBillData->billnameid;
                                                $productQuantityAfter = decreaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity, $proprice, $productnumber, "buybilldetailid", $detailId, $productId, "buybilldetail", "delete", $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId, $rowtaxval, $payedtax, $cFactor);

                                                //insert in storereport
                                                insertStorereport($productId, $storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 1, $buyBill_Id, "حذف فاتورة مشتريات", "buyBillController.php", $sizeId, $colorId);
                                            } else {

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

                                                //insert in storereport
                                                insertStorereport($productId, $storeId, $finalquantity, 0, $pronum, 1, $buyBill_Id, "حذف فاتورة مشتريات", "buyBillController.php", $sizeId, $colorId);
                                            }


                                            $allStoredetailData2 = getStoreDetails($storeId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                            $allStoredetailDataother = $allStoredetailData2[0];
                                            $storeDetailIdother = $allStoredetailData2[1];
                                            $productQuantityBeforeother = $allStoredetailData2[2];



                                            if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                                //update productquantity in storedetail
                                                print_r('in if');
                                                $finalquantityother = $productQuantityBeforeother - $scunitname;
                                                $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                                //insert in storereport
                                                insertStorereportupdate2($productId, $storeId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $buyBill_Id, "حذف فاتورة  مشتريات", "buyBillController.php", $buybillDate, 1);
                                            } else {
                                                //insert in storedetail tbl
                                                if ($scunitname > 0) {
                                                    insertStoredetailupdate2($storeId, $productId, -1 * ($scunitname), $buybillDate, 1);

                                                    //insert in storereport
                                                    insertStorereportupdate2($productId, $storeId, $scunitname, 0, -1 * ($scunitname), 0, $buyBill_Id, "اضافة فاتورة  مشتريات", "buyBillController.php", $buybillDate, 1);
                                                }
                                            }
                                        }
                                    }
                                }

                                //****************** Update supplier dept ************************//
                                //check if supplier deptAfter change from  supplier deptBefor
                                //if($totaldeptafter != $totaldeptbefore)
                                //{
                                $supplierData = $supplierDAO->load($supplierId);
                                $supplierDeptBeforeInMainCurr = $supplierData->suppliercurrentDebt;
                                $supplierDeptBefore = $supplierData->suppliercurrentDebtInCurrency;
                                $supplierDeptAfterInMainCurr = ($supplierData->suppliercurrentDebt) - $finalbill;
                                $supplierDeptAfter = ($supplierData->suppliercurrentDebtInCurrency) - $buybillfinalbillC;
                                //update supplierdebt
                                updateSupplierDebt($supplierId, $supplierDeptAfter, $supplierDeptAfterInMainCurr);

                                insertSupplierDebtChange($supplierId, $supplierDeptBefore, $supplierDeptBeforeInMainCurr, $finalbill, $buybillfinalbillC, 1, "حذف فاتورة مشتريات", $buyBill_Id, $supplierDeptAfter, $supplierDeptAfterInMainCurr, "buyBillController.php", "حذف فاتورة مشتريات");
                                //}
                                //****************** Update save value ************************//
                                //check if payed or not to change the save value
                                if ($totalpayed > 0) {
                                    //get saveValue before and saveValue after plus totalPayed
                                    ##curr conversion
                                    $saveConversionFactor = 0;
                                    if ($currencyId > 1) {
                                        $billCurrData = $buyBillCurrEX->queryOneByBuybillid($buyBill_Id);
                                        $saveConversionFactor = (float) $billCurrData->saveConversionFactor;
                                    }
                                    $saveData = getSaveValueAndPlus($saveId, $totalpayed, $saveConversionFactor);
                                    $saveId = $saveData[0];
                                    $saveValuebefore = $saveData[1];
                                    $saveValueafter = $saveData[2];
                                    ##curr conversion
                                    $totalpayedSaveCurr = $saveData[3];
                                    $saveConversionFactor = $saveData[4];


                                    //update saveFrom value after add transfer
                                    updateSave($saveId, $saveValueafter);

                                    //insert into savedaily tbl from savefrom
                                    $_SESSION['client_id'] = $supplierId;
                                    insertSavedaily($saveValuebefore, $totalpayedSaveCurr, 0, $saveId, "حذف فاتورة مشتريات", $buyBill_Id, $saveValueafter, "buyBillController.php");
                                    unset($_SESSION['client_id']);
                                }
                            }
                        }
                    }
                    ########
                    $billData[0] = 2; //$billType
                    $billData[1] = 0; //$returnBuyBill_Id
                    $billData[2] = $buyBill_Id; //$buyBill_Id
                    $billData[3] = 0; //$buyAndReturnBill_Id
                    updateOverallAveragePriceOfProducts($billData);

                    //قيود اليومية
                    foreach (explode(',', $dailyentryid) as $entryid) {
                        reverseEntryWithItsID($entryid, 1);
                    }
                    ########
                    removefileMultiple(explode(',', $buyBillData->files), '../upload/buyBillFiles');
                } elseif ($ordertype == 1) { //offer
                    $buyBillOfferDAO->delete($buyBill_Id);
                    $buyBillDetailOfferDAO->deleteByBuybillid($buyBill_Id);
                }
            }
        } else { //if user choosed more than one buy bill
            $operationType = $_POST['operation'];
            $smarty->assign("operationType", $operationType);

            $choosedItemArr = $_POST['choosedItem'];

            if (count($choosedItemArr) > 0) {
                $i = 1;
                foreach ($choosedItemArr as $buyBill_Id) {
                    if ($operationType == '1') {
                        if (isset($buyBill_Id)) {

                            if ($ordertype == 0) { //bill
                                $buyBillData = $buyBillDAO->load($buyBill_Id);
                                if (count($buyBillData) > 0 && $buyBillData->conditions == 0) {
                                    $deleteOrNot = $buyBillData->conditions;
                                    if (isset($deleteOrNot) && $deleteOrNot == 0) {

                                        $CostcenterdetailEX->updatedellbytypeandmodelid(3, $buyBill_Id, 1);
                                        $billCurrData = $buyBillCurrEX->queryOneByBuybillid($buyBill_Id);
                                        $totaldeptafter = $buyBillData->buybilltotaldeptafter;
                                        $totaldeptbefore = $buyBillData->buybilltotaldeptbefor;
                                        $totalpayed = $buyBillData->buybilltotalpayed;
                                        $finalbill = $buyBillData->buybillfinalbill;
                                        $buybillfinalbillC = $billCurrData->buybillfinalbillC;
                                        $cFactor = $billCurrData->conversionFactor;
                                        $storeId = $buyBillData->buybillstoreid;
                                        $supplierId = $buyBillData->buybillsupplierid;
                                        $saveId = $buyBillData->buybillsaveid;
                                        $currencyId = $buyBillData->currencyId;
                                        $dailyentryid = $buyBillData->dailyentryid;
                                        $payedtax = $buyBillData->payedtax;


                                        $ProductserialEX->updateDelBybillid($buyBill_Id, 0, 1); //deleteBybillid
                                        ## values needed for mean and last buy price with discount #############
                                        ##get $billTotalBeforeDiscount
                                        $billTotalBeforeDiscount = $buyBillData->buybillaftertotalbill;
                                        ##get $billDiscountVal
                                        $billDiscountVal = $buyBillData->buybilldiscount;
                                        if ($buyBillData->buybilldiscountrype == "1") {
                                            $billDiscountVal = ($buyBillData->buybilldiscount / 100) * $billTotalBeforeDiscount;
                                            $billDiscountVal = round($billDiscountVal, $noOfDecimalPlaces);
                                        }
                                        ########################################################################
                                        /////////////////check save value before //////////////
                                        //get save value
                                        $saveValueBefore = getSaveValueBefore($saveId);
                                        $saveValueafterValid = $saveValueBefore + $totalpayed;

                                        $buyBill->conditions = 1;
                                        $buyBill->buybillsysdate = $today;
                                        //$buyBill->userid = $_SESSION['userid'];
                                        $buyBill->userid = $buyBillData->userid;
                                        $buyBill->delbyuserid = $_SESSION['userid'];
                                        $buyBill->buybillid = $buyBill_Id;

                                        $buyBillExt->updateConditions($buyBill);

                                        //buybilldetails
                                        $buyBillDetailsData = $buyBillDetailDAO->queryByBuybillid($buyBill_Id);
                                        if (count($buyBillDetailsData) > 0) {
                                            foreach ($buyBillDetailsData as $data) {
                                                $detailId = $data->buybilldetailid;
                                                $proprice = $data->buybilldetailprice;
                                                $productId = $data->buybilldetailproductid;
                                                $sizeId = $data->sizeid;
                                                $colorId = $data->colorid;
                                                $rowtaxval = $data->rowtaxval;
                                                $unitId = $data->productunitid;

                                                if ($data->storeid > 0) {
                                                    $storeId = $data->storeid;
                                                } else {
                                                    $storeId = $buyBill->buybillstoreid;
                                                }

                                                $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeId, $sizeId, $colorId);

                                                $pronum = $data->buybilldetailquantity;
                                                $scunitname = $data->otherdetailquantity;
                                                $prototal = $data->buybilldetailtotalprice;
                                                $prodis = $data->discountvalue;
                                                $productunitId = $data->productunitid;

                                                if (isset($productId)) {


                                                    $isService = isService($productId);
                                                    if ($isService == 0) { //if product
                                                        $productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
                                                        //print_r($productunitData);
                                                        $productnumber = $productunitData->productnumber;
                                                        $finalquantity = $pronum * $productnumber;

                                                        //
                                                        $prototalWithDiscount = $prototal - ($billDiscountVal * ($prototal / $billTotalBeforeDiscount));
                                                        $buyPrice = round(($prototalWithDiscount / $finalquantity), $noOfDecimalPlaces); //$data->buybilldetailprice / $productnumber; //$data->buybilldetailtotalprice/$finalquantity;
                                                        decreaseBuyPricesHistoryBookBuyQuantity($buyBillData->buybilldate, $storeId, $data->buybilldetailproductid, $data->sizeid, $data->colorid, $buyPrice, $finalquantity);

                                                        //print_r('<br>'.$finalquantity);

                                                        $storeDetailData = getStoreDetails($storeId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);
                                                        $allStoredetailData = $storeDetailData[0];
                                                        $storeDetailId = $storeDetailData[1];
                                                        $productQuantityBefore = $storeDetailData[2];

                                                        //print_r($allStoredetailData);

                                                        if (count($allStoredetailData) > 0) {
                                                            //update productquantity in storedetail
                                                            $billnameId = $buyBillData->billnameid;
                                                            $productQuantityAfter = decreaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity, $proprice, $productnumber, "buybilldetailid", $detailId, $productId, "buybilldetail", "delete", $billnameId, $prototal, $prodis, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId, $rowtaxval, $payedtax, $cFactor);

                                                            //insert in storereport
                                                            insertStorereport($productId, $storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 1, $buyBill_Id, "حذف فاتورة مشتريات", "buyBillController.php", $sizeId, $colorId);
                                                        } else {

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

                                                            //insert in storereport
                                                            insertStorereport($productId, $storeId, $finalquantity, 0, $pronum, 1, $buyBill_Id, "حذف فاتورة مشتريات", "buyBillController.php", $sizeId, $colorId);
                                                        }


                                                        $allStoredetailData2 = getStoreDetails($storeId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                                        $allStoredetailDataother = $allStoredetailData2[0];
                                                        $storeDetailIdother = $allStoredetailData2[1];
                                                        $productQuantityBeforeother = $allStoredetailData2[2];



                                                        if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                                            //update productquantity in storedetail
                                                            print_r('in if');
                                                            $finalquantityother = $productQuantityBeforeother - $scunitname;
                                                            $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                                            //insert in storereport
                                                            insertStorereportupdate2($productId, $storeId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $buyBill_Id, "حذف فاتورة  مشتريات", "buyBillController.php", $buybillDate, 1);
                                                        } else {
                                                            //insert in storedetail tbl
                                                            if ($scunitname > 0) {
                                                                insertStoredetailupdate2($storeId, $productId, -1 * ($scunitname), $buybillDate, 1);

                                                                //insert in storereport
                                                                insertStorereportupdate2($productId, $storeId, $scunitname, 0, -1 * ($scunitname), 0, $buyBill_Id, "اضافة فاتورة  مشتريات", "buyBillController.php", $buybillDate, 1);
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                            //****************** Update supplier dept ************************//
                                            //check if supplier deptAfter change from  supplier deptBefor
                                            //if($totaldeptafter != $totaldeptbefore)
                                            //{
                                            $supplierData = $supplierDAO->load($supplierId);
                                            $supplierDeptBeforeInMainCurr = $supplierData->suppliercurrentDebt;
                                            $supplierDeptBefore = $supplierData->suppliercurrentDebtInCurrency;
                                            $supplierDeptAfterInMainCurr = ($supplierData->suppliercurrentDebt) - $finalbill;
                                            $supplierDeptAfter = ($supplierData->suppliercurrentDebtInCurrency) - $buybillfinalbillC;
                                            //update supplierdebt
                                            updateSupplierDebt($supplierId, $supplierDeptAfter, $supplierDeptAfterInMainCurr);

                                            insertSupplierDebtChange($supplierId, $supplierDeptBefore, $supplierDeptBeforeInMainCurr, $finalbill, $buybillfinalbillC, 1, "حذف فاتورة مشتريات", $buyBill_Id, $supplierDeptAfter, $supplierDeptAfterInMainCurr, "buyBillController.php", "حذف فاتورة مشتريات");
                                            //}
                                            //****************** Update save value ************************//
                                            //check if payed or not to change the save value
                                            if ($totalpayed > 0) {
                                                //get saveValue before and saveValue after plus totalPayed
                                                ##curr conversion
                                                $saveConversionFactor = 0;
                                                if ($currencyId > 1) {
                                                    $billCurrData = $buyBillCurrEX->queryOneByBuybillid($buyBill_Id);
                                                    $saveConversionFactor = (float) $billCurrData->saveConversionFactor;
                                                }
                                                $saveData = getSaveValueAndPlus($saveId, $totalpayed, $saveConversionFactor);
                                                $saveId = $saveData[0];
                                                $saveValuebefore = $saveData[1];
                                                $saveValueafter = $saveData[2];
                                                ##curr conversion
                                                $totalpayedSaveCurr = $saveData[3];
                                                $saveConversionFactor = $saveData[4];


                                                //update saveFrom value after add transfer
                                                updateSave($saveId, $saveValueafter);

                                                //insert into savedaily tbl from savefrom
                                                $_SESSION['client_id'] = $supplierId;
                                                insertSavedaily($saveValuebefore, $totalpayedSaveCurr, 0, $saveId, "حذف فاتورة مشتريات", $buyBill_Id, $saveValueafter, "buyBillController.php");
                                                unset($_SESSION['client_id']);
                                            }
                                        }
                                    }
                                }
                                ########
                                $billData[0] = 2; //$billType
                                $billData[1] = 0; //$returnBuyBill_Id
                                $billData[2] = $buyBill_Id; //$buyBill_Id
                                $billData[3] = 0; //$buyAndReturnBill_Id
                                updateOverallAveragePriceOfProducts($billData);

                                //قيود اليومية
                                foreach (explode(',', $dailyentryid) as $entryid) {
                                    reverseEntryWithItsID($entryid, 1);
                                }
                                ########
                                removefileMultiple(explode(',', $buyBillData->files), '../upload/buyBillFiles');
                            } elseif ($ordertype == 1) { //offer
                                $buyBillOfferDAO->delete($buyBill_Id);
                                $buyBillDetailOfferDAO->deleteByBuybillid($buyBill_Id);
                            }
                        }
                    }
                    $i++;
                }
            }
        }
        $mytransactions->commit();
        $flag = 1;
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $flag = 2;
    }
    return $flag;
}

////////////////////////////save///////////////////////////
// get savecurrentvalue from save tbl

function getSaveValueBefore($saveid) {

    //to use the variable out side the funcion
    global $save;
    global $saveDAO;

    $saveData = $saveDAO->load($saveid);
    $saveValuebefore = $saveData->savecurrentvalue;

    return $saveValuebefore;
}

// get initialvalue and plus from save tbl

function getSaveValueAndPlus($saveid, $savevaluechanged, $saveConversionFactor = 0) {
    global $save;
    global $saveExt;

    $saveData = $saveExt->loadForUpdateEx($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    if ($saveConversionFactor == 0) { // if not given conversion factor use conversion factor of save
        $saveConversionFactor = $saveData->conversionFactor;
    }
    $savevaluechanged = round(($savevaluechanged * $saveConversionFactor), 4); //convert from main curr

    $saveValueafter = $saveValuebefore + $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter, $savevaluechanged, $saveConversionFactor);
}

// get initialvalue and mins from save tbl

function getSaveValueAndMins($saveid, $savevaluechanged, $saveConversionFactor = 0) {
    global $save;
    global $saveExt;

    $saveData = $saveExt->loadForUpdateEx($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    if ($saveConversionFactor == 0) { // if not given conversion factor use conversion factor of save
        $saveConversionFactor = $saveData->conversionFactor;
    }
    $savevaluechanged = round(($savevaluechanged * $saveConversionFactor), 4); //convert from main curr

    $saveValueafter = $saveValuebefore - $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter, $savevaluechanged, $saveConversionFactor);
}

// update in Save tbl

function updateSave($saveid, $savevalueafter) {
    global $save;
    global $saveExt;

    //update initialvalue in Save tbl
    $save->savecurrentvalue = $savevalueafter;
    $save->userid = $_SESSION['userid'];
    $save->saveid = $saveid;

    $saveExt->updateSaveValue($save);
}

// insert in Savedaily tbl

function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename) {
    global $saveDaily;
    global $saveDailyDAO;

    //insert in Savedaily tbl
    $saveDaily->savedailydate = date("Y-m-d H:i:s");
    $saveDaily->userid = $_SESSION['userid'];
    $saveDaily->savedailysavebefore = $savedailysavebefore;
    $saveDaily->savedailychangeamount = $savedailychangeamount;
    $saveDaily->savedailychangetype = $savedailychangetype;
    $saveDaily->saveid = $saveid;
    $saveDaily->processname = $processname;
    $saveDaily->savedailymodelid = $savedailymodelid;
    $saveDaily->savedailysaveafter = $savedailysaveafter;
    $saveDaily->tablename = $tablename;
    if (isset($_SESSION['client_id']) && !empty($_SESSION['client_id'])) {
        $mySavedaily->clientid = $_SESSION['client_id'];
    } else {
        $mySavedaily->clientid = 0;
    }

    $saveDailyDAO->insert($saveDaily);
}

/////////////////////////////////store////////////////////////////

function getStoreDetails($storeId, $productId, $unittype, $sizeColorStoreDetailId, $sizeId, $colorId) {
    // get productquantity from storedetail tbl
    global $storeDetailExt;
    global $sizeColorStoreDetailDAO;

    if ((isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) || ($sizeId > 0 && $colorId > 0)) { //sizecolor product
        if ((!isset($sizeColorStoreDetailId) || empty($sizeColorStoreDetailId)) && ($sizeId > 0 && $colorId > 0)) {
            $storeDetailId = 0;
            $productQuantityBefore = 0;
        } else {
            $storeDetailData = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);
            $storeDetailId = $storeDetailData->id;
            $productQuantityBefore = $storeDetailData->quantity;
        }
    } else {
        //select data from storedetails by storeid and productid
        $storeDetailData = $storeDetailExt->queryWithStoreAndProductandunit($productId, $storeId, $unittype);

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

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

//update and increase productquantity in storedetail tbl

function increaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount, $lastBuyPrice, $productnumber, $colName, $detailId, $productId, $tableName, $operation, $billnameId, $prototal, $rowDiscount, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId, $rowtaxval, $billPayedTaxPer, $cFactor, $probuyDiscountPer) {
    global $storeDetail;
    global $storeDetailDAO;
    global $storeDetailExt;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

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

    $myStoredetail = $storeDetailDAO->load($storedetailId);
    if (empty($sizeColorStoreDetailId) && $sizeId > 0 && $colorId > 0) {
        //try to copy from existing data in store 1
        $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($myStoredetail->productid, 1, $sizeId, $colorId);
        $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

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

        $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
    }
    //$lastBuyPriceOnePiece = $lastBuyPrice / $productChangeAmount;
    $lastBuyPriceOnePiece = $lastBuyPrice / $productnumber;
    $storeId = $storeDetailExt->getStoreidByStoredetailid($storedetailId);
    lastAndMeanBuyPrice($lastBuyPriceOnePiece, $colName, $detailId, $productId, $sizeId, $colorId, $tableName, $productquantityBefore, $productquantityAfter, $productChangeAmount, $operation, $billnameId, $prototal, $rowDiscount, $billDiscountVal, $billTotalBeforeDiscount, $rowtaxval, $billPayedTaxPer, $cFactor, $probuyDiscountPer);
    if (isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) {
        $sizecolorstoredetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);
        $sizecolorstoredetail->userid = $_SESSION['userid'];
        $sizecolorstoredetail->sysdate = date("Y-m-d H:i:s");
        $sizecolorstoredetail->quantity = $productquantityAfter;
        $sizeColorStoreDetailDAO->update($sizecolorstoredetail);
        onlineTempStoreDetailFunc($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $sizecolorstoredetail->sizeid, $sizecolorstoredetail->colorid, abs($productChangeAmount), 1);
        //affect product to make it have total quantity
        $storeDetailData = $storeDetailExt->queryWithStoreAndProductandunit($productId, $sizecolorstoredetail->storeid, 0);
        if (!isset($storeDetailData) || empty($storeDetailData->storedetailid)) {
            insertStoredetail($sizecolorstoredetail->storeid, $productId, $productChangeAmount, $sizeColorStoreDetailId, $sizeId, $colorId);
        } else {
            //$storeDetailExt->updateQuantityPlusEqualORMinusEqual($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), $productChangeAmount, 0, 0);
            $storeDetailExt->updateQuantityWithSumChild($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $sizecolorstoredetail->storeid, $sizecolorstoredetail->productid);
        }
    } else {
        //update productquantity in storedetail tbl
        $storeDetail->storedetailid = $storedetailId;
        $storeDetail->userid = $_SESSION['userid'];
        $storeDetail->storedetaildate = date("Y-m-d");
        $storeDetail->productquantity = $productquantityAfter;

        $storeDetailExt->updateProductquantity($storeDetail);
        onlineTempStoreDetailFunc($storeId, $productId, 0, 0, abs($productChangeAmount), 1);
    }

    return $productquantityAfter;
}

//update and decrease product quantity in storedetails tbl

function updateProductQuantitotherunit($storedetailId, $productquantityAfter) {
    global $storeDetail;
    global $storeDetailExt;


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

function updateProductQuantitotherunit2($storedetailId, $productquantityAfter, $unittype) {
    global $storeDetail;
    global $storeDetailExt;


    //update productquantity in storedetail tbl


    $storeDetailExt->updateProductquantity2($storedetailId, $_SESSION['userid'], date("Y-m-d"), $productquantityAfter, $unittype);

    return $productquantityAfter;
}

function decreaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount, $lastBuyPrice, $productnumber, $colName, $detailId, $productId, $tableName, $operation, $billnameId, $prototal, $rowDiscount, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId, $rowtaxval, $billPayedTaxPer, $cFactor, $probuyDiscountPer) {
    global $storeDetail;
    global $storeDetailDAO;
    global $storeDetailExt;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;


//    print_r('<br>billnameId===' . $billnameId);
    //decrease productquantity
    $productquantityAfter = $productquantityBefore - $productChangeAmount;
    $myStoredetail = $storeDetailDAO->load($storedetailId);
    if (empty($sizeColorStoreDetailId) && $sizeId > 0 && $colorId > 0) {
        //try to copy from existing data in store 1
        $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($myStoredetail->productid, 1, $sizeId, $colorId);
        $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

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

        $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
    }

    //$lastBuyPriceOnePiece = $lastBuyPrice / $productChangeAmount;
    $lastBuyPriceOnePiece = $lastBuyPrice / $productnumber;
    $storeId = $storeDetailExt->getStoreidByStoredetailid($storedetailId);
    lastAndMeanBuyPrice($lastBuyPriceOnePiece, $colName, $detailId, $productId, $sizeId, $colorId, $tableName, $productquantityBefore, $productquantityAfter, $productChangeAmount, $operation, $billnameId, $prototal, $rowDiscount, $billDiscountVal, $billTotalBeforeDiscount, $rowtaxval, $billPayedTaxPer, $cFactor, $probuyDiscountPer);
    if (isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) {
        $sizecolorstoredetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);
        $sizecolorstoredetail->userid = $_SESSION['userid'];
        $sizecolorstoredetail->sysdate = date("Y-m-d H:i:s");
        $sizecolorstoredetail->quantity = $productquantityAfter;
        $sizeColorStoreDetailDAO->update($sizecolorstoredetail);
        onlineTempStoreDetailFunc($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $sizecolorstoredetail->sizeid, $sizecolorstoredetail->colorid, (abs($productChangeAmount) * -1), 1);
        //affect product to make it have total quantity
        $storeDetailData = $storeDetailExt->queryWithStoreAndProductandunit($productId, $sizecolorstoredetail->storeid, 0);
        if (!isset($storeDetailData) || empty($storeDetailData->storedetailid)) {
            insertStoredetail($sizecolorstoredetail->storeid, $productId, $productChangeAmount, $sizeColorStoreDetailId, $sizeId, $colorId);
        } else {
            //            $storeDetailExt->updateQuantityPlusEqualORMinusEqual($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), $productChangeAmount, 0, 1);
            $storeDetailExt->updateQuantityWithSumChild($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $sizecolorstoredetail->storeid, $sizecolorstoredetail->productid);
        }
    } else {
        //update productquantity in storedetail tbl
        $storeDetail->storedetailid = $storedetailId;
        $storeDetail->userid = $_SESSION['userid'];
        $storeDetail->storedetaildate = date("Y-m-d");
        $storeDetail->productquantity = $productquantityAfter;

        $storeDetailExt->updateProductquantity($storeDetail);
        onlineTempStoreDetailFunc($storeId, $productId, 0, 0, (abs($productChangeAmount) * -1), 1);
    }

    return $productquantityAfter;
}

//add in storedetails tbl

function insertStoredetail($storeid, $productid, $productChangeAmount, $sizeColorStoreDetailId, $sizeId, $colorId) {
    global $storeDetail;
    global $storeDetailDAO;
    global $storeDetailExt;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;


    //increase productquantity
    if (empty($sizeColorStoreDetailId) && $sizeId > 0 && $colorId > 0) {
        //try to copy from existing data in store 1
        $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productid, 1, $sizeId, $colorId);
        $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

        $sizeColorStoreDetail->storeid = $storeid;
        $sizeColorStoreDetail->quantity = $productChangeAmount;
        $sizeColorStoreDetail->userid = $_SESSION['userid'];
        $sizeColorStoreDetail->sysdate = date("Y-m-d H:i:s");
        $sizeColorStoreDetail->productid = $productid;
        $sizeColorStoreDetail->sizeid = $sizeId;
        $sizeColorStoreDetail->colorid = $colorId;

        $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
    }
    $row = $storeDetailExt->queryByStoreidAndProductid($productid, $storeid);
    if (!isset($row->storedetailid) || $row->storedetailid < 1) {
        $storeDetail->userid = $_SESSION['userid'];
        $storeDetail->storedetaildate = date("Y-m-d");
        $storeDetail->productquantity = $productChangeAmount;
        $storeDetail->storeid = $storeid;
        $storeDetail->productid = $productid;

        $storeDetailDAO->insert($storeDetail);
    } else {
        $storeDetailExt->updateQuantityWithSumChild($row->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $storeid, $productid);
    }
}

//add in Storemovement tbl

function insertStorereport($productid, $storeid, $productChangeAmount, $productbefore, $productafter, $storereporttype, $storereportmodelid, $processname, $tablename, $sizeId, $colorId) {
    global $storeReport;
    global $storeReportDAO;

    $storeReport->processname = $processname;
    $storeReport->productafter = $productafter;
    $storeReport->productbefore = $productbefore;
    $storeReport->productquantity = $productChangeAmount;
    $storeReport->productid = $productid;
    $storeReport->storeid = $storeid;
    $storeReport->storereportdate = date("Y-m-d");
    $storeReport->storereportmodelid = $storereportmodelid;
    $storeReport->storereporttype = $storereporttype;
    $storeReport->tablename = $tablename;
    $storeReport->userid = $_SESSION['userid'];
    $storeReport->sizeid = $sizeId;
    $storeReport->colorid = $colorId;

    $id = $storeReportDAO->insert($storeReport);
    $storeReport->storereportid = $id;
    onlineTempStoreReportFunc($storeReport);
}

///////////////////////////////////suppliers//////////////////////
// update in rawmaterialssuppliers tbl

function updateSupplierDebt($supplierId, $supplierDebtAfter, $totaldeptafterInMainCurr) {
    global $supplier;
    global $supplierExt;
    global $today;

    //update clientdebt in client tbl
    $supplier->userid = $_SESSION['userid'];
    $supplier->suppliercurrentDebt = $totaldeptafterInMainCurr;
    $supplier->suppliercurrentDebtInCurrency = $supplierDebtAfter;
    $supplier->supplierid = $supplierId;
    $supplier->supplierdate = $today;

    $supplierExt->updatedept($supplier);
}

// insert data into Clientdebtchange tbl

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

    $supplierDebtChange->comment = $comment;
    $supplierDebtChange->processname = $processname;
    $supplierDebtChange->supplierdebtchangeafter = $supplierDebtChangeAfterInMainCurr;
    $supplierDebtChange->supplierdebtchangeamount = $supplierDebtChangeAmountInMainCurr;
    $supplierDebtChange->supplierdebtchangebefore = $supplierDebtChangeBeforeInMainCurr;
    $supplierDebtChange->debtchangafterInSupplierCurrency = $supplierDebtChangeAfter;
    $supplierDebtChange->debtchangamountInSupplierCurrency = $supplierDebtChangeAmount;
    $supplierDebtChange->debtchangbeforeInSupplierCurrency = $supplierDebtChangeBefore;
    $supplierDebtChange->supplierdebtchangedate = $today;
    $supplierDebtChange->supplierdebtchangemodelid = $supplierDebtChangeModelId;
    $supplierDebtChange->supplierdebtchangetype = $supplierDebtChangeType;
    $supplierDebtChange->supplierid = $supplierId;
    $supplierDebtChange->tablename = $tablename;
    $supplierDebtChange->userid = $_SESSION['userid'];
    $supplierDebtChange->dailyentryid = 0;

    $supplierDebtChangeDAO->insert($supplierDebtChange);
}

function saveserail() {

    global $Productserial;
    global $ProductserialDAO;
    global $ProductserialEX;

    global $buyBillDAO;

    $itr = $_POST["itr"];
    $buybillid = $_POST["buybillid"];
    $delIds = $_POST["delIds"];
    $delIds = rtrim($delIds, ',');

    $storeid = 0;
    //    $countmyusedserial = $_POST["countmyusedserial"];
    //    if ($countmyusedserial == 0) {
    if ($buybillid != "" && isset($buybillid)) {
        $billDAta = $buyBillDAO->load($buybillid);
        $storeid = $billDAta->buybillstoreid;
    }
    if ($delIds != "" && isset($delIds))
        $ProductserialEX->deleteBybillid($buybillid, 0, " and productserailid in($delIds) ");



    for ($i = 1; $i <= $itr; $i++) {
        $productid = $_POST['productid' . $i . ''];
        $sizeid = (int) $_POST['sizeid' . $i . ''];
        $colorid = (int) $_POST['colorid' . $i . ''];
        //	print_r($productid."ddd<br>");
        $buybilldetailid = $_POST['buybilldetailid' . $i . ''];
        $totalproduct = $_POST['totalproduct' . $i . ''];


        for ($x = 1; $x <= $totalproduct; $x++) {
            $productserailid = (int) $_POST['productserailid' . $x . $i . ''];
            $quantitySold = (float) $_POST['quantitySold' . $x . $i . ''];
            $serialnumber = $_POST['serialnumber' . $x . $i . ''];
            $comment = $_POST['comment' . $x . $i . ''];
            $stratdate = $_POST['stratdate' . $x . $i . ''];
            $enddate = $_POST['enddate' . $x . $i . ''];
            $quantity = $_POST['quantity' . $x . $i . ''];
            $chassisNo = $_POST['chassisNo' . $x . $i . ''];
            $motorNo = $_POST['motorNo' . $x . $i . ''];
            $theColor = $_POST['theColor' . $x . $i . ''];
            //print_r("<br>fff".$serialnumber);
            if ($quantitySold == 0) {
                $Productserial->productserailid = $productserailid;
                $Productserial->billid = $buybillid;
                $Productserial->enddate = $enddate;
                $Productserial->productid = $productid;
                $Productserial->serialnumber = $serialnumber;
                $Productserial->startdate = $stratdate;
                $Productserial->type = 0;
                $Productserial->don = $quantity;
                $Productserial->buybilldetailid = $buybilldetailid;
                $Productserial->storeid = $storeid;
                $Productserial->sizeid = $sizeid;
                $Productserial->colorid = $colorid;
                $Productserial->chassisNo = $chassisNo;
                $Productserial->motorNo = $motorNo;
                $Productserial->theColor = $theColor; //of car
                //print_r($Productserial);
                //print_r("<br>");
                if (isset($serialnumber) && $serialnumber != "" && isset($quantity) && $quantity != "") {
                    if ($productserailid > 0) {
                        $ProductserialDAO->update($Productserial, $comment);
                    } else {
                        $ProductserialDAO->insert($Productserial, $comment);
                    }
                }
            }
        }
    }
    //    }
}

function getserail($length = 6, $productid) {
    global $Productserial;
    global $ProductserialEX;
    global $ProductserialDAO;

    //global $serialArray;

    $serialArray = $_SESSION["serialarray"];

    //print_r($serialArray);
    //$productid=$_REQUEST["productid"];
    $characters = '0123456789';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    //check if this parcode already exists
    $data = $ProductserialEX->queryAllbyserial($randomString);
    if (count($data) > 0) {

        //print_r('in if <br>');
        getserail(6, $productid);
    } elseif (@in_array($randomString, $serialArray)) {
        //print_r('in elseif <br>');
        getserail(6, $productid);
    }

    /* if(in_array($randomString, $_SESSION["serialarray"]))
      {
      generateParcode();
      } */

    $serialArray[$randomString] = $randomString;
    $_SESSION["serialarray"] = $serialArray;

    return $randomString;
}

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 returnshowBillDetails($returnbuybillId) {
    global $returnBuyBillExt;
    global $returnBuyBillDetailExt;
    global $returnBuyBllCurrEX;

    $returnbuybillData = $returnBuyBillExt->loadExt($returnbuybillId);
    $returnbuybilldetailData = $returnBuyBillDetailExt->queryByBuyReturnbuybillIdExt($returnbuybillId);
    $billCurrData = $returnBuyBllCurrEX->queryOneByBuybillid($returnbuybillId);

    return array($returnbuybillData, $returnbuybilldetailData, $billCurrData);
}

function buyandreturnshowBillDetails($buyAndReturnBill_Id) {
    global $buyAndReturnBillExt;
    global $buyAndReturnBillDetailExt;
    global $buyAndRuternBillCurrEX;

    $buyBillData = $buyAndReturnBillExt->loadExt($buyAndReturnBill_Id);
    $buyBillDetails = $buyAndReturnBillDetailExt->queryByBuybillidExt($buyAndReturnBill_Id);
    $billCurrData = $buyAndRuternBillCurrEX->queryOneByBuybillid($buyAndReturnBill_Id);

    return array($buyBillData, $buyBillDetails, $billCurrData);
}

/* --------------------------------------------------------- */

function getCategoryChilds($parentid = 0) {
    global $productCatExt;
    global $productCatDAO;
    //load cat
    $parentobject = $productCatDAO->load($parentid);
    $childsArray = $productCatExt->getChilds($parentid);

    return array($parentobject, $childsArray);
}

/*
 * $rowDiscount : the discount on row "product"
 * $prototal : row total after discount
 * $billDiscountVal : the discount on bill it self including all products
 * $billTotalBeforeDiscount: bill total before $billDiscountVal
 */

function lastAndMeanBuyPrice($lastBuyPriceOnePiece, $colName, $detailId, $productId, $sizeId, $colorId, $tableName, $productquantityBefore, $productquantityAfter, $productChangeAmount, $operation = "add", $billnameId, $prototal, $rowDiscount, $billDiscountVal, $billTotalBeforeDiscount, $rowtaxval, $billPayedTaxPer, $cFactor, $probuyDiscountPer) {

    global $productDAO;
    global $buyBillDetailExt;
    global $ProductunitDAO;
    global $billSettingExt;
    global $myProductunitEx;
    global $Programsettingdata;
    global $noOfDecimalPlaces;

    ##currency convert to main currency
    $cFactor = (isset($cFactor) && !empty($cFactor)) ? $cFactor : 1;
    $billDiscountVal = $billDiscountVal / $cFactor;
    $billTotalBeforeDiscount = $billTotalBeforeDiscount / $cFactor;
    $rowtaxval = $rowtaxval / $cFactor;


    ##use quantity @allstores
    ##we has affected db but transaction isnot commited yet so now we have the before quantity
    $productquantityBeforeAllStores = 0;
    if ($sizeId > 0 && $colorId > 0) {
        $productquantityBeforeAllStores = (float) R::getCell("select sum(quantity) from sizecolorstoredetail where productid = $productId and sizeid = $sizeId and colorid = $colorId");
    } else {
        $productquantityBeforeAllStores = (float) R::getCell("select sum(productquantity) from storedetail where productid = $productId");
    }
    //
    if ($productquantityAfter < $productquantityBefore) {
        $productquantityAfter = $productquantityBeforeAllStores - $productChangeAmount;
    } else {
        $productquantityAfter = $productquantityBeforeAllStores + $productChangeAmount;
    }
    $productquantityBefore = $productquantityBeforeAllStores;
    ###################################
    $buyProduct = new Product();

    if ($operation == "delete") {
        $lastBuyDetailData = $buyBillDetailExt->getLastBuyPriceOfProductBillNotDel($productId);
        if (count($lastBuyDetailData) < 1) {
            //save prices in product
            ##2-save them
            $buyProduct = $productDAO->load($productId);

            if (isset($detailId) && !empty($detailId)) {
                $buyBillDetailExt->updatePrices_f($tableName, $buyProduct->lastbuyprice, $buyProduct->meanbuyprice, $buyProduct->lastbuyprice_withDiscount, $buyProduct->meanbuyprice_withDiscount, $buyProduct->lastbuyprice_withTax, $buyProduct->meanbuyprice_withTax, $buyProduct->lastbuyprice_withDiscountAndTax, $colName, $detailId);
            }
            //no exit we need to revrse the effect on prices
            //            //exit function now we are done
            //            return true;
        } else {
            $lastBuyDetailData = $lastBuyDetailData[0];
            $productunitData = $ProductunitDAO->load($lastBuyDetailData->productunitid);

            $productnumber = $productunitData->productnumber;
            $finalquantity = $lastBuyDetailData->buybilldetailquantity * $productnumber;

            $lastBuyPriceOnePiece = (($lastBuyDetailData->buybilldetailtotalprice + $lastBuyDetailData->discountvalue) / $finalquantity) + 0;
            $prototalWithDiscount = $lastBuyDetailData->buybilldetailtotalprice - ($billDiscountVal * ($lastBuyDetailData->buybilldetailtotalprice / $billTotalBeforeDiscount));
            $lastBuyPriceOnePiece_withDiscount = ($prototalWithDiscount / $finalquantity) + 0;
        }
    }

    //# load billSettingData
    $billpropertyid = 67; //# هذا الرقم يدل على تطبيق نسب الخصم فى فاتورة الشراء فى الداتا بيز

    $billSettingData = $billSettingExt->queryByBillidAndBillpropertyid($billnameId, $billpropertyid);



    ##1- get mean
    $buyProduct = $productDAO->load($productId);

    if ($buyProduct->meanbuyprice == NULL || $buyProduct->meanbuyprice == 0) {
        $buyProduct->meanbuyprice = $buyProduct->productBuyPrice;
    }
    if ($buyProduct->meanbuyprice_withDiscount == NULL || $buyProduct->meanbuyprice_withDiscount == 0) {
        $buyProduct->meanbuyprice_withDiscount = $buyProduct->productBuyPrice;
    }
    // var_dump('Bast: productquantityBefore'.$productquantityBefore.' $buyProduct->meanbuyprice='.$buyProduct->meanbuyprice.' prototal'.$prototal.' rowDiscount'.$rowDiscount.' probuyDiscountPer'.$probuyDiscountPer.' rowtaxval'.$rowtaxval);
    // die();
    // note :- ------- $probuyDiscountPer  is included in $prototal now
    //# عند تطبيق تطبيق نسب الخصم
    if ($billSettingData[0]->billsettingsvalue == 0) {
        //# $prototal الاجمالى
        if ($productquantityAfter < $productquantityBefore) { // $operation == "delete")
            $Bast = ($productquantityBefore * $buyProduct->meanbuyprice) - ($prototal + $rowDiscount - $rowtaxval);
            // $billTaxShareForRow = ($prototal + $rowDiscount) * ($billPayedTaxPer / 100);
            $billTaxShareForRow = $prototal * ($billPayedTaxPer / 100);
            $BastWithTax = ($productquantityBefore * $buyProduct->meanbuyprice_withTax) - ($prototal + $billTaxShareForRow);
        } else {
            $Bast = ($productquantityBefore * $buyProduct->meanbuyprice) + ($prototal + $rowDiscount - $rowtaxval);
            // $billTaxShareForRow = ($prototal + $rowDiscount) * ($billPayedTaxPer / 100);
            $billTaxShareForRow = $prototal * ($billPayedTaxPer / 100);
            $BastWithTax = ($productquantityBefore * $buyProduct->meanbuyprice_withTax) + ($prototal + $billTaxShareForRow);
        }

        $makam = $productquantityAfter;
        $meanBuyPrice = round(($Bast / $makam), $noOfDecimalPlaces);
        $meanBuyPriceWithTax = round(($BastWithTax / $makam), $noOfDecimalPlaces);
        ##with discount ##decrease pro total with its share of general discount
        $prototalWithDiscount = $prototal - ($billDiscountVal * ($prototal / $billTotalBeforeDiscount));
        if ($productquantityAfter < $productquantityBefore) { // $operation == "delete")
            $Bast = ($productquantityBefore * $buyProduct->meanbuyprice_withDiscount) - $prototalWithDiscount;
        } else {
            $Bast = ($productquantityBefore * $buyProduct->meanbuyprice_withDiscount) + $prototalWithDiscount;
        }

        $makam = $productquantityAfter;
        $meanBuyPrice_withDiscount = round(($Bast / $makam), $noOfDecimalPlaces);
    } else {
        $realPrice_precentage = $buyProduct->buypricereal_precentage; //#   نسبة سعر الشراء الفعلى
        $total_precntage = ($realPrice_precentage / 100) * ($prototal + $rowDiscount - $rowtaxval); //# نسبة شعر الشراء على 100 * الاجمالى
        if ($productquantityAfter < $productquantityBefore) { // $operation == "delete")
            $Bast = ($productquantityBefore * $buyProduct->meanbuyprice) - ($prototal - $total_precntage);
        } else {
            $Bast = ($productquantityBefore * $buyProduct->meanbuyprice) + ($prototal - $total_precntage);
        }

        $makam = $productquantityAfter;
        $meanBuyPrice = round(($Bast / $makam), $noOfDecimalPlaces);
        ##with discount ##decrease pro total with its share of general discount
        $prototalWithDiscount = $prototal - ($billDiscountVal * ($prototal / $billTotalBeforeDiscount));
        $realPrice_precentage = $buyProduct->buypricereal_precentage; //#   نسبة سعر الشراء الفعلى
        $total_precntage = ($realPrice_precentage / 100) * $prototalWithDiscount; //# نسبة شعر الشراء على 100 * الاجمالى
        if ($productquantityAfter < $productquantityBefore) { // $operation == "delete")
            $Bast = ($productquantityBefore * $buyProduct->meanbuyprice) - ($prototalWithDiscount - $total_precntage);
        } else {
            $Bast = ($productquantityBefore * $buyProduct->meanbuyprice) + ($prototalWithDiscount - $total_precntage);
        }

        $makam = $productquantityAfter;
        $meanBuyPrice_withDiscount = round(($Bast / $makam), $noOfDecimalPlaces);
    }

    ##
    $lastBuyPriceOnePiece = $lastBuyPriceOnePiece - $probuyDiscountPer;
    $lastBuyPriceOnePiece_WithRowTax = $lastBuyPriceOnePiece + ($rowtaxval / $productChangeAmount);
    $lastBuyPriceOnePiece_WithTax = $lastBuyPriceOnePiece_WithRowTax + ($lastBuyPriceOnePiece_WithRowTax * ($billPayedTaxPer / 100)); //$billTaxPer is like 0.14 is bill tax percentage
    //
    ##2-save them
    $buyProduct->meanbuyprice = abs($meanBuyPrice);
    $buyProduct->meanbuyprice_withDiscount = abs($meanBuyPrice_withDiscount);
    $buyProduct->lastbuyprice = $lastBuyPriceOnePiece;
    $buyProduct->lastbuyprice_withTax = abs($lastBuyPriceOnePiece_WithTax);
    $buyProduct->meanbuyprice_withTax = abs($meanBuyPriceWithTax);

    //calc $rowDiscountPer============
    $rowDiscountPer = (($rowDiscount + $probuyDiscountPer) / ($prototal + $rowDiscount + $probuyDiscountPer - $rowtaxval)) * 100;
    if ($productquantityAfter < $productquantityBefore) { // $operation == "delete")
        if ($operation == "add") {
            $lastBuyPriceOnePiece_withDiscount = ($prototalWithDiscount / $productChangeAmount);
            $lastBuyPriceOnePiece_withDiscountAndTax = $lastBuyPriceOnePiece_withDiscount + ($rowtaxval / $productChangeAmount);
        }
        $buyProduct->lastbuyprice_withDiscount = round($lastBuyPriceOnePiece_withDiscount, $noOfDecimalPlaces);
        $buyProduct->lastbuyprice_withDiscountAndTax = round($lastBuyPriceOnePiece_withDiscountAndTax, $noOfDecimalPlaces);
        $newWeightedDiscount = (($productquantityBefore * $buyProduct->weightedDiscount) - ($productChangeAmount * $rowDiscountPer)) / ($productquantityBefore - $productChangeAmount);
        $buyProduct->weightedDiscount = round($newWeightedDiscount, $noOfDecimalPlaces);
    } else {
        $buyProduct->lastbuyprice_withDiscount = round(($prototalWithDiscount / $productChangeAmount), $noOfDecimalPlaces);
        $buyProduct->lastbuyprice_withDiscountAndTax = round($buyProduct->lastbuyprice_withDiscount + ($buyProduct->lastbuyprice_withDiscount * ($billPayedTaxPer / 100)), $noOfDecimalPlaces);
        $newWeightedDiscount = (($productquantityBefore * $buyProduct->weightedDiscount) + ($productChangeAmount * $rowDiscountPer)) / ($productquantityBefore + $productChangeAmount);
        $buyProduct->weightedDiscount = round($newWeightedDiscount, $noOfDecimalPlaces);
    }

    //another check after calculation to stop zero value
    if ($buyProduct->meanbuyprice == NULL || $buyProduct->meanbuyprice == 0) {
        $buyProduct->meanbuyprice = $buyProduct->productBuyPrice;
    }
    if ($buyProduct->meanbuyprice_withDiscount == NULL || $buyProduct->meanbuyprice_withDiscount == 0) {
        $buyProduct->meanbuyprice_withDiscount = $buyProduct->productBuyPrice;
    }

    $productDAO->update($buyProduct);
    if ($operation != "delete") {
        if (isset($detailId) && !empty($detailId)) {
            $buyBillDetailExt->updatePrices_f($tableName, $buyProduct->lastbuyprice, $buyProduct->meanbuyprice, $buyProduct->lastbuyprice_withDiscount, $buyProduct->meanbuyprice_withDiscount, $buyProduct->lastbuyprice_withTax, $buyProduct->meanbuyprice_withTax, $buyProduct->lastbuyprice_withDiscountAndTax, $colName, $detailId);
        }
    }

    if ($Programsettingdata->updateProUnitPricesOnPriceUpdate == 0) {
        $myProductunitEx->updateQuery("UPDATE productunit SET proUnitBuyPrice  = $buyProduct->lastbuyprice * productnumber WHERE productid = $productId");
    }
}

function updateOverallAveragePriceOfProducts($billData) {
    global $buyBillDetailExt;
    global $productExt;

    $billType = (int) $billData[0];
    $returnBuyBill_Id = $billData[1];
    $buyBill_Id = $billData[2];
    $buyAndReturnBill_Id = $billData[3];

    $queryStringBuy = '';
    $queryStringBuyAndRet = '';
    //save btn clicked, go to new bill after print but you need to print bill too
    switch ($billType) {
        case 1: //ret
            //wont change price we take buy not ret
            break;
        case 2: //buy
            $queryStringBuy = " and buybilldetailproductid in (select buybilldetailproductid from buybilldetail where buybillid = $buyBill_Id) ";
            $queryStringBuyAndRet = " and buybilldetailproductid in (select buybilldetailproductid from buybilldetail where buybillid = $buyBill_Id) ";
            break;
        case 3: //buy and ret
            $queryStringBuy = " and buybilldetailproductid in (select buybilldetailproductid from buyandruternbilldetail where buybillid = $buyAndReturnBill_Id and billtype =0) ";
            $queryStringBuyAndRet = " and buybilldetailproductid in (select buybilldetailproductid from buyandruternbilldetail where buybillid = $buyAndReturnBill_Id and billtype =0) ";
            break;
    }
    if ($queryStringBuy != "" || $queryStringBuyAndRet != "") {
        $productsOverAllAverage = $buyBillDetailExt->getOverallAverage($queryStringBuy, $queryStringBuyAndRet);
        $sql = '';
        foreach ($productsOverAllAverage as $value) {
            $overallAverage = (float) $value->overallAverage;
            $sql .= "UPDATE product SET overAllAveragePrice = $overallAverage WHERE productId = $value->buybilldetailproductid;";
        }

        if ($sql != '') {
            $productExt->updateBulk($sql);
        }
    }
}

function updateSerailQty($productserailId, $soldQuantity) {
    global $myProductserial;
    global $myProductserialEx;

    $productQuantity = $myProductserialEx->getProductQuantity($productserailId);
    if ($productQuantity > 0) {
        $availableQty = $productQuantity - $soldQuantity;
        //if(isset($availableQty) && $availableQty < 0)
        //			{
        //				//في حالة بيع منتج بكمية أكبر من عدد السريالات
        //			}
        //			else
        //			{
        //
        //			}

        $myProductserial->productserailid = $productserailId;
        $myProductserial->don = $availableQty;
        //print_r($myProductserial);
        $myProductserialEx->updateDon($myProductserial);
    }
}

function updateSerailQty_ForReturn($productserailId, $returnedQuantity) {
    global $myProductserial;
    global $myProductserialEx;

    $productQuantity = $myProductserialEx->getProductQuantity($productserailId);

    //print_r('<br>returnedQuantity'.$returnedQuantity);
    //print_r('<br>productQuantity'.$productQuantity);
    //    if ($productQuantity > 0) {
    $availableQty = $productQuantity + $returnedQuantity;

    //print_r('<br>availableQty'.$availableQty);
    $myProductserial->productserailid = $productserailId;
    $myProductserial->don = $availableQty;
    //print_r('<br>cccccccccccccccccccc'.$productserailId);
    $myProductserialEx->updateDon($myProductserial);
    //    }
}

function updateproductpriceFunc($productId, $finalprice) {
    global $productDAO;
    global $productExt;
    global $Programsettingdata;

    if ($Programsettingdata->changeBuyPriceChangeSellInBuyBillCtrl == 0) { //dont change sell prices //only buy prices
        $productExt->updateproductBuyPrice($productId, $finalprice);
    } else {
        $proData = $productDAO->load($productId);
        $oldBuyPrice = $proData->productBuyPrice;
        $newBuyPrice = $finalprice;
        if ($Programsettingdata->changeBuyPriceChangeSellInBuyBillCtrl == 1) { // by value diffrence
            $diff = $newBuyPrice - $oldBuyPrice;
            $productExt->updateproductBuyAndSellPriceByValue($productId, $finalprice, $diff);
        } elseif ($Programsettingdata->changeBuyPriceChangeSellInBuyBillCtrl == 2) { // by percentage diffrence
            $diff = $newBuyPrice / $oldBuyPrice;
            $productExt->updateproductBuyAndSellPriceByPercentage($productId, $finalprice, $diff);
        }
    }
}

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

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 useSpecializedParcodeDigits($parcode, $productId, $specializedParcodeDigits) {
    $preDigits = '';
    if (strlen($productId) != $specializedParcodeDigits) {
        $noDigitsLeft = $specializedParcodeDigits - strlen($productId);
        for ($j = 0; $j < $noDigitsLeft; $j++) {
            $preDigits .= '0';
        }
    }
    $newParcode = 'i' . $preDigits . $productId;
    return $newParcode;
}

function doBillDailyEntry($billType, $buyBill_Id, $returnBuyBill_Id, $buyAndReturnBill_Id, $billTotalBeforeDiscount, $storeId, $taxVal, $totalpayed, $saveId, $remin, $supdata, $billDiscountVal, $taxOfDiscountVal, $billAdditionVal) {
    global $storeDAO;
    global $mySaveRecord;
    global $buyBillExt;

    ## step zero perpare variables
    $taxOfDiscountTreeId = 0;
    $vatTreeId = 0;
    $buyTreeId = 0;
    $billComment = '';
    $table = '';
    $billIdColumn = '';
    $billId = 0;
    $detailsURL = '';
    if ($billType == 2) { //buy
        $taxOfDiscountTreeId = 107; ##ضريبة الخصم من المنبع - دائنة
        $vatTreeId = 76; ##ضريبة القيمة المضافة - مدينة
        $billComment = 'اضافة فاتورة مشتريات رقم ' . $buyBill_Id;
        $table = 'buybill';
        $billIdColumn = 'buybillid';
        $billId = $buyBill_Id;
        $detailsURL = "buyBillController.php?do=details&id=" . $billId;
    } elseif ($billType == 1) { //ret
        $taxOfDiscountTreeId = 77; ##ضريبة الخصم من المنبع - مدينة
        $vatTreeId = 106; ##ضريبة القيمة المضافة - دائنة
        $billComment = 'اضافة فاتورة مردود مشتريات رقم ' . $returnBuyBill_Id;
        $table = 'returnbuybill';
        $billIdColumn = 'returnbuybillid';
        $billId = $returnBuyBill_Id;
        $detailsURL = "returnBuyBillController.php?do=details&id=" . $billId;
    } elseif ($billType == 3) { //buy&ret
        $billComment = 'اضافة فاتورة مشتريات و مردود رقم ' . $buyAndReturnBill_Id;
        $table = 'buyandruternbill';
        $billIdColumn = 'buybillid';
        $billId = $buyAndReturnBill_Id;
        $detailsURL = "buyAndReturnBillController.php?do=details&id=" . $billId;
    }

    ##1 main bill entry
    // start المشتريات
    $dailyEntryIdOfMainBuyEntry = 0;
    if ($billTotalBeforeDiscount) {
        ###########################
        ##from
        $dailyEntry->entryComment = $billComment;
        $dailyEntry->fromFlag = 1;
        $dailyEntryDebtorArray = array();
        $dailyEntryCreditorArray = array();

        // من المخزن
        $dailyEntryDebtor = new stdClass();
        $dailyEntryDebtor->value = abs($billTotalBeforeDiscount) - abs($billDiscountVal) + abs($billAdditionVal);
        $storeData = $storeDAO->load($storeId);
        $dailyEntryDebtor->accountstreeid = $storeData->treeId;
        if ($billType == 2) {
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        } else {
            array_push($dailyEntryCreditorArray, $dailyEntryDebtor);
        }
        //من ضريبة القيمة المضافة
        if (!empty($taxVal) && $taxVal != 0) {
            $dailyEntryDebtor = new stdClass();
            $dailyEntryDebtor->value = abs($taxVal);
            $dailyEntryDebtor->accountstreeid = $vatTreeId; //ضريبة القيمة المضافة
            if ($billType == 2) {
                array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            } else {
                array_push($dailyEntryCreditorArray, $dailyEntryDebtor);
            }
        }





        ###########################
        ##to
        /* //  الى حساب الخزنة
          if ($totalpayed != 0) {
          $dailyEntryCreditor = new stdClass();
          $dailyEntryCreditor->value = abs($totalpayed);
          $dataSave = $mySaveRecord->load($saveId);
          $idTreeSave = $dataSave->treeId;
          $dailyEntryCreditor->accountstreeid = $idTreeSave;

          if ($billType == 2) {
          array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
          } else {
          array_push($dailyEntryDebtorArray, $dailyEntryCreditor);
          }
          } */
        //المتبقى من المورد
        if ($remin != 0) {
            $dailyEntryCreditor = new stdClass();
            $dailyEntryCreditor->value = abs($remin + $totalpayed); //abs($remin)
            $dailyEntryCreditor->accountstreeid = $supdata->treeId;
            if ($billType == 2) {
                array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            } else {
                array_push($dailyEntryDebtorArray, $dailyEntryCreditor);
            }
        }
        //        //الى خصم مكتسب
        //        if (!empty($billDiscountVal) && $billDiscountVal != 0) {
        //            $dailyEntryCreditor = new stdClass();
        //            $dailyEntryCreditor->value = abs($billDiscountVal);
        //            $dailyEntryCreditor->accountstreeid = 146; //خصم مكتسب
        //            if ($billType == 2) {
        //                array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
        //            } else {
        //                array_push($dailyEntryDebtorArray, $dailyEntryCreditor);
        //            }
        //        }
        //الى ضريبة الخصم
        if (!empty($taxOfDiscountVal) && $taxOfDiscountVal != 0) {
            $dailyEntryCreditor = new stdClass();
            $dailyEntryCreditor->value = abs($taxOfDiscountVal);
            $dailyEntryCreditor->accountstreeid = $taxOfDiscountTreeId; //ضريبة الخصم
            if ($billType == 2) {
                array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            } else {
                array_push($dailyEntryDebtorArray, $dailyEntryCreditor);
            }
        }
        //var_dump($dailyEntryDebtorArray);
        //var_dump($dailyEntryCreditorArray);
        $returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $billId, $detailsURL);
        $dailyEntryIdOfMainBuyEntry = $returnDailyId[1];
    }

    ##2 supplier Payment entry  ## cancelled by eng.sherif , it is done @Dof3at
    $dailyEntryIdOfSupplierPay = 0;
    if ($totalpayed != 0) {
        $dailyEntry->entryComment = $billComment . ' - سداد الفاتورة للمورد';
        $dailyEntry->fromFlag = 1;
        $dailyEntryDebtorArray = array();
        $dailyEntryCreditorArray = array();


        //من حساب المورد
        $dailyEntryDebtor = new stdClass();
        $dailyEntryDebtor->value = abs($totalpayed);
        $dailyEntryDebtor->accountstreeid = $supdata->treeId;
        if ($billType == 2) {
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        } else {
            array_push($dailyEntryCreditorArray, $dailyEntryDebtor);
        }

        //  الى حساب الخزنة
        $dailyEntryCreditor = new stdClass();
        $dailyEntryCreditor->value = abs($totalpayed);
        $dataSave = $mySaveRecord->load($saveId);
        $idTreeSave = $dataSave->treeId;
        $dailyEntryCreditor->accountstreeid = $idTreeSave;

        if ($billType == 2) {
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
        } else {
            array_push($dailyEntryDebtorArray, $dailyEntryCreditor);
        }


        $returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $billId, $detailsURL);
        $dailyEntryIdOfSupplierPay = $returnDailyId[1];
    }



    $dailyentryidS = "$dailyEntryIdOfMainBuyEntry,$dailyEntryIdOfSupplierPay";
    $buyBillExt->executeSQLQuery("update $table set dailyentryid='" . $dailyentryidS . "' where $billIdColumn=$billId");
}

function CURL_IT2($data_arr, $url) {
    ##preparing session data
    //$projectURL = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/';
    $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $url;

    ##appending necessary data
    $data_arr['curlpost'] = '1';
    $data_arr['sessionlist'] = json_encode($_SESSION);


    // set post fields
    //    $post = [
    //        'data_arr' => json_encode($data_arr), //encode it as it is array
    //    ];
    $post = $data_arr;
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        //echo 'Error : ' . curl_error($ch);
    }

    // close the connection, release resources used
    curl_close($ch);
    // do anything you want with your response
    //var_dump($response);
    print_r($response);
    return $response;
}
