<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

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


    global $buyBillExt;
    global $returnBuyBillExt;
    global $buyAndReturnBillExt;
    global $buyBill;
    global $buyBillDAO;
    global $buyBillExt;
    global $buyBillDetail;
    global $buyBillDetailDAO;
    global $buyBillDetailExt;
    global $returnBuyBill;
    global $returnBuyBillDAO;
    global $returnBuyBillDetail;
    global $returnBuyBillDetailDAO;
    global $buyAndReturnBill;
    global $buyAndReturnBillDAO;
    global $buyAndReturnBillDetail;
    global $buyAndReturnBillDetailDAO;
    global $supplierDAO;
    global $ProgramsettingDAO;
    global $productExt;

    global $CostcenterdetailDAO;
    global $Costcenterdetail;

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

    global $accountsTreeDAO2;
    global $accountsTree2;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

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

    global $today;

    global $mySave;
    global $mySaveRecord;

    $Programsettingdata = $ProgramsettingDAO->load(1);
    $billnameId = $_POST['billnameid'];

    //settings
    $returnBillSetting = $_POST['returnBillSetting'];
    $storeSetting = $_POST['storeSetting'];
    $dateSetting = $_POST['dateSetting'];
    $noteSetting = $_POST['noteSetting'];
    $productDiscountSetting = $_POST['productDiscountSetting'];
    $Costcenterid = $_POST["Costcenter"];
    $dailyentryid = $_POST["dailyentryid"];
    $buybillsupplierid = $_POST["buybillsupplierid"];

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

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

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

    //post variables

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

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

    $totalbill = $_POST['totalbeforediscount']; //إجمالي الفاتورة
    $discount_type = $_POST['discount_type']; //نوع الخصم
    $gendis = $_POST['gendis']; //قيمة الخصم
    $aftertotalbill = $_POST['totalafterdiscount']; // المتبقى


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

    $totalpayed = $_POST['genpay']; //المدفوع
    $remin = $aftertotalbill - $totalpayed;

    $totaldeptafter = $totaldeptbefore + $remin; //$_POST['supplierdebtafter']; //إجمالي المديونية
    //print_r('totaldeptafter'.$totaldeptafter.'<br>');
    //print_r('totaldeptafter'.$totaldeptafter.'<br>');
    $tabelname = '';
    $islast = 0;
    if ($controlname == "buyBillController.php") {
        $tabelname = 'buybill';
        $xid = $buyBillExt->querylastid($tabelname);
        if ($xid->buybillid == $oldbuyid) {
            $islast = 1;
        }
    } elseif ($controlname == "buyAndReturnBillController.php") {
        $tabelname = 'buyandruternbill';
        $xid = $buyBillExt->querylastid($tabelname);
        if ($xid->buybillid == $oldbuyid) {
            $islast = 1;
        }
    }
    /* 	print_r('<br>xid'.$xid->buybillid);
      print_r('<br>oldbuyid'.$oldbuyid);
      print_r('<br>islast'.$islast); */
    $finalbill;
    if ($aftertotalbill > 0) {
        $finalbill = $aftertotalbill - $totalpayed; // المتبقي
    } else {
        $finalbill = $aftertotalbill + $totalpayed; // المتبقي
    }

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


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

    $buyBillFlag = 0;
    $returnBuyBillFlag = 0;

    for ($i = 1; $i <= $buyItr; $i++) {
        $productIdxxx = $_POST['product' . $i];
        $proprice = $_POST['proprice' . $i];
        if ($productIdxxx > 0) {
            $buyBillFlag += 1;
        }
    }

    for ($i = 1; $i <= $returnBuyItr; $i++) {
        $productIdxxx = $_POST['product_re' . $i];
        $proprice = $_POST['proprice_re' . $i];
        if ($productIdxxx > 0) {
            $returnBuyBillFlag += 1;
        }
    }

    //($controlname,$oldbuyid,$norbuyBillTotal,$norbuyBillTotal_re)
    if ($norbuyBillTotal_re > 0 && $norbuyBillTotal > 0) {
        if (!empty($buyItr) && $buyItr != 0 && $buyBillFlag != 0 && !empty($returnBuyItr) && $returnBuyItr != 0 && $returnBuyBillFlag != 0) {


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


                $buyAndReturnBill_Id = $buyAndReturnBillExt->insertEX($buyAndReturnBill);


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

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



                for ($j = 1; $j <= $buyItr; $j++) {
                    $parcode = $_POST['parcode' . $j];
                    $productId = $_POST['product' . $j];
                    $unitId = $_POST['unitId' . $j];
                    $proprice = $_POST['proprice' . $j];
                    $pronum = $_POST['pronum' . $j];
                    $prototal = $_POST['hidden_prototal' . $j];
                    $note = $_POST['note' . $j];
                    $prodis = $_POST['prodis' . $j];
                    $scunitname = $_POST['scunitname' . $j];


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


                        if (!empty($buyAndReturnBill_Id)) {
                            $buyAndReturnBillDetail->billtype = 0;
                            $buyAndReturnBillDetail->buybilldetailcatid = $catId;
                            $buyAndReturnBillDetail->buybilldetaildate = $today;
                            $buyAndReturnBillDetail->buybillid = $buyAndReturnBill_Id;
                            $buyAndReturnBillDetail->buybilldetailprice = $proprice;
                            $buyAndReturnBillDetail->buybilldetailquantity = $pronum;
                            $buyAndReturnBillDetail->buybilldetailproductid = $productId;
                            $buyAndReturnBillDetail->buybilldetailtotalprice = $prototal;
                            $buyAndReturnBillDetail->discountvalue = $prodis;
                            $buyAndReturnBillDetail->note = $note;
                            $buyAndReturnBillDetail->parcode = $parcode;
                            $buyAndReturnBillDetail->productunitid = $unitId;
                            $buyAndReturnBillDetail->otherdetailquantity = $scunitname;

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


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

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

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

                        if (count($allStoredetailData) > 0) {
                            //update productquantity in storedetail
                            $productQuantityAfter = increaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity, $proprice, "buybilldetailid", $detailId, $productId, "buyandruternbilldetail", $billnameId, $prototal);

                            //insert in storereport
                            insertStorereportupdate($productId, $storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 0, $buyAndReturnBill_Id, "اضافة فاتورة مشتريات", "buyAndReturnBillController.php", $buybillDate);
                        } else {
                            //insert in storedetail tbl
                            insertStoredetailupdate($storeId, $productId, $finalquantity, $buybillDate);

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


                        $allStoredetailData2 = getStoreDetails($storeId, $productId, 1);
                        $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
                            print_r('in else');
                            insertStoredetailupdate2($storeId, $productId, $scunitname, $buybillDate, 1);

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

                for ($y = 1; $y <= $returnBuyItr; $y++) {
                    $parcode = $_POST['parcode_re' . $y];
                    $productId = $_POST['product_re' . $y];
                    $unitId = $_POST['unitId_re' . $y];
                    $proprice = $_POST['proprice_re' . $y];
                    $pronum = $_POST['pronum_re' . $y];
                    $prototal = $_POST['hidden_prototal_re' . $y];
                    $note = $_POST['note_re' . $y];
                    $prodis = $_POST['prodis_re' . $y];
                    $scunitname = $_POST['scunitname_re' . $y];


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

                        if (!empty($buyAndReturnBill_Id)) {
                            $buyAndReturnBillDetail->billtype = 1;
                            $buyAndReturnBillDetail->buybilldetailcatid = $catId;
                            $buyAndReturnBillDetail->buybilldetaildate = $today;
                            $buyAndReturnBillDetail->buybillid = $buyAndReturnBill_Id;
                            $buyAndReturnBillDetail->buybilldetailprice = $proprice;
                            $buyAndReturnBillDetail->buybilldetailquantity = $pronum;
                            $buyAndReturnBillDetail->buybilldetailproductid = $productId;
                            $buyAndReturnBillDetail->buybilldetailtotalprice = $prototal;
                            $buyAndReturnBillDetail->discountvalue = $prodis;
                            $buyAndReturnBillDetail->productunitid = $unitId;
                            $buyAndReturnBillDetail->note = $note;
                            $buyAndReturnBillDetail->parcode = $parcode;
                            $buyAndReturnBillDetail->otherdetailquantity = $scunitname;


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

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

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


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

                        if (count($allStoredetailData) > 0) {

                            $productQuantityAfter = decreaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity, $proprice, "buybilldetailid", $detailId, $productId, "buyandruternbilldetail", $billnameId, $prototal);

                            //insert in storereport
                            insertStorereportupdate($productId, $storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 1, $buyAndReturnBill_Id, "اضافة فاتورة مردودات مشتريات", "buyAndReturnBillController.php", $buybillDate);
                        } else {
                            //insert in storedetail tbl
                            insertStoredetailupdate($storeId, $productId, $finalquantity, $buybillDate);

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

                        $allStoredetailData2 = getStoreDetails($storeId, $productId, 1);
                        $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
                            print_r('in else');
                            insertStoredetailupdate2($storeId, $productId, ($scunitname) * -1, $buybillDate, 1);

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

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

                insertSupplierDebtChangeupdate($supplierId, $totaldeptbefore, $finalbill, 0, "اضافة فاتورة مشتريات ومردودات مشتريات", $buyAndReturnBill_Id, $totaldeptafter, "buyAndReturnBillController.php", "اضافة فاتورة مشتريات ومردودات مشتريات", $buybillDate);
                //}
                //****************** Update save value ************************//
                //check if payed or not to change the save value
                //if($totalpayed > 0)
                //{
                if ($aftertotalbill > 0) {
                    //get saveValue before and saveValue after minus totalPayed
                    $saveData = getSaveValueAndMins($_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
                    insertSavedailyupdate($saveValuebefore, $totalpayed, 1, $saveId, "اضافة فاتورة مشتريات ومردودات مشتريات", $buyAndReturnBill_Id, $saveValueafter, "buyAndReturnBillController.php", $buybillDate);
                } else {
                    //get saveValue before and saveValue after plus totalPayed
                    $saveData = getSaveValueAndPlus($_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
                    insertSavedailyupdate($saveValuebefore, $totalpayed, 0, $saveId, "اضافة فاتورة مشتريات ومردودات مشتريات", $buyAndReturnBill_Id, $saveValueafter, "buyAndReturnBillController.php", $buybillDate);
                }

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


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


        if ($buyItr == 0 || $buyBillFlag == 0) { //return buy bill only
            $billType = 1;

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


                $returnBuyBill->deletedbuyid = $oldbuyid;
                $returnBuyBill->controlname = $controlname;
                $returnBuyBill->costcenterid = $Costcenterid;

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

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


                //   print_r($returnBuyBill);
                for ($j = 1; $j <= $returnBuyItr; $j++) {
                    $parcode = $_POST['parcode_re' . $j];
                    $productId = $_POST['product_re' . $j];
                    $unitId = $_POST['unitId_re' . $j];
                    $proprice = $_POST['proprice_re' . $j];
                    $pronum = $_POST['pronum_re' . $j];
                    $prototal = $_POST['hidden_prototal_re' . $j];
                    $note = $_POST['note_re' . $j];
                    $prodis = $_POST['prodis_re' . $j];
                    $scunitname = $_POST['scunitname_re' . $j];


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

                        if (!empty($returnBuyBill_Id)) {
                            $returnBuyBillDetail->discountvalue = $prodis;
                            $returnBuyBillDetail->note = $note;
                            $returnBuyBillDetail->parcode = $parcode;
                            $returnBuyBillDetail->returnbuybilldetailcatid = $catId;
                            $returnBuyBillDetail->returnbuybilldetailprice = $proprice;
                            $returnBuyBillDetail->returnbuybilldetailproductid = $productId;
                            $returnBuyBillDetail->returnbuybilldetailquantity = $pronum;
                            $returnBuyBillDetail->returnbuybilldetailtotalprice = $prototal;
                            $returnBuyBillDetail->returnbuybillid = $returnBuyBill_Id;
                            $returnBuyBillDetail->productunitid = $unitId;
                            $returnBuyBillDetail->otherdetailquantity = $scunitname;

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


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

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


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

                        if (count($allStoredetailData) > 0) {
                            //update productquantity in storedetail
                            print_r('<pre>');
                            print_r('2222222222222222222222');
                            print_r('<pre>');
                            $productQuantityAfter = decreaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity, $proprice, "returnbuybilldetailid", $detailId, $productId, "returnbuybilldetail", $billnameId, $prototal);

                            //insert in storereport
                            insertStorereportupdate($productId, $storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 1, $returnBuyBill_Id, "اضافة فاتورة مردودات مشتريات", "returnBuyBillController.php", $buybillDate);
                        } else {
                            //insert in storedetail tbl
                            insertStoredetailupdate($storeId, $productId, $finalquantity, $buybillDate);

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




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



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

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

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

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

                insertSupplierDebtChangeupdate($supplierId, $totaldeptbefore, $finalbill, 1, "اضافة فاتورة مردوات مشتريات", $returnBuyBill_Id, $totaldeptafter, "returnBuyBillController.php", "اضافة فاتورة مردوات مشتريات", $buybillDate);
                //}
                //****************** Update save value ************************//
                //check if payed or not to change the save value
                //if($totalpayed > 0)
                //{
                //print($totalpayed);
                $totalpayed = $totalpayed * (-1);
                //get saveValue before and saveValue after plus totalPayed
                $saveData = getSaveValueAndPlus($_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
                insertSavedailyupdate($saveValuebefore, $totalpayed, 0, $saveId, "اضافة فاتورة مردوات مشتريات", $returnBuyBill_Id, $saveValueafter, "returnBuyBillController.php", $buybillDate);

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


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

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


                $buyBill->deletedbuyid = $oldbuyid;
                $buyBill->controlname = $controlname;
                $buyBill->costcenterid = $Costcenterid;


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

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

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

                for ($j = 1; $j <= $buyItr; $j++) {
                    $parcode = $_POST['parcode' . $j];
                    $productId = $_POST['product' . $j];
                    $unitId = $_POST['unitId' . $j];
                    $proprice = $_POST['proprice' . $j];
                    $pronum = $_POST['pronum' . $j];
                    $prototal = $_POST['hidden_prototal' . $j];
                    $note = $_POST['note' . $j];
                    $prodis = $_POST['prodis' . $j];
                    $scunitname = $_POST['scunitname' . $j];


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


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


                        if (!empty($buyBill_Id)) {
                            $buyBillDetail->discountvalue = $prodis;
                            $buyBillDetail->note = $note;
                            $buyBillDetail->parcode = $parcode;
                            $buyBillDetail->buybilldetailcatid = $catId;
                            $buyBillDetail->buybilldetailprice = $proprice;
                            $buyBillDetail->buybilldetailproductid = $productId;
                            $buyBillDetail->buybilldetailquantity = $pronum;
                            $buyBillDetail->buybilldetailtotalprice = $prototal;
                            $buyBillDetail->buybillid = $buyBill_Id;
                            $buyBillDetail->buybilldetaildate = $today;
                            $buyBillDetail->productunitid = $unitId;
                            $buyBillDetail->otherdetailquantity = $scunitname;

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



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


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

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

                        //print_r($allStoredetailData);

                        if (count($allStoredetailData) > 0) {
                            //update productquantity in storedetail
                            $productQuantityAfter = increaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity, $proprice, "buybilldetailid", $detailId, $productId, "buybilldetail", $billnameId, $prototal);

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

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

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



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



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

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

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

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

                insertSupplierDebtChange($supplierId, $totaldeptbefore, $finalbill, 0, "اضافة فاتورة مشتريات", $buyBill_Id, $totaldeptafter, "buyBillController.php", "اضافة فاتورة مشتريات");
                //}
                //****************** Update save value ************************//
                //check if payed or not to change the save value
                if ($totalpayed > 0) {
                    //get saveValue before and saveValue after plus totalPayed
                    $saveData = getSaveValueAndMins($_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
                    insertSavedailyupdate($saveValuebefore, $totalpayed, 1, $saveId, "اضافة فاتورة مشتريات", $buyBill_Id, $saveValueafter, "buyBillController.php", $buybillDate);
                }
            } catch (Exception $e) {
                header("location:?do=error");
                //echo $e;
            }
        }
    }
    if (isset($returnBuyBill_Id)) {

        if ($aftertotalbill != 0 && $totalpayed == 0) {
            reverseEntryWithItsID($returndailyEntryId);


            $dailyEntry->entryComment = 'تم اضافة فاتوره مردودات مشتريات ( اجل )';


// start من حساب الدائنون (اسم المورد )

            $dailyEntryDebtorArray = array();

            $dailyEntryDebtor->value = $aftertotalbill * -1;


            $oldSupplier = $supplierDAO->load($supplierId);
            $treeId = $oldSupplier->treeId;


            $dailyEntryDebtor->accountstreeid = $treeId;

            ///الي حساب مردودات المشتريات
            $dailyEntryCreditorArray = array();

            $dailyEntryCreditor->value = $aftertotalbill * -1;

            $dailyEntryCreditor->accountstreeid = 17;


            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

// load daily entry id and insert it

            $returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);

            $dailyId = $returnDailyId[1];


            $rowData = $returnBuyBillDAO->load($returnBuyBill_Id);

            $returnBuyBill->billnameid = $rowData->billnameid;
            $returnBuyBill->conditions = $rowData->conditions;
            $returnBuyBill->returnbuybillaftertotalbill = $rowData->returnbuybillaftertotalbill;
            $returnBuyBill->returnbuybilldate = $rowData->returnbuybilldate;
            $returnBuyBill->returnbuybilldirectpayment = $rowData->returnbuybilldirectpayment;
            $returnBuyBill->returnbuybilldiscountrype = $rowData->returnbuybilldiscountrype;
            $returnBuyBill->returnbuybilldiscount = $rowData->returnbuybilldiscount;
            $returnBuyBill->returnbuybillfinalbill = $rowData->returnbuybillfinalbill;
            $returnBuyBill->returnbuybillsaveid = $rowData->returnbuybillsaveid;
            $returnBuyBill->returnbuybillSerial = $rowData->returnbuybillSerial;
            $returnBuyBill->returnbuybillstoreid = $rowData->returnbuybillstoreid;
            $returnBuyBill->returnbuybillsupplierid = $rowData->returnbuybillsupplierid;
            $returnBuyBill->returnbuybillsysdate = $rowData->returnbuybillsysdate;
            $returnBuyBill->returnbuybilltotalbill = $rowData->returnbuybilltotalbill;
            $returnBuyBill->returnbuybilltotaldeptafter = $rowData->returnbuybilltotaldeptafter;
            $returnBuyBill->returnbuybilltotaldeptbefor = $rowData->returnbuybilltotaldeptbefor;
            $returnBuyBill->returnbuybilltotalpayed = $rowData->returnbuybilltotalpayed;
            $returnBuyBill->payedtax = $rowData->payedtax;
            $returnBuyBill->userid = $rowData->userid;
            $returnBuyBill->costcenterid = $rowData->costcenterid;
            $returnBuyBill->dailyentryid = $dailyId;
            $returnBuyBillDAO->update($returnBuyBill);
        } elseif ($totalpayed * -1 == $aftertotalbill * -1) {

            reverseEntryWithItsID($returndailyEntryId);

            $dailyEntry->entryComment = 'تم اضافة فاتوره مردودات مشتريات ( كاش )';

            // start الخزنة

            $dailyEntryDebtorArray = array();

            $dailyEntryDebtor->value = $aftertotalbill * -1;
//save session
            $saveid = $_SESSION['saveid'];
            $dataSave = $mySaveRecord->load($saveid);

            $idTreeSave = $dataSave->treeId;
            $dailyEntryDebtor->accountstreeid = $idTreeSave;
// start الخزنة
            ///الي حساب مردودات المشتريات
            $dailyEntryCreditorArray = array();

            $dailyEntryCreditor->value = $aftertotalbill * -1;

            $dailyEntryCreditor->accountstreeid = 17;


            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

// load daily entry id and insert it

            $returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);

            $dailyId = $returnDailyId[1];



            $rowData = $returnBuyBillDAO->load($returnBuyBill_Id);

            $returnBuyBill->billnameid = $rowData->billnameid;
            $returnBuyBill->conditions = $rowData->conditions;
            $returnBuyBill->returnbuybillaftertotalbill = $rowData->returnbuybillaftertotalbill;
            $returnBuyBill->returnbuybilldate = $rowData->returnbuybilldate;
            $returnBuyBill->returnbuybilldirectpayment = $rowData->returnbuybilldirectpayment;
            $returnBuyBill->returnbuybilldiscountrype = $rowData->returnbuybilldiscountrype;
            $returnBuyBill->returnbuybilldiscount = $rowData->returnbuybilldiscount;
            $returnBuyBill->returnbuybillfinalbill = $rowData->returnbuybillfinalbill;
            $returnBuyBill->returnbuybillsaveid = $rowData->returnbuybillsaveid;
            $returnBuyBill->returnbuybillSerial = $rowData->returnbuybillSerial;
            $returnBuyBill->returnbuybillstoreid = $rowData->returnbuybillstoreid;
            $returnBuyBill->returnbuybillsupplierid = $rowData->returnbuybillsupplierid;
            $returnBuyBill->returnbuybillsysdate = $rowData->returnbuybillsysdate;
            $returnBuyBill->returnbuybilltotalbill = $rowData->returnbuybilltotalbill;
            $returnBuyBill->returnbuybilltotaldeptafter = $rowData->returnbuybilltotaldeptafter;
            $returnBuyBill->returnbuybilltotaldeptbefor = $rowData->returnbuybilltotaldeptbefor;
            $returnBuyBill->returnbuybilltotalpayed = $rowData->returnbuybilltotalpayed;
            $returnBuyBill->payedtax = $rowData->payedtax;
            $returnBuyBill->userid = $rowData->userid;
            $returnBuyBill->costcenterid = $rowData->costcenterid;
            $returnBuyBill->dailyentryid = $dailyId;
            $returnBuyBillDAO->update($returnBuyBill);
        } elseif ($totalpayed < $aftertotalbill * -1 && $totalpayed != 0) {

            reverseEntryWithItsID($returndailyEntryId);

            $total = ($aftertotalbill * -1) - ($totalpayed * -1);


            $dailyEntry->entryComment = 'تم اضافة فاتوره مردودات مشتريات ( اجل وكاش )';

            // start الخزنة

            $dailyEntryDebtorArray = array();

            $dailyEntryDebtor->value = ($totalpayed * -1);
//save session
            $saveid = $_SESSION['saveid'];
            $dataSave = $mySaveRecord->load($saveid);

            $idTreeSave = $dataSave->treeId;
            $dailyEntryDebtor->accountstreeid = $idTreeSave;
// start الخزنة
            // start من حساب الدائنون (اسم المورد )


            $dailyEntryDebtor2->value = $total;


            $oldSupplier = $supplierDAO->load($supplierId);
            $treeId = $oldSupplier->treeId;


            $dailyEntryDebtor2->accountstreeid = $treeId;

            ///الي حساب مردودات المشتريات
            $dailyEntryCreditorArray = array();

            $dailyEntryCreditor->value = $aftertotalbill * -1;

            $dailyEntryCreditor->accountstreeid = 17;



            array_push($dailyEntryDebtorArray, $dailyEntryDebtor, $dailyEntryDebtor2);
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

// load daily entry id and insert it

            $returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);

            $dailyId = $returnDailyId[1];


            $rowData = $returnBuyBillDAO->load($returnBuyBill_Id);

            $returnBuyBill->billnameid = $rowData->billnameid;
            $returnBuyBill->conditions = $rowData->conditions;
            $returnBuyBill->returnbuybillaftertotalbill = $rowData->returnbuybillaftertotalbill;
            $returnBuyBill->returnbuybilldate = $rowData->returnbuybilldate;
            $returnBuyBill->returnbuybilldirectpayment = $rowData->returnbuybilldirectpayment;
            $returnBuyBill->returnbuybilldiscountrype = $rowData->returnbuybilldiscountrype;
            $returnBuyBill->returnbuybilldiscount = $rowData->returnbuybilldiscount;
            $returnBuyBill->returnbuybillfinalbill = $rowData->returnbuybillfinalbill;
            $returnBuyBill->returnbuybillsaveid = $rowData->returnbuybillsaveid;
            $returnBuyBill->returnbuybillSerial = $rowData->returnbuybillSerial;
            $returnBuyBill->returnbuybillstoreid = $rowData->returnbuybillstoreid;
            $returnBuyBill->returnbuybillsupplierid = $rowData->returnbuybillsupplierid;
            $returnBuyBill->returnbuybillsysdate = $rowData->returnbuybillsysdate;
            $returnBuyBill->returnbuybilltotalbill = $rowData->returnbuybilltotalbill;
            $returnBuyBill->returnbuybilltotaldeptafter = $rowData->returnbuybilltotaldeptafter;
            $returnBuyBill->returnbuybilltotaldeptbefor = $rowData->returnbuybilltotaldeptbefor;
            $returnBuyBill->returnbuybilltotalpayed = $rowData->returnbuybilltotalpayed;
            $returnBuyBill->payedtax = $rowData->payedtax;
            $returnBuyBill->userid = $rowData->userid;
            $returnBuyBill->costcenterid = $rowData->costcenterid;
            $returnBuyBill->dailyentryid = $dailyId;
            $returnBuyBillDAO->update($returnBuyBill);
        }
    } else {


        if ($aftertotalbill == 0) {

            reverseEntryWithItsID($dailyentryid);
        } elseif ($aftertotalbill != 0 && $totalpayed == 0) {

            reverseEntryWithItsID($dailyentryid);

            //   print_r('old d id' . $dailyentryid);
            $dailyEntry->dComment = 'فاتوره مردودات مشتريات ' . $totalpayed;


            // start ألمشتريات
            $dailyEntryDebtorArray = array();

            $dailyEntryDebtor->value = $aftertotalbill;

            $dailyEntryDebtor->accountstreeid = 12;

            /// end ألمشتريات


            $dailyEntryCreditorArray = array();

            $dailyEntryCreditor->value = $aftertotalbill;


            $oldSupplier = $supplierDAO->load($supplierId);
            $treeId = $oldSupplier->treeId;


            $dailyEntryCreditor->accountstreeid = $treeId;
            // start المورد


            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

//        print_r('<pre>');
//        print_r($dailyEntryDebtorArray);
//        print_r($dailyentryid);
//
//        print_r('</pre>');
//
//
//        print_r('<pre>');
//        print_r($dailyEntryCreditorArray);
//        print_r($dailyentryid);
//
//        print_r('</pre>');


            $returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);

            $dailyId = $returnDailyId[1];


            $rowData = $buyBillDAO->load($buyBill_Id);

//        print_r('<pre>aaaaaaaaaaaaaaaaaa');
//        print_r($dailyId);
//        print_r('<pre>');

            $buyBill->billnameid = $rowData->billnameid;
            $buyBill->conditions = $rowData->conditions;
            $buyBill->buybillaftertotalbill = $rowData->buybillaftertotalbill;
            $buyBill->buybilldate = $rowData->buybilldate;
            $buyBill->buybilldirectpayment = $rowData->buybilldirectpayment;
            $buyBill->buybilldiscountrype = $rowData->buybilldiscountrype;
            $buyBill->buybilldiscount = $rowData->buybilldiscount;
            $buyBill->buybillfinalbill = $rowData->buybillfinalbill;
            $buyBill->buybillsaveid = $rowData->buybillsaveid;
            $buyBill->buybillSerial = $rowData->buybillSerial;
            $buyBill->buybillstoreid = $rowData->buybillstoreid;
            $buyBill->buybillsupplierid = $rowData->buybillsupplierid;
            $buyBill->buybillsysdate = $rowData->buybillsysdate;
            $buyBill->buybilltotalbill = $rowData->buybilltotalbill;
            $buyBill->buybilltotaldeptafter = $rowData->buybilltotaldeptafter;
            $buyBill->buybilltotaldeptbefor = $rowData->buybilltotaldeptbefor;
            $buyBill->buybilltotalpayed = $rowData->buybilltotalpayed;
            $buyBill->userid = $rowData->userid;
            $buyBill->payedtax = $rowData->payedtax;
            $buyBill->costcenterid = $rowData->costcenterid;
            $buyBill->dailyentryid = $dailyId;

//        print_r('<pre>aaaaaaaaaaaaaaaaaa');
//        print_r($buyBill->dailyentryid);
//        print_r('<pre>');
            $buyBillDAO->update($buyBill);
        } elseif ($totalpayed == $aftertotalbill) {

///////// قيد اليومية للمشتريات
// فى حالة  المتبقى  يساوى صفر


            reverseEntryWithItsID($dailyentryid);

            $dailyEntry->dComment = 'فاتوره مردودات مشتريات ' . $totalpayed;


// start ألمشتريات
            $dailyEntryDebtorArray = array();

            $dailyEntryDebtor->value = $aftertotalbill;

            $dailyEntryDebtor->accountstreeid = 12;

/// end ألمشتريات
// start الخزنة

            $dailyEntryCreditorArray2 = array();

            $dailyEntryCreditor2->value = $aftertotalbill;
//save session
            $saveid = $_SESSION['saveid'];
            $dataSave = $mySaveRecord->load($saveid);

            $idTreeSave = $dataSave->treeId;
            $dailyEntryCreditor2->accountstreeid = $idTreeSave;
// start الخزنة


            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            array_push($dailyEntryCreditorArray2, $dailyEntryCreditor2);
//        print_r('<pre>$totalpayed == $aftertotalbill');
//        print_r($dailyEntryDebtor);
//        print_r('<pre>');
            $returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray2);

            $dailyId = $returnDailyId[1];


            $rowData = $buyBillDAO->load($buyBill_Id);

//        print_r('<pre>aaaaaaaaaaaaaaaaaa');
//        print_r($dailyId);
//        print_r('<pre>');

            $buyBill->billnameid = $rowData->billnameid;
            $buyBill->conditions = $rowData->conditions;
            $buyBill->buybillaftertotalbill = $rowData->buybillaftertotalbill;
            $buyBill->buybilldate = $rowData->buybilldate;
            $buyBill->buybilldirectpayment = $rowData->buybilldirectpayment;
            $buyBill->buybilldiscountrype = $rowData->buybilldiscountrype;
            $buyBill->buybilldiscount = $rowData->buybilldiscount;
            $buyBill->buybillfinalbill = $rowData->buybillfinalbill;
            $buyBill->buybillsaveid = $rowData->buybillsaveid;
            $buyBill->buybillSerial = $rowData->buybillSerial;
            $buyBill->buybillstoreid = $rowData->buybillstoreid;
            $buyBill->buybillsupplierid = $rowData->buybillsupplierid;
            $buyBill->buybillsysdate = $rowData->buybillsysdate;
            $buyBill->buybilltotalbill = $rowData->buybilltotalbill;
            $buyBill->buybilltotaldeptafter = $rowData->buybilltotaldeptafter;
            $buyBill->buybilltotaldeptbefor = $rowData->buybilltotaldeptbefor;
            $buyBill->buybilltotalpayed = $rowData->buybilltotalpayed;
            $buyBill->userid = $rowData->userid;
            $buyBill->payedtax = $rowData->payedtax;
            $buyBill->costcenterid = $rowData->costcenterid;
            $buyBill->dailyentryid = $dailyId;

//        print_r('<pre>aaaaaaaaaaaaaaaaaa');
//        print_r($buyBill->dailyentryid);
//        print_r('<pre>');
            $buyBillDAO->update($buyBill);
///////// قيد اليومية للمشتريات
        } elseif ($totalpayed < $aftertotalbill) {
///////// قيد اليومية للمشتريات

            reverseEntryWithItsID($dailyentryid);

            //  print_r($totalpayed . 'المدفوع');
            $total = $aftertotalbill - $totalpayed;
            //     print_r($total . 'المتبقى');


            $dailyEntry->dComment = 'فاتوره مردودات مشتريات ' . $totalpayed;


// start ألمشتريات
            $dailyEntryDebtorArray = array();

            $dailyEntryDebtor->value = $aftertotalbill;

            $dailyEntryDebtor->accountstreeid = 12;

/// end ألمشتريات
// start المورد

            $dailyEntryCreditorArray = array();

            $dailyEntryCreditor->value = $total;


            $oldSupplier = $supplierDAO->load($supplierId);
            $treeId = $oldSupplier->treeId;


            $dailyEntryCreditor->accountstreeid = $treeId;
// start المورد
// start الخزنة



            $dailyEntryCreditor2->value = $totalpayed;
//save session
            $saveid = $_SESSION['saveid'];
            $dataSave = $mySaveRecord->load($saveid);

            $idTreeSave = $dataSave->treeId;
            $dailyEntryCreditor2->accountstreeid = $idTreeSave;
// start الخزنة

            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

            array_push($dailyEntryCreditorArray, $dailyEntryCreditor, $dailyEntryCreditor2);
//print_r($dailyEntryCreditorArray);

            $returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);


            $dailyId = $returnDailyId[1];


            $rowData = $buyBillDAO->load($buyBill_Id);

//        print_r('<pre>');
//        print_r($returnDailyId);
//        print_r('<pre>');


            $buyBill->billnameid = $rowData->billnameid;
            $buyBill->conditions = $rowData->conditions;
            $buyBill->buybillaftertotalbill = $rowData->buybillaftertotalbill;
            $buyBill->buybilldate = $rowData->buybilldate;
            $buyBill->buybilldirectpayment = $rowData->buybilldirectpayment;
            $buyBill->buybilldiscountrype = $rowData->buybilldiscountrype;
            $buyBill->buybilldiscount = $rowData->buybilldiscount;
            $buyBill->buybillfinalbill = $rowData->buybillfinalbill;
            $buyBill->buybillsaveid = $rowData->buybillsaveid;
            $buyBill->buybillSerial = $rowData->buybillSerial;
            $buyBill->buybillstoreid = $rowData->buybillstoreid;
            $buyBill->buybillsupplierid = $rowData->buybillsupplierid;
            $buyBill->buybillsysdate = $rowData->buybillsysdate;
            $buyBill->buybilltotalbill = $rowData->buybilltotalbill;
            $buyBill->buybilltotaldeptafter = $rowData->buybilltotaldeptafter;
            $buyBill->buybilltotaldeptbefor = $rowData->buybilltotaldeptbefor;
            $buyBill->buybilltotalpayed = $rowData->buybilltotalpayed;
            $buyBill->userid = $rowData->userid;
            $buyBill->payedtax = $rowData->payedtax;
            $buyBill->costcenterid = $rowData->costcenterid;
            $buyBill->dailyentryid = $dailyId;

//        print_r('<pre>aaaaaaaaaaaaaaaaaa');
//        print_r($buyBill->dailyentryid);
//        print_r('<pre>');
            $buyBillDAO->update($buyBill);
        }
    }
    return array($billType, $returnBuyBill_Id, $buyBill_Id, $buyAndReturnBill_Id);
}
