<?php

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

//global varable
global $showoutside;

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

//here the db files that include in the file
include("../public/include_dao.php");
include_once("dailyentryfun.php");
//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');
//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');
//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');

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

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

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


//get the do the action
$do = $_GET['do'];

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

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

  Controller Name :- buyAndReturnBillController

  OPERTATION in Controller

  1- show buyAndReturnBill details
  2- show buyAndReturnBills
  3- delete buyAndReturnBill

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

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

//here goes the instances and general variables

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

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



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

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

//Buyandruternbill
$buyAndReturnBill = new Buyandruternbill();
$buyAndReturnBillDAO = new BuyandruternbillMySqlDAO();
$buyAndReturnBillExt = new BuyandruternbillMySqlExtDAO();
//Buyandruternbilldetail
$buyAndReturnBillDetail = new Buyandruternbilldetail();
$buyAndReturnBillDetailDAO = new BuyandruternbilldetailMySqlDAO();
$buyAndReturnBillDetailExt = new BuyandruternbilldetailMySqlExtDAO();
//Buybilldetail
$buyBillDetail = new Buybilldetail();
$buyBillDetailDAO = new BuybilldetailMySqlDAO();
$buyBillDetailExt = new BuybilldetailMySqlExtDAO();
//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();
//Product
$product = new Product();
$productDAO = $myProductRecord = 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 = new Productserial();
$ProductserialDAO = new ProductserialMySqlDAO();
$ProductserialEX = new ProductserialMySqlExtDAO();

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

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

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();
//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();

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

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

//check and use the condition that suits this action
if (empty($do)) {

} elseif ($do == "editprint") {
    //editprint
    //here the permission check
    include_once("../public/authentication.php");


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

    $buyAndReturnBill_Id = $_GET['id'];

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

    $buyBillDetails = $detailsData[1];


    //getalldiscount
    $buybilldiscount = $detailsData[0]->buybilldiscount;
    $buybilldiscountrype = $detailsData[0]->buybilldiscountrype; //1 مباشر
    $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
    $details = countBillDetails($buyAndReturnBill_Id);
    $countBillDetails_buy = $details[0];
    $countBillDetails_return = $details[1];
    $totalBuyPrice = $details[2];
    $totalReturnBuyPrice = $details[3];

    $smarty->assign('countBillDetails_buy', $countBillDetails_buy);
    $smarty->assign('countBillDetails_return', $countBillDetails_return);
    $smarty->assign('totalBuyPrice', $totalBuyPrice);
    $smarty->assign('totalReturnBuyPrice', $totalReturnBuyPrice);

    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('buyBillDetails', $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);

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

    $smarty->display("buyAndReturnBillview/editprint.html");
} elseif ($do == "details") {
    include_once("../public/authentication.php");

    $countBillDetails = 0;

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


    $buyAndReturnBill_Id = $_GET['id'];

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

    $buyBillDetails = $detailsData[1];

    //getalldiscount
    $buybilldiscount = $detailsData[0]->buybilldiscount;
    $buybilldiscountrype = $detailsData[0]->buybilldiscountrype; //1 مباشر
    $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
    $details = countBillDetails($buyAndReturnBill_Id);

    $countBillDetails_buy = $details[0];
    $countBillDetails_return = $details[1];
    $totalBuyPrice = $details[2];
    $totalReturnBuyPrice = $details[3];
    $smarty->assign('countBillDetails_buy', $countBillDetails_buy);
    $smarty->assign('countBillDetails_return', $countBillDetails_return);
    $smarty->assign('totalBuyPrice', $totalBuyPrice);
    $smarty->assign('totalReturnBuyPrice', $totalReturnBuyPrice);

    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('buyBillDetails', $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);

    //here the smarty templates
    $smarty->assign("customBuyBill", 1);
    $smarty->assign("buyBillNewProductScript", 1);

    $smarty->display("buyAndReturnBillview/details.html");
}
//add serail
elseif ($do == "addserial") {
    include_once("../public/authentication.php");

    $buyAndReturnBill_Id = $_GET['id'];

    $detailsData = showBillDetails($buyAndReturnBill_Id);

    $myusedserial = $ProductserialEX->queryAllbybillandtype($buyAndReturnBill_Id, 1);
    $smarty->assign('countmyusedserial', count($myusedserial));

    $buyBillData = $detailsData[0];

    $buyBillDetails = $detailsData[1];
    $i = 1;
    foreach ($buyBillDetails as $mybuyBillDetails) {
        if ($mybuyBillDetails->billtype == 0) {
            $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);
                }
            }

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

            $buybilldetailid = $mybuyBillDetails->buybilldetailid;
            $allseraildata = $ProductserialEX->queryWithProductIdandbillid($productid, $buybillid, 1, $buybilldetailid);
            $smarty->assign('allseraildata' . $i . '', $allseraildata);

            $i++;
        } else {

        }
    }

    foreach ($buyBillDetails as $key => $row) {
        if ($row->billtype == 1) {
            unset($buyBillDetails[$key]);
        }
    }

    $countBillDetails = count($buyBillDetails);
    $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);

    //here the smarty templates
    //	$smarty->assign("customBuyBill",1);
    $smarty->assign("buyBillNewProductScript", 1);

    $smarty->display("buyAndReturnBillview/addserial.html");
} elseif ($do == "addoneserial") {
    include_once("../public/authentication.php");

    $buyAndReturnBill_Id = $_GET['id'];

    $detailsData = showBillDetails($buyAndReturnBill_Id);

    $myusedserial = $ProductserialEX->queryAllbybillandtype($buyAndReturnBill_Id, 1);
    $smarty->assign('countmyusedserial', count($myusedserial));

    $buyBillData = $detailsData[0];

    $buyBillDetails = $detailsData[1];
    $i = 1;
    foreach ($buyBillDetails as $mybuyBillDetails) {
        if ($mybuyBillDetails->billtype == 0) {
            $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);
                }
            }

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

            $buybilldetailid = $mybuyBillDetails->buybilldetailid;
            $allseraildata = $ProductserialEX->queryWithProductIdandbillid($productid, $buybillid, 1, $buybilldetailid);
            $smarty->assign('allseraildata' . $i . '', $allseraildata);

            $i++;
        } else {

        }
    }

    foreach ($buyBillDetails as $key => $row) {
        if ($row->billtype == 1) {
            unset($buyBillDetails[$key]);
        }
    }

    $countBillDetails = count($buyBillDetails);
    $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);

    //here the smarty templates
    //	$smarty->assign("customBuyBill",1);
    $smarty->assign("buyBillNewProductScript", 1);

    $smarty->display("buyAndReturnBillview/addoneserial.html");
} 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);

    $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 buyandruternbill.conditions = 0 ';
    }

    //display the converted time ##reportsPlusHours
    $Programsetting = $ProgramsettingDAO->load(1);

    if (isset($supplierId) && $supplierId > 0) {
        showBySupplier($supplierId, $delString);

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

        $message = "رقم الفاتورة: " . $serial;
        $smarty->assign("message", $message);
    } else if (isset($buybillid) && $buybillid != "-1") {
        showBybuybillid($buybillid, $delString);
        $message = "الرقم المتسلسل: " . $buybillid;
        $smarty->assign("message", $message);
    } else if (!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 {
            $endDatePrepared = $endDate . ' 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("buyAndReturnBillview/show.html");
} elseif ($do == "delete") {
    try {
        delete();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "saveserail") {
    try {
        saveserail();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}
//here the global templates
$smarty->display("footer.html");

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

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

    $buyBillData = $buyAndReturnBillExt->loadExt($buyAndReturnBill_Id);
    $buyBillDetails = $buyAndReturnBillDetailExt->queryByBuybillidExt($buyAndReturnBill_Id);
    $billCurrData = $buyAndRuternBillCurrEX->queryOneByBuybillid($buyAndReturnBill_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);
}

function countBillDetails($buyAndReturnBill_Id) {
    global $buyAndReturnBillExt;
    global $buyAndReturnBillDetailExt;

    $countBillDetails_return = 0;
    $countBillDetails_buy = 0;

    $buyBillDetails_buy = $buyAndReturnBillDetailExt->queryByBuybillidANDType($buyAndReturnBill_Id, 0);
    $buyBillDetails_return = $buyAndReturnBillDetailExt->queryByBuybillidANDType($buyAndReturnBill_Id, 1);

    /////////////الكمية المباعة والكمية المرتجعة
    //////////////إجمالي المباع وإجمالي المردود
    //get count
    if (count($buyBillDetails_buy) > 0) {
        foreach ($buyBillDetails_buy as $detail) {
            //عدد القطع المباعة
            $countBillDetails_buy += $detail->buybilldetailquantity;

            //إجمالي المبيعات
            $totalBuyPrice += $detail->buybilldetailtotalprice;
        }
    }

    //get count
    if (count($buyBillDetails_return) > 0) {
        foreach ($buyBillDetails_return as $detail) {
            //عدد القطع المرتجعة
            $countBillDetails_return += $detail->buybilldetailquantity;

            //إجمالي المردودات
            $totalReturnBuyPrice += $detail->buybilldetailtotalprice;
        }
    }

    return array($countBillDetails_buy, $countBillDetails_return, $totalBuyPrice, $totalReturnBuyPrice);
}

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

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

function loadBillProperties($billnameid) {
    global $billSettingExt;

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

    return $billSettingsData;
}

function showAll() {
    global $buyAndReturnBillExt;
    global $smarty;
    $totalBills = 0;
    $buyBillData = $buyAndReturnBillExt->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 $buyAndReturnBillExt;
    global $smarty;
    $totalBills = 0;
    $buyBillData = $buyAndReturnBillExt->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 showBySupplier($supplierId, $delString) {
    global $buyAndReturnBillExt;
    global $smarty;
    $totalBills = 0;
    $buyBillData = $buyAndReturnBillExt->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 showByBillSerial($serial, $delString) {
    global $buyAndReturnBillExt;
    global $smarty;
    $totalBills = 0;
    $buyBillData = $buyAndReturnBillExt->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 $buyAndReturnBillExt;
    global $smarty;
    $totalBills = 0;
    $buyBillData = $buyAndReturnBillExt->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 $buyAndReturnBill;
    global $buyAndReturnBillDAO;
    global $buyAndReturnBillExt;
    global $buyAndReturnBillDetail;
    global $buyAndReturnBillDetailDAO;
    global $buyAndReturnBillDetailExt;
    //
    global $buyAndRuternBillCurr;
    global $buyAndRuternBillCurrDAO;
    global $buyAndRuternBillCurrEX;

    global $CostcenterdetailDAO;
    global $Costcenterdetail;
    global $CostcenterdetailEX;

    global $sizeColorStoreDetailEX;


    global $today;
    global $noOfDecimalPlaces;

    //Transaction
    $mytransactions = new Transaction();
    try {
        $buyAndReturnBill_Id_one = $_GET['id'];

        if (isset($buyAndReturnBill_Id_one)) {
            $buyAndReturnBill_Id = $buyAndReturnBill_Id_one;
            if (isset($buyAndReturnBill_Id)) {
                $buyBillData = $buyAndReturnBillDAO->load($buyAndReturnBill_Id);
                $billCurrData = $buyAndRuternBillCurrEX->queryOneByBuybillid($buyAndReturnBill_Id);
                if (count($buyBillData) > 0 && $buyBillData->conditions == 0) {
                    $deleteOrNot = $buyBillData->conditions;
                    if (isset($deleteOrNot) && $deleteOrNot != 1) {
                        $CostcenterdetailEX->updatedellbytypeandmodelid(5, $buyAndReturnBill_Id, 1);


                        $dailyentryid = $buyBillData->dailyentryid;
                        $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;
                        $buybilltotalbill = $buyBillData->buybilltotalbill;
                        $buybillaftertotalbill = $buyBillData->buybillaftertotalbill;
                        $currencyId = $buyBillData->currencyId;
                        $payedtax = $buyBillData->payedtax;

                        foreach (explode(',', $dailyentryid) as $entryid) {
                            reverseEntryWithItsID($entryid, 1);
                        }

                        ## 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, 2);
                        }
                        ########################################################################

                        $buyBill->conditions = 1;
                        $buyBill->buybillsysdate = date("Y-m-d H:i:s");
                        //$buyBill->userid = $_SESSION['userid'];
                        $buyBill->userid = $buyBillData->userid;
                        $buyBill->delbyuserid = $_SESSION['userid'];
                        $buyBill->buybillid = $buyAndReturnBill_Id;

                        $buyAndReturnBillExt->updateConditions($buyBill);

                        //buybilldetails
                        $buyBillDetailsData = $buyAndReturnBillDetailDAO->queryByBuybillid($buyAndReturnBill_Id);
                        if (count($buyBillDetailsData) > 0) {
                            foreach ($buyBillDetailsData as $data) {
                                $proprice = $data->buybilldetailprice;
                                $detailId = $data->buybilldetailid;
                                $productId = $data->buybilldetailproductid;
                                $pronum = $data->buybilldetailquantity;
                                $billType = $data->billtype;
                                $productunitId = $data->productunitid;
                                $scunitname = $data->otherdetailquantity;

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

                                $sizeId = $data->sizeid;
                                $colorId = $data->colorid;

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

                                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                                $productnumber = $productunitData->productnumber;
                                $finalquantity = $pronum * $productnumber;
                                //print_r($allStoredetailData);
                                $pronum = $data->buybilldetailquantity;
                                $scunitname = $data->otherdetailquantity;
                                $prototal = $data->buybilldetailtotalprice;
                                $prodis = $data->discountvalue;
                                $rowtaxval = $data->rowtaxval;
                                $isService = isService($productId);
                                if ($isService == 0) { //if product
                                    if (isset($productId) && $billType == 0) {
                                        //
                                        $prototalWithDiscount = $prototal - ($billDiscountVal * ($prototal / $billTotalBeforeDiscount));
                                        $buyPrice = round(($prototalWithDiscount / $finalquantity), $noOfDecimalPlaces);  //$buyBillDetail->buybilldetailtotalprice/$finalquantity;
                                        decreaseBuyPricesHistoryBookBuyQuantity($buyBillData->buybilldate, $storeId, $data->buybilldetailproductid, $data->sizeid, $data->colorid, $buyPrice, $finalquantity);

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



                                        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, $buyAndReturnBill_Id, "حذف فاتورة مشتريات ومردودات", "buyAndReturnBillController.php", $sizeId, $colorId);
                                        } else {
                                            //insert in storedetail tbl
                                            insertStoredetail($storeId, $productId, $finalquantity, $sizeColorStoreDetailId, $sizeId, $colorId);

                                            //insert in storereport
                                            insertStorereport($productId, $storeId, $finalquantity, 0, $finalquantity, 1, $buyAndReturnBill_Id, "حذف فاتورة مشتريات ومردودات", "buyAndReturnBillController.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, $buyAndReturnBill_Id, "حذف فاتورة مشتريات ومردودات", "buyAndReturnBillController.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, $buyAndReturnBill_Id, "حذف فاتورة مشتريات ومردودات", "buyAndReturnBillController.php", $buybillDate, 1);
                                            }
                                        }
                                    } elseif (isset($productId) && $billType == 1) {
                                        $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 = increaseProductQuantity($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, 0, $buyAndReturnBill_Id, "حذف فاتورة مشتريات ومردودات", "buyAndReturnBillController.php", $sizeId, $colorId);
                                        } else {

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

                                            //insert in storereport
                                            insertStorereport($productId, $storeId, $finalquantity, 0, $finalquantity, 1, $buyAndReturnBill_Id, "حذف فاتورة مشتريات ومردودات", "buyAndReturnBillController.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, $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);
                                            }
                                        }
                                    }
                                }
                            }

                            //****************** Update supplier dept ************************//
                            //check if supplier deptAfter change from  supplier deptBefor
                            //if($totaldeptafter != $totaldeptbefore)
                            //{
                            $supplierData = loadSupplierDataById($supplierId);
                            $supplierDeptBeforeInMainCurr = $supplierData->suppliercurrentDebt;
                            $supplierDeptBefore = $supplierData->suppliercurrentDebtInCurrency;

                            if ($buybilltotalbill < 0) {
                                $supplierDeptAfterInMainCurr = ($supplierData->suppliercurrentDebt) + ($finalbill * (-1));
                                $supplierDeptAfter = ($supplierData->suppliercurrentDebtInCurrency) + ($buybillfinalbillC * (-1));
                                insertSupplierDebtChange($supplierId, $supplierDeptBefore, $supplierDeptBeforeInMainCurr, abs($finalbill), abs($buybillfinalbillC), 0, "حذف فاتورة مشتريات ومردودات", $buyAndReturnBill_Id, $supplierDeptAfter, $supplierDeptAfterInMainCurr, "buyAndReturnBillController.php", "حذف فاتورة مشتريات ومردودات");
                            } else {
                                $supplierDeptAfterInMainCurr = ($supplierData->suppliercurrentDebt) - $finalbill;
                                $supplierDeptAfter = ($supplierData->suppliercurrentDebtInCurrency) - $buybillfinalbillC;
                                insertSupplierDebtChange($supplierId, $supplierDeptBefore, $supplierDeptBeforeInMainCurr, abs($finalbill), abs($buybillfinalbillC), 1, "حذف فاتورة مشتريات ومردودات", $buyAndReturnBill_Id, $supplierDeptAfter, $supplierDeptAfterInMainCurr, "buyAndReturnBillController.php", "حذف فاتورة مشتريات ومردودات");
                            }

                            //update supplierdebt
                            updateSupplierDebt($supplierId, $supplierDeptAfter, $supplierDeptAfterInMainCurr);

                            //	}
                            //****************** Update save value ************************//
                            //check if payed or not to change the save value
                            //if($totalpayed > 0)
                            //{


                            if ($buybillaftertotalbill > 0) {
                                //get saveValue before and saveValue after plus totalPayed
                                ##curr conversion
                                $saveConversionFactor = 0;
                                if ($currencyId > 1) {
                                    $billCurrData = $buyAndRuternBillCurrEX->queryOneByBuybillid($buyAndReturnBill_Id);
                                    $saveConversionFactor = (float) $billCurrData->saveConversionFactor;
                                }
                                $saveData = getSaveValueAndPlus($_SESSION['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, "حذف فاتورة مشتريات ومردودات", $buyAndReturnBill_Id, $saveValueafter, "buyAndReturnBillController.php");
                                unset($_SESSION['client_id']);
                            } else {
                                //get saveValue before and saveValue after plus totalPayed
                                ##curr conversion
                                $saveConversionFactor = 0;
                                if ($currencyId > 1) {
                                    $billCurrData = $buyAndRuternBillCurrEX->queryOneByBuybillid($buyAndReturnBill_Id);
                                    $saveConversionFactor = (float) $billCurrData->saveConversionFactor;
                                }
                                $saveData = getSaveValueAndMins($_SESSION['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, 1, $saveId, "حذف فاتورة مشتريات ومردودات", $buyAndReturnBill_Id, $saveValueafter, "buyAndReturnBillController.php");
                                unset($_SESSION['client_id']);
                            }
                            //}
                        }
                    }
                }
                ########
                $billData[0] = 3; //$billType
                $billData[1] = 0; //$returnBuyBill_Id
                $billData[2] = 0; //$buyBill_Id
                $billData[3] = $buyAndReturnBill_Id; //$buyAndReturnBill_Id
                updateOverallAveragePriceOfProducts($billData);
                ########
            }
        } else {

            $operationType = $_POST['operation'];
            $smarty->assign("operationType", $operationType);

            $choosedItemArr = $_POST['choosedItem'];

            if (count($choosedItemArr) > 0) {
                $i = 1;
                foreach ($choosedItemArr as $buyAndReturnBill_Id) {
                    if ($operationType == '1') {
                        if (isset($buyAndReturnBill_Id)) {
                            $buyBillData = $buyAndReturnBillDAO->load($buyAndReturnBill_Id);
                            $billCurrData = $buyAndRuternBillCurrEX->queryOneByBuybillid($buyAndReturnBill_Id);
                            if (count($buyBillData) > 0 && $buyBillData->conditions == 0) {

                                $deleteOrNot = $buyBillData->conditions;
                                if (isset($deleteOrNot) && $deleteOrNot != 1) {
                                    $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;
                                    $payedtax = $buyBillData->payedtax;

                                    ## 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, 2);
                                    }
                                    ########################################################################

                                    $buyBill->conditions = 1;
                                    $buyBill->buybillsysdate = date("Y-m-d H:i:s");
                                    //$buyBill->userid = $_SESSION['userid'];
                                    $buyBill->userid = $buyBillData->userid;
                                    $buyBill->delbyuserid = $_SESSION['userid'];
                                    $buyBill->buybillid = $buyAndReturnBill_Id;

                                    $buyAndReturnBillExt->updateConditions($buyBill);

                                    //buybilldetails
                                    $buyBillDetailsData = $buyAndReturnBillDetailDAO->queryByBuybillid($buyAndReturnBill_Id);
                                    if (count($buyBillDetailsData) > 0) {
                                        foreach ($buyBillDetailsData as $data) {
                                            $proprice = $data->buybilldetailprice;
                                            $detailId = $data->buybilldetailid;
                                            $productId = $data->buybilldetailproductid;
                                            $billType = $data->billtype;
                                            $productunitId = $data->productunitId;

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


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

                                            $sizeId = $data->sizeid;
                                            $colorId = $data->colorid;
                                            $rowtaxval = $data->rowtaxval;

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

                                            $pronum = $data->buybilldetailquantity;
                                            $scunitname = $data->otherdetailquantity;
                                            $prototal = $data->buybilldetailtotalprice;
                                            $prodis = $data->discountvalue;
                                            $isService = isService($productId);
                                            if ($isService == 0) { //if product
                                                if (isset($productId) && $billType == 0) {
                                                    $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, $buyAndReturnBill_Id, "حذف فاتورة مشتريات ومردودات", "buyAndReturnBillController.php", $sizeId, $colorId);
                                                    } else {

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

                                                        //insert in storereport
                                                        insertStorereport($productId, $storeId, $finalquantity, 0, $finalquantity, 1, $buyAndReturnBill_Id, "حذف فاتورة مشتريات ومردودات", "buyAndReturnBillController.php", $sizeId, $colorId);
                                                    }
                                                } elseif (isset($productId) && $billType == 1) {
                                                    $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 = increaseProductQuantity($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, 0, $buyAndReturnBill_Id, "حذف فاتورة مشتريات ومردودات", "buyAndReturnBillController.php", $sizeId, $colorId);
                                                    } else {

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

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

                                        //****************** Update supplier dept ************************//
                                        //check if supplier deptAfter change from  supplier deptBefor
                                        if ($totaldeptafter != $totaldeptbefore) {
                                            $supplierData = loadSupplierDataById($supplierId);

                                            $supplierDeptBeforeInMainCurr = $supplierData->suppliercurrentDebt;
                                            $supplierDeptBefore = $supplierData->suppliercurrentDebtInCurrency;

                                            if ($buybilltotalbill < 0) {
                                                $supplierDeptAfterInMainCurr = ($supplierData->suppliercurrentDebt) + ($finalbill * (-1));
                                                $supplierDeptAfter = ($supplierData->suppliercurrentDebtInCurrency) + ($buybillfinalbillC * (-1));
                                                insertSupplierDebtChange($supplierId, $supplierDeptBefore, $supplierDeptBeforeInMainCurr, $finalbill, $buybillfinalbillC, 0, "حذف فاتورة مشتريات ومردودات", $buyAndReturnBill_Id, $supplierDeptAfter, $supplierDeptAfterInMainCurr, "buyAndReturnBillController.php", "حذف فاتورة مشتريات ومردودات");
                                            } else {
                                                $supplierDeptAfterInMainCurr = ($supplierData->suppliercurrentDebt) - $finalbill;
                                                $supplierDeptAfter = ($supplierData->suppliercurrentDebtInCurrency) - $buybillfinalbillC;
                                                insertSupplierDebtChange($supplierId, $supplierDeptBefore, $supplierDeptBeforeInMainCurr, $finalbill, $buybillfinalbillC, 1, "حذف فاتورة مشتريات ومردودات", $buyAndReturnBill_Id, $supplierDeptAfter, $supplierDeptAfterInMainCurr, "buyAndReturnBillController.php", "حذف فاتورة مشتريات ومردودات");
                                            }

                                            //update supplierdebt
                                            updateSupplierDebt($supplierId, $supplierDeptAfter, $supplierDeptAfterInMainCurr);
                                        }

                                        //****************** 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($_SESSION['saveid'], $totalpayed);
                                            $saveId = $saveData[0];
                                            $saveValuebefore = $saveData[1];
                                            $saveValueafter = $saveData[2];

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

                                            //insert into savedaily tbl from savefrom
                                            $_SESSION['client_id'] = $supplierId;
                                            insertSavedaily($saveValuebefore, $totalpayed, 1, $saveId, "حذف فاتورة مشتريات ومردودات", $buyAndReturnBill_Id, $saveValueafter, "buyAndReturnBillController.php");
                                            unset($_SESSION['client_id']);
                                        }
                                    }
                                }
                            }
                            ########
                            $billData[0] = 3; //$billType
                            $billData[1] = 0; //$returnBuyBill_Id
                            $billData[2] = 0; //$buyBill_Id
                            $billData[3] = $buyAndReturnBill_Id; //$buyAndReturnBill_Id
                            updateOverallAveragePriceOfProducts($billData);
                            ########
                        }
                    }
                    $i++;
                }
            }
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback($ex);
        echo $ex;
        die();
    }
}

function loadSupplierDataById($supplierid) {
    //to use the variable out side the funcion
    global $supplierDAO;

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

    return $supplierData;
}

////////////////////////////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) {
    global $save;
    global $saveDAO;

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

    $saveValueafter = $saveValuebefore + $savevaluechanged;

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

// get initialvalue and mins from save tbl
function getSaveValueAndMins($saveid, $savevaluechanged) {
    global $save;
    global $saveDAO;

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

    $saveValueafter = $saveValuebefore - $savevaluechanged;

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

// 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) {
    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 / $productnumber;
    lastAndMeanBuyPrice($lastBuyPriceOnePiece, $colName, $detailId, $productId, $sizeId, $colorId, $tableName, $productquantityBefore, $productquantityAfter, $productChangeAmount, $operation, $billnameId, $prototal, $rowDiscount, $billDiscountVal, $billTotalBeforeDiscount, $rowtaxval, $billPayedTaxPer, $cFactor);
    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($myStoredetail->storeid, $myStoredetail->productid, 0, 0, abs($productChangeAmount), 1);
    }

    return $productquantityAfter;
}

//update and decrease product quantity in storedetails tbl
function decreaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount, $lastBuyPrice, $productnumber, $colName, $detailId, $productId, $tableName, $operation, $billnameId, $prototal, $rowDiscount, $billDiscountVal, $billTotalBeforeDiscount, $sizeColorStoreDetailId, $sizeId, $colorId, $rowtaxval, $billPayedTaxPer, $cFactor) {
    global $storeDetail;
    global $storeDetailDAO;
    global $storeDetailExt;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    //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 / $productnumber;
    lastAndMeanBuyPrice($lastBuyPriceOnePiece, $colName, $detailId, $productId, $sizeId, $colorId, $tableName, $productquantityBefore, $productquantityAfter, $productChangeAmount, $operation, $billnameId, $prototal, $rowDiscount, $billDiscountVal, $billTotalBeforeDiscount, $rowtaxval, $billPayedTaxPer, $cFactor);
    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($myStoredetail->storeid, $myStoredetail->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");

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

    $itr = $_POST["itr"];
    $buybillid = $_POST["buybillid"];
    $countmyusedserial = $_POST["countmyusedserial"];
    print_r('countmyusedserial ' . $countmyusedserial);
    if ($countmyusedserial == 0) {
        print_r('in if ');
        $ProductserialEX->deleteBybillid($buybillid, 1);
        //print($itr."itr");
        for ($i = 1; $i <= $itr; $i++) {
            $productid = $_POST['productid' . $i . ''];
            $totalproduct = $_POST['totalproduct' . $i . ''];
            $buybilldetailid = $_POST['buybilldetailid' . $i . ''];


            //	print_r("productid=".$productid);
            //	print("<br>");
            //	print_r("totalproduct=".$totalproduct);
            //$productid=$_POST['productid'.$i.''];
            for ($x = 1; $x <= $totalproduct; $x++) {
                $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 . ''];
                //print_r("<br>fff".$serialnumber);

                $Productserial->billid = $buybillid;
                $Productserial->enddate = $enddate;
                $Productserial->productid = $productid;
                $Productserial->serialnumber = $serialnumber;
                $Productserial->startdate = $stratdate;
                $Productserial->type = 1;
                $Productserial->buybilldetailid = $buybilldetailid;
                $Productserial->don = $quantity;
                //print_r($Productserial);
                //print_r("<br>");
                if (isset($serialnumber) && $serialnumber != "" && isset($quantity) && $quantity != "") {
                    $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();
    } elseif (in_array($randomString, $serialArray)) {
        //print_r('in elseif <br>');
        getserail();
    }

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

    $serialArray[] = $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 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 insertStorereportupdate2($productid, $storeid, $productChangeAmount, $productbefore, $productafter, $storereporttype, $storereportmodelid, $processname, $tablename, $mydate, $unittype) {
    global $storeReport;
    global $storeReportExt;

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

    print_r($storeReport);

    $storeReportExt->insertEX($storeReport);
}

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

    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, $colName, $detailId);
            }
            //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; //# هذا الرقم يدل على تطبيق نسب الخصم فى فاتورة الشراء فى الداتا بيز

    print_r('billnameId' . $billnameId . '<br>');
    $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;
    }
    print_r('<br>lastBuyPriceOnePiece1' . $lastBuyPriceOnePiece);

    //# عند تطبيق تطبيق نسب الخصم
    if ($billSettingData[0]->billsettingsvalue == 0) {
        //# $prototal الاجمالى
        if ($productquantityAfter < $productquantityBefore) {// $operation == "delete")
            $Bast = ($productquantityBefore * $buyProduct->meanbuyprice ) - ($prototal + $rowDiscount - $rowtaxval);
            $billTaxShareForRow = ($prototal + $rowDiscount) * ($billPayedTaxPer / 100);
            $BastWithTax = ($productquantityBefore * $buyProduct->meanbuyprice_withTax ) - ($prototal + $rowDiscount + $billTaxShareForRow);
        } else {
            $Bast = ($productquantityBefore * $buyProduct->meanbuyprice ) + ($prototal + $rowDiscount - $rowtaxval);
            $billTaxShareForRow = ($prototal + $rowDiscount) * ($billPayedTaxPer / 100);
            $BastWithTax = ($productquantityBefore * $buyProduct->meanbuyprice_withTax ) + ($prototal + $rowDiscount + $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);
    }

    print_r('<br>lastBuyPriceOnePiece' . $lastBuyPriceOnePiece);

    $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 / ($prototal + $rowDiscount - $rowtaxval)) * 100;
    if ($productquantityAfter < $productquantityBefore) {// $operation == "delete")
        if ($operation == "add") {
            $lastBuyPriceOnePiece_withDiscount = ($prototalWithDiscount / $productChangeAmount);
        }
        $buyProduct->lastbuyprice_withDiscount = round($lastBuyPriceOnePiece_withDiscount, $noOfDecimalPlaces);
        $newWeightedDiscount = (($productquantityBefore * $buyProduct->weightedDiscount) - ($productChangeAmount * $rowDiscountPer)) / ($productquantityBefore - $productChangeAmount);
        $buyProduct->weightedDiscount = round($newWeightedDiscount, $noOfDecimalPlaces);
    } else {
        $buyProduct->lastbuyprice_withDiscount = round(($prototalWithDiscount / $productChangeAmount), $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, $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 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->insertOrUpdateMinusEX($buyPricesHistoryBook);
}

function isService($id) {

    global $myProductRecord;

    $pro = $myProductRecord->load($id);
    return $pro->isService;
}

?>