HEX
Server: Apache
System: Linux server1.royalgt4.com 4.18.0-553.89.1.lve.el8.x86_64 #1 SMP Wed Dec 10 13:58:50 UTC 2025 x86_64
User: mostafedeg (1125)
PHP: 5.6.40
Disabled: mail,passthru,parse_ini_file,show_source,eval,assert,pcntl_exec,dl,putenv,proc_open,popen
Upload Files
File: /home/mostafedeg/public_html/erp/controllers/api_olddddddddddd.php
<?php

session_start();
global $showoutside;

$_SESSION['dbname'] = $_POST['db'];
$_SESSION['userid'] = $_POST['userid'];
$_SESSION['usergroupid'] = 1;
$_SESSION['username'] = 1;
$_SESSION['usergroupname'] = 1;
$_SESSION['saveid'] = $_POST['saveid'];
$_SESSION['employeename'] = 1;
$_SESSION['searchinonesave'] = 1;
$_SESSION['branchId'] = 1;

//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");
//Sellbill
require_once('../models/dao/SellbillDAO.class.php');
require_once('../models/dto/Sellbill.class.php');
require_once('../models/mysql/SellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillMySqlExtDAO.class.php');
//Sellbilldetail
require_once('../models/dao/SellbilldetailDAO.class.php');
require_once('../models/dto/Sellbilldetail.class.php');
require_once('../models/mysql/SellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbilldetailMySqlExtDAO.class.php');
//Returnsellbill
require_once('../models/dao/ReturnsellbillDAO.class.php');
require_once('../models/dto/Returnsellbill.class.php');
require_once('../models/mysql/ReturnsellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbillMySqlExtDAO.class.php');
//Returnsellbilldetail
require_once('../models/dao/ReturnsellbilldetailDAO.class.php');
require_once('../models/dto/Returnsellbilldetail.class.php');
require_once('../models/mysql/ReturnsellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbilldetailMySqlExtDAO.class.php');
//Sellbillandrutern
require_once('../models/dao/SellbillandruternDAO.class.php');
require_once('../models/dto/Sellbillandrutern.class.php');
require_once('../models/mysql/SellbillandruternMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillandruternMySqlExtDAO.class.php');
//Sellandruternbilldetail
require_once('../models/dao/SellandruternbilldetailDAO.class.php');
require_once('../models/dto/Sellandruternbilldetail.class.php');
require_once('../models/mysql/SellandruternbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SellandruternbilldetailMySqlExtDAO.class.php');
//Storereport
require_once('../models/dao/StorereportDAO.class.php');
require_once('../models/dto/Storereport.class.php');
require_once('../models/mysql/StorereportMySqlDAO.class.php');
require_once('../models/mysql/ext/StorereportMySqlExtDAO.class.php');
//Storedetail
require_once('../models/dao/StoredetailDAO.class.php');
require_once('../models/dto/Storedetail.class.php');
require_once('../models/mysql/StoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/StoredetailMySqlExtDAO.class.php');
//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');
//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');
//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');
//Client
require_once('../models/dao/ClientDAO.class.php');
require_once('../models/dto/Client.class.php');
require_once('../models/mysql/ClientMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientMySqlExtDAO.class.php');
//Clientdebtchange
require_once('../models/dao/ClientdebtchangeDAO.class.php');
require_once('../models/dto/Clientdebtchange.class.php');
require_once('../models/mysql/ClientdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientdebtchangeMySqlExtDAO.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');
//User
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.class.php');
//Productunit
require_once('../models/dao/ProductunitDAO.class.php');
require_once('../models/dto/Productunit.class.php');
require_once('../models/mysql/ProductunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductunitMySqlExtDAO.class.php');
//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');
//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');
//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');
//Soldserialproduct
require_once('../models/dao/SoldserialproductDAO.class.php');
require_once('../models/dto/Soldserialproduct.class.php');
require_once('../models/mysql/SoldserialproductMySqlDAO.class.php');
require_once('../models/mysql/ext/SoldserialproductMySqlExtDAO.class.php');

//user
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.class.php');

//Usergroup
require_once('../models/dao/UsergroupDAO.class.php');
require_once('../models/dto/Usergroup.class.php');
require_once('../models/mysql/UsergroupMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupMySqlExtDAO.class.php');

//Sellbilldetailorder
require_once('../models/dao/SellbilldetailorderDAO.class.php');
require_once('../models/dto/Sellbilldetailorder.class.php');
require_once('../models/mysql/SellbilldetailorderMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbilldetailorderMySqlExtDAO.class.php');

//Sellbillorder
require_once('../models/dao/SellbillorderDAO.class.php');
require_once('../models/dto/Sellbillorder.class.php');
require_once('../models/mysql/SellbillorderMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillorderMySqlExtDAO.class.php');

//Temsellbill
require_once('../models/dao/TemsellbillDAO.class.php');
require_once('../models/dto/Temsellbill.class.php');
require_once('../models/mysql/TemsellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/TemsellbillMySqlExtDAO.class.php');
//Temsellbilldetail
require_once('../models/dao/TemsellbilldetailDAO.class.php');
require_once('../models/dto/Temsellbilldetail.class.php');
require_once('../models/mysql/TemsellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/TemsellbilldetailMySqlExtDAO.class.php');

//Temreturnsellbill
require_once('../models/dao/TemreturnsellbillDAO.class.php');
require_once('../models/dto/Temreturnsellbill.class.php');
require_once('../models/mysql/TemreturnsellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/TemreturnsellbillMySqlExtDAO.class.php');
//Temreturnsellbilldetail
require_once('../models/dao/TemreturnsellbilldetailDAO.class.php');
require_once('../models/dto/Temreturnsellbilldetail.class.php');
require_once('../models/mysql/TemreturnsellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/TemreturnsellbilldetailMySqlExtDAO.class.php');

//Temsellbillandrutern
require_once('../models/dao/TemsellbillandruternDAO.class.php');
require_once('../models/dto/Temsellbillandrutern.class.php');
require_once('../models/mysql/TemsellbillandruternMySqlDAO.class.php');
require_once('../models/mysql/ext/TemsellbillandruternMySqlExtDAO.class.php');
//Temsellandruternbilldetail
require_once('../models/dao/TemsellandruternbilldetailDAO.class.php');
require_once('../models/dto/Temsellandruternbilldetail.class.php');
require_once('../models/mysql/TemsellandruternbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/TemsellandruternbilldetailMySqlExtDAO.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');


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

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

  Controller Name :- sellbillController

  OPERTATION in Controller

  1-display add form
  2- add in sellbill, sellbilldetail, sellbillandrutern, sellandruternbilldetail, returnsellbill, returnsellbilldetail tbl
  3- display sucess or error

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

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

//here the global templates
//$smarty->display("headbeil.html");
//here goes the instances and general variables
//Sellbilldetailorder
$Sellbilldetailorder = new Sellbilldetailorder();
$SellbilldetailorderDAO = new SellbilldetailorderMySqlDAO();
$SellbilldetailorderEX = new SellbilldetailorderMySqlExtDAO();

//Sellbillorder
$Sellbillorder = new Sellbillorder();
$SellbillorderDAO = new SellbillorderMySqlDAO();
$SellbillorderEX = new SellbillorderMySqlExtDAO();
//Sellbill
$mySellbill = new Sellbill();
$mySellbillRecord = new SellbillMySqlDAO();
$mySellbillEx = new SellbillMySqlExtDAO();
//Sellbilldetail
$mySellbilldetail = new Sellbilldetail();
$mySellbilldetailRecord = new SellbilldetailMySqlDAO();
$mySellbilldetailEx = new SellbilldetailMySqlExtDAO();
//Returnsellbill
$myReturnsellbill = new Returnsellbill();
$myReturnsellbillRecord = new ReturnsellbillMySqlDAO();
$myReturnsellbillEx = new ReturnsellbillMySqlExtDAO();


//Returnsellbilldetail
$myReturnsellbilldetail = new Returnsellbilldetail();
$myReturnsellbilldetailRecord = new ReturnsellbilldetailMySqlDAO();
$myReturnsellbilldetailEx = new ReturnsellbilldetailMySqlExtDAO();


//Sellbillandrutern
$mySellbillandrutern = new Sellbillandrutern();
$mySellbillandruternRecord = new SellbillandruternMySqlDAO();
$mySellbillandruternEx = new SellbillandruternMySqlExtDAO();
//Sellandruternbilldetail
$mySellandruternbilldetail = new Sellandruternbilldetail();
$mySellandruternbilldetailRecord = new SellandruternbilldetailMySqlDAO();
$mySellandruternbilldetailEx = new SellandruternbilldetailMySqlExtDAO();
//Storereport
$myStorereport = new Storereport();
$myStorereportRecord = new StorereportMySqlDAO();
$myStorereportEx = new StorereportMySqlExtDAO();
//Storedetail
$myStoredetailEx = new StoredetailMySqlExtDAO();
$myStoredetailRecord = new StoredetailMySqlDAO();
//Store
$myStoreRecord = new StoreMySqlDAO();
//Product
$myProductRecord = new ProductMySqlDAO();
$myProductEx = new ProductMySqlExtDAO();
//save
$mySave = new Save();
$mySaveRecord = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();
//savedaily
$mySavedaily = new Savedaily();
$mySavedailyRecord = new SavedailyMySqlDAO();
$mySavedailyEx = new SavedailyMySqlExtDAO();
//Client
$myClientRecord = new ClientMySqlDAO();
$myClient = new Client();
$myClientEx = new ClientMySqlExtDAO();
//Clientdebtchange
$myClientdebtchange = new Clientdebtchange();
$myClientdebtchangeRecord = new ClientdebtchangeMySqlDAO();
//Billname
$myBillnameRecord = new BillnameMySqlDAO();
$myBillnameEx = new BillnameMySqlExtDAO();
//Billsetting
$myBillsettingEx = new BillsettingsMySqlExtDAO();
//User
$myUserEx = new UserMySqlExtDAO();

//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();
//$Productunit= new Productunit();
//$ProductunitDAO= new ProductunitDAO();
//Productcat
$myProductcatRecord = new ProductcatMySqlDAO();
$myProductcatEx = new ProductcatMySqlExtDAO();
//Unit
$myUnitRecord = new UnitMySqlDAO();
//Productserial
$myProductserial = new Productserial();
$myProductserialEx = new ProductserialMySqlExtDAO();
//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$programSettingExt = new ProgramsettingsMySqlExtDAO();
//Soldserialproduct
$soldSerialProduct = new Soldserialproduct();
$soldSerialProductDAO = new SoldserialproductMySqlDAO();
$soldSerialProductExt = new SoldserialproductMySqlExtDAO();

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

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

//Temsellbill
$Temsellbill = new Temsellbill();
$TemsellbillDAO = new TemsellbillMySqlDAO();
$TemsellbillEX = new TemsellbillMySqlExtDAO();
//Temsellbilldetail
$Temsellbilldetail = new Temsellbilldetail();
$TemsellbilldetailDAO = new TemsellbilldetailMySqlDAO();
$TemsellbilldetailEX = new TemsellbilldetailMySqlExtDAO();

//Temreturnsellbill
$Temreturnsellbill = new Temreturnsellbill();
$TemreturnsellbillDAO = new TemreturnsellbillMySqlDAO();
$TemreturnsellbillEX = new TemreturnsellbillMySqlExtDAO();
//Temreturnsellbilldetail
$Temreturnsellbilldetail = new Temreturnsellbilldetail();
$TemreturnsellbilldetailDAO = new TemreturnsellbilldetailMySqlDAO();
$TemreturnsellbilldetailEX = new TemreturnsellbilldetailMySqlExtDAO();

//Temsellbillandrutern
$Temsellbillandrutern = new Temsellbillandrutern();
$TemsellbillandruternDAO = new TemsellbillandruternMySqlDAO();
$TemsellbillandruternEX = new TemsellbillandruternMySqlExtDAO();
//Temsellandruternbilldetail
$Temsellandruternbilldetail = new Temsellandruternbilldetail();
$TemsellandruternbilldetailDAO = new TemsellandruternbilldetailMySqlDAO();
$TemsellandruternbilldetailEX = new TemsellandruternbilldetailMySqlExtDAO();


require_once('../models/dao/ClientareaDAO.class.php');
require_once('../models/dto/Clientarea.class.php');
require_once('../models/mysql/ClientareaMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientareaMySqlExtDAO.class.php');

$Clientarea = new Clientarea();
$ClientareaDAO = new ClientareaMySqlDAO();
$ClientareaEX = new ClientareaMySqlExtDAO();


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

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





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


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

include_once("selllfunction.php");




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

$ordertype = $_POST["ordertype"];
$url = "";

$addData = add();
//  print_r($addData);
$sellbillId = $addData[0];
if ($sellbillId > 0) {

    echo "1";
}
$returnsellbillId = $addData[1];
$productsBeforeValid = $addData[2];
$saveValuebeforeValid = $addData[3];
$billtype = $addData[4];

// add in sellbill tbl
function add() {
    //
    //  echo "add works";
    //e cho $_POST['hidden_debt'];
    global $mySellbill;
    global $mySellbillRecord;
    global $mySellbilldetail;
    global $mySellbilldetailRecord;

    global $myReturnsellbill;
    global $myReturnsellbillRecord;
    global $myReturnsellbilldetail;
    global $myReturnsellbilldetailRecord;


    global $mySellbillandrutern;
    global $mySellbillandruternRecord;
    global $mySellandruternbilldetail;
    global $mySellandruternbilldetailRecord;


    //Temsellbill
    global $Temsellbill;
    global $TemsellbillDAO;
    //Temsellbilldetail
    global $Temsellbilldetail;
    global $TemsellbilldetailDAO;

    //Temreturnsellbill
    global $Temreturnsellbill;
    global $TemreturnsellbillDAO;
    //Temreturnsellbilldetail
    global $Temreturnsellbilldetail;
    global $TemreturnsellbilldetailDAO;

    //Temsellbillandrutern
    global $Temsellbillandrutern;
    global $TemsellbillandruternDAO;
    //Temsellandruternbilldetail
    global $Temsellandruternbilldetail;
    global $TemsellandruternbilldetailDAO;



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

    global $CostcenterdetailDAO;
    global $Costcenterdetail;


    global $soldSerialProduct;
    global $soldSerialProductDAO;

    global $ProductunitDAO;
    global $Productunit;
    global $myProductunitEx;

    global $myClientRecord;
    $billnameId = $_POST['billnameid'];

    $settingReturn = $_POST['settingreturn'];
    $settingClient = $_POST['settingclient'];
    $settingStore = $_POST['settingstore'];
    $settingSeller = $_POST['settingseller'];
    $settingParcode = $_POST['settingparcode'];
    $settingDate = $_POST['settingdate'];
    $settingNewproduct = $_POST['settingnewproduct'];
    $settingComment = $_POST['settingcomment'];
    $settingDiscount = $_POST['settingdiscount'];
    $settingQuantityCondition = $_POST['settingquantitycondition'];

    $tempClientName = $_POST['tempclientName'];

    $sellbillclientId = $_POST['supplier'];
    $sellbilltotaldeptBefor = $_POST['hidden_debt'];
    $sellbilltotaldeptAfter = $_POST['clientdebtafter'];
    $tax = $_POST["tax"];

    $sellbillcarnumber = $_POST['carNumber'];
    $sellbillcartype = $_POST['carType'];
    $sellbillcarchase = $_POST['carChase'];
    $sellbillcarmotor = $_POST['carMotor'];

    $Costcenterid = $_POST["Costcenter"];

    $clientName = loadClientNameById($sellbillclientId);

    $sellbildirectPayment;
    //client
    if ($settingClient == 0 && $_POST['supplier'] != 1) {
        $sellbildirectPayment = 1;
    } else {
        $sellbildirectPayment = 0;
    }

    //Date
    if ($settingDate == 0) {
        $sellbillDate = $_POST['bn'];
    } else {
        $sellbillDate = date("Y-m-d h:m:s");
    }

    //Store
    if ($settingStore == 0) {
        $sellbillstoreId = $_POST['storeid'];
    } else {
        $sellbillstoreId = $_POST['storeid'];
    }

    //seller
    if ($settingSeller == 0) {
        $sellerId = $_POST['sellerid'];
        if ($sellerId == "-1" || $sellerId == "" || $sellerId == NULL) {
            $sellerId = 0;
        }
    } else {
        $sellerId = 0;
    }

    $sellbillSerial = $_POST['bns'];
    $priceType = $_POST['hiddenpricetype'];

    $sellbilltotalBill = $_POST['sellbilltotalbill']; //اجمالى الفاتورة قبل الخصم
    $sellbillDiscountType = $_POST['distype']; //نوع الخصم

    $sellbillDiscount = $_POST['gendis']; //قيمة الخصم
    $sellbillAftertotalBill = $_POST['sellbillaftertotalbill']; //القيمة بعد الخصم
    $sellbilltotalPayed = $_POST['genpay']; //المدفوع
    $sellbillFinalbill = $sellbillAftertotalBill - $sellbilltotalPayed; //المتبقى

    $sellbillPrice = $_POST['sellbillprice']; //اجمالى المبيعات
    $returnsellbillPrice = $_POST['returnsellbillprice']; //اجمالى مردودات المبيعات

    $sellQuantity = $_POST['sellQuantity'];
    $returnsellQuantity = $_POST['returnsellQuantity'];

    $clientdata = $myClientRecord->load($sellbillclientId);

    $sellbilltotaldeptBefor = $clientdata->clientdebt; //$_POST['hidden_debt'];
    $gen4totalinput = $_POST["gen4totalinput"];

    if ($sellbillclientId == 1) {
        $sellbilltotaldeptAfter = $sellbilltotaldeptBefor + $gen4totalinput; //$_POST['clientdebtafter'];
    } else {

        $sellbilltotaldeptAfter = $sellbilltotaldeptBefor + $gen4totalinput; //$sellbillFinalbill;
    }




    //////////////////////////////////////////////////////////////////////////

    $sellbillItr = $_POST['hidden_itr'];
    $returnSellbillItr = $_POST['returnhidden_itr'];

    $productsBeforeValid = 1;
    $saveValuebeforeValid = 1;
    /* ----------------------------- */
    $sellbillId;
    $returnsellbillId;
    $billtype;
    /* ------------------------ */

    if ($billnameId != 11) {
        //check storerdetail value
        //check product quantity
        if ($sellbillPrice > 0) {
            $h = 1;
            for ($h = 1; $h <= $sellbillItr; $h++) {
                $productId = $_POST['product' . $h . ''];
                $productQuantity = $_POST['pronum' . $h . ''];

                if (isset($productId) && $productId != '-1' && $productId != "") {
                    //get storefrom productquantity before change
                    $storedetailData = getStoredetailData($sellbillstoreId, $productId);

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

                    //check if productquantityFromBefore greater than 0 or not
                    $productsBeforeValid = 1;
                    if ($productquantityBefore > 0 && count($allStoredetailData) > 0) {
                        $productsAfterValid = $productquantityBefore - $productQuantity;

                        if ($productsAfterValid >= 0) {
                            $productsBeforeValid = 1;
                        } else {
                            $productsBeforeValid = 0;
                            //return $productsBeforeValid;
                        }
                    } else {
                        $productsBeforeValid = 0;
                        //return $productsBeforeValid;
                    }
                }
            }
        }




        /////////////////check savefrom value before transfer//////////////////////

        if ($returnsellbillPrice > 0 && ($sellbillPrice <= 0 || $sellbillAftertotalBill)) {
            $saveValueafterValid;

            //get save value
            $saveValueBefore = getSaveValueBefore($_SESSION['saveid']);

            $saveValueafterValid = $saveValueBefore - $sellbilltotalPayed;

            if ($saveValueafterValid >= 0) {
                $saveValuebeforeValid = 1;
            } else {
                $saveValuebeforeValid = 0;
                //return $saveValuebeforeValid;
            }
        }


        $billtype;
        // مبيعات و ومردودات
        //insert data into Sellbillandrutern tbl
        if ($sellbillPrice > 0 && $returnsellbillPrice > 0) {


            $billtype = 3; // مبيعات و ومردودات

            $mySellbillandrutern->billnameid = $billnameId;
            $mySellbillandrutern->conditions = 0;
            $mySellbillandrutern->sellbildirectpayment = $sellbildirectPayment;
            $mySellbillandrutern->sellbillaftertotalbill = $sellbillAftertotalBill;
            $mySellbillandrutern->sellbillclientid = $sellbillclientId;
            $mySellbillandrutern->sellbillclientname = $clientName;
            $mySellbillandrutern->sellbilldate = $sellbillDate;
            $mySellbillandrutern->sellbilldiscount = $sellbillDiscount;
            $mySellbillandrutern->sellbilldiscounttype = $sellbillDiscountType;
            $mySellbillandrutern->tempclientName = $tempClientName;
            $mySellbillandrutern->sellQuantity = $sellQuantity;
            $mySellbillandrutern->returnsellQuantity = $returnsellQuantity;
            $mySellbillandrutern->tax = $tax;


            if ($sellbilltotalBill < 0) {
                $sellbillFinalbill = $sellbillAftertotalBill + $sellbilltotalPayed;
            }
            $mySellbillandrutern->sellbillfinalbill = $sellbillFinalbill;
            $mySellbillandrutern->sellbillsaveid = $_SESSION['saveid'];
            $mySellbillandrutern->sellbillserial = $sellbillSerial;
            $mySellbillandrutern->sellbillstoreid = $sellbillstoreId;
            $mySellbillandrutern->sellbillsysdate = date("Y-m-d H:i:s");
            $mySellbillandrutern->sellbilltotalbill = $sellbilltotalBill;
            $mySellbillandrutern->sellbilltotaldeptafter = $sellbilltotaldeptAfter;
            $mySellbillandrutern->sellbilltotaldeptbefor = $sellbilltotaldeptBefor;
            $mySellbillandrutern->sellbilltotalpayed = $sellbilltotalPayed;
            $mySellbillandrutern->sellerid = $sellerId;
            $mySellbillandrutern->userid = $_SESSION['userid'];
            $mySellbillandrutern->sellbillprice = $sellbillPrice;
            $mySellbillandrutern->returnsellbillprice = $returnsellbillPrice;
            $mySellbillandrutern->carnumber = $sellbillcarnumber;
            $mySellbillandrutern->cartype = $sellbillcartype;
            $mySellbillandrutern->carchase = $sellbillcarchase;
            $mySellbillandrutern->carmotor = $sellbillcarmotor;
            $mySellbillandrutern->costcenterid = $Costcenterid;






            $sellbillId = $mySellbillandruternRecord->insert($mySellbillandrutern);

            $Costcenterdetail->costamount = $sellbillAftertotalBill;
            $Costcenterdetail->costcenterid = $Costcenterid;
            $Costcenterdetail->costdate = date('Y-m-d');
            $Costcenterdetail->del = 0;
            $Costcenterdetail->modelid = $sellbillId;
            $Costcenterdetail->processname = 'فاتوره مبيعات ومردودات';
            $Costcenterdetail->tablename = 'sellbillandruternController.php';
            $Costcenterdetail->type = 2;
            $Costcenterdetail->uesrid = $_SESSION['userid'];

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



            //insert Sell Data into Sellandruternbilldetail tbl
            $sellbillItr = $_POST['hidden_itr'];
            $h = 1;
            for ($h = 1; $h <= $sellbillItr; $h++) {
                $parcode = $_POST['parcode' . $h . ''];
                $parcodeType = $_POST['parcodeType' . $h . ''];
                $productserailId = $_POST['productserailid' . $h . ''];
                $productId = $_POST['product' . $h . ''];
                $productunitId = $_POST['productunit' . $h . ''];
                $quantity = $_POST['pronum' . $h . ''];
                $price = $_POST['proprice' . $h . ''];
                $discountValue = $_POST['prodis' . $h . ''];
                $discounttype = $_POST['discounttype' . $h . ''];
                $totalPrice = $_POST['hidden_prototal' . $h . ''];
                $comment = $_POST['comment' . $h . ''];
                $prstorid = $_POST['prstorid' . $h . ''];

                if (isset($prstorid) && $prstorid != -1 && $prstorid != '') {

                    $sellbillstoreId = $prstorid;
                } else {
                    $sellbillstoreId = $_POST['storeid'];
                    //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                }

                if ($productunitId == "") {
                    $productunitId = 0;
                }


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


                    $productData = loadProductById($productId);


                    $mySellandruternbilldetail->buyprice = $productData->productBuyPrice;
                    $mySellandruternbilldetail->discountvalue = $discountValue;
                    $mySellandruternbilldetail->note = $comment;
                    $mySellandruternbilldetail->parcode = $parcode;
                    $mySellandruternbilldetail->pricetype = $priceType;
                    $mySellandruternbilldetail->productunitid = $productunitId;
                    $mySellandruternbilldetail->sellbilldetailcatid = $productData->productCatId;
                    $mySellandruternbilldetail->sellbilldetaildate = date("Y-m-d h:m:s");
                    $mySellandruternbilldetail->sellbilldetailprice = $price;
                    $mySellandruternbilldetail->sellbilldetailproductid = $productId;
                    $mySellandruternbilldetail->sellbilldetailquantity = $quantity;
                    $mySellandruternbilldetail->sellbilldetailtotalprice = $totalPrice;
                    $mySellandruternbilldetail->sellbillid = $sellbillId;
                    $mySellandruternbilldetail->selltype = 0; //مبيعات
                    $mySellandruternbilldetail->buydiscount = $productData->buydiscount;
                    $mySellandruternbilldetail->buydiscounttype = $productData->discounttype;
                    $mySellandruternbilldetail->storeid = $sellbillstoreId;
                    $mySellandruternbilldetail->discounttype = $discounttype;



                    $mySellandruternbilldetailRecord->insert($mySellandruternbilldetail);


                    $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                    $productnumber = $productunitData->productnumber;
                    $finalquantity = $quantity * $productnumber;
                    //update DON if is Serial
                    if ($parcodeType == "serialnumber") {
                        //update don column (quantity) in productserial table
                        updateSerailQty($productserailId, $finalquantity);
                        insertIntoSoldSerialProduct($productserailId, $finalquantity, $sellbillId, 1);
                    }



                    //get store productquantity before change
                    $storedetailData = getStoredetailData($sellbillstoreId, $productId);

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



                    if (count($allStoredetailData) > 0) {

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


                        //insert in storereport
                        insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillandruternController.php", $sellbillDate);
                    } else {
                        $specialQuantityAfter = $finalquantity * -1;

                        //insert in storedetail tbl
                        insertStoredetailupdate($sellbillstoreId, $productId, $specialQuantityAfter, $sellbillDate);

                        //insert in storereport
                        insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $specialQuantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillandruternController.php", $sellbillDate);
                    }
                }
            }



            //insert Return Data into Sellandruternbilldetail tbl
            $returnSellbillItr = $_POST['returnhidden_itr'];
            $h = 1;
            for ($h = 1; $h <= $returnSellbillItr; $h++) {
                $parcode = $_POST['returnparcode' . $h . ''];
                $parcodeType = $_POST['returnparcodeType' . $h . ''];
                $productserailId = $_POST['returnproductserailid' . $h . ''];
                $productId = $_POST['returnproduct' . $h . ''];
                $productunitId = $_POST['returnproductunit' . $h . ''];
                $quantity = $_POST['returnpronum' . $h . ''];
                $price = $_POST['returnproprice' . $h . ''];
                $discountValue = $_POST['returnprodis' . $h . ''];
                $totalPrice = $_POST['returnhidden_prototal' . $h . ''];
                $comment = $_POST['returncomment' . $h . ''];
                $returndiscounttype = $_POST['returndiscounttype' . $h . ''];


                if (isset($reprstorid) && $reprstorid != -1 && $reprstorid != '') {

                    $sellbillstoreId = $reprstorid;
                } else {
                    $sellbillstoreId = $_POST['storeid'];
                    //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                }
                if ($productunitId == "") {
                    $productunitId = 0;
                }

                if (isset($productId) && $productId != '-1' && $productId != "") {
                    $productData = loadProductById($productId);


                    $mySellandruternbilldetail->buyprice = $productData->productBuyPrice;
                    $mySellandruternbilldetail->discountvalue = $discountValue;
                    $mySellandruternbilldetail->note = $comment;
                    $mySellandruternbilldetail->parcode = $parcode;
                    $mySellandruternbilldetail->pricetype = $priceType;
                    $mySellandruternbilldetail->productunitid = $productunitId;
                    $mySellandruternbilldetail->sellbilldetailcatid = $productData->productCatId;
                    $mySellandruternbilldetail->sellbilldetaildate = date("Y-m-d h:m:s");
                    $mySellandruternbilldetail->sellbilldetailprice = $price;
                    $mySellandruternbilldetail->sellbilldetailproductid = $productId;
                    $mySellandruternbilldetail->sellbilldetailquantity = $quantity;
                    $mySellandruternbilldetail->sellbilldetailtotalprice = $totalPrice;
                    $mySellandruternbilldetail->sellbillid = $sellbillId;
                    $mySellandruternbilldetail->selltype = 1; //مردودات
                    $mySellandruternbilldetail->buydiscount = $productData->buydiscount;
                    $mySellandruternbilldetail->buydiscounttype = $productData->discounttype;
                    $mySellandruternbilldetail->storeid = $sellbillstoreId;
                    $mySellandruternbilldetail->discounttype = $returndiscounttype;

                    $mySellandruternbilldetailRecord->insert($mySellandruternbilldetail);

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

                    //update DON if is Serial
                    if ($parcodeType == "serialnumber") {
                        //update don column (quantity) in productserial table
                        updateSerailQty_ForReturn($productserailId, $finalquantity);
                    }


                    //get storeto productquantity before change
                    $storedetailData = getStoredetailData($sellbillstoreId, $productId);

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

                    if (count($allStoredetailData) > 0) {

                        //update productquantity in storedetail
                        $productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity);


                        //insert in storereport
                        insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $sellbillId, "اضافة فاتورة مردودات مبيعات", "sellbillandruternController.php", $sellbillDate);
                    } else {
                        //insert in storedetail tbl
                        insertStoredetailupdate($sellbillstoreId, $productId, $finalquantity, $sellbillDate);


                        //insert in storereport
                        insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $sellbillId, "اضافة فاتورة مردودات مبيعات", "sellbillandruternController.php", $sellbillDate);
                    }
                }
            }



            if ($sellbillclientId != 0) {
                //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
                {

                    //update rawmaterialssupplierdebt
                    updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                    if ($sellbilltotalBill < 0) {
                        $sellbillFinalbill = $sellbillFinalbill * -1;
                        insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 1, "اضافة فاتورة مبيعات ومردودات", $sellbillId, $sellbilltotaldeptAfter, "sellbillandruternController.php", "اضافة فاتورة مبيعات ومردودات", $sellbillAftertotalBill, $sellbillDate);
                    } else {
                        insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 0, "اضافة فاتورة مبيعات ومردودات", $sellbillId, $sellbilltotaldeptAfter, "sellbillandruternController.php", "اضافة فاتورة مبيعات ومردودات", $sellbillAftertotalBill, $sellbillDate);
                    }
                }
            }


            //check if payed or not to change save value

            if ($sellbilltotalPayed > 0) {
                if ($sellbillAftertotalBill > 0) {

                    //get saveValue before and saveValue after Plus lPayed
                    $saveData = getSaveValueAndPlus($_SESSION['saveid'], $sellbilltotalPayed);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];

                    //update save value after add sellbill
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from save
                    insertSavedailyupdate($saveValuebefore, $sellbilltotalPayed, 0, $saveId, "اضافة فاتورة مبيعات ومردودات", $sellbillId, $saveValueafter, "sellbillandruternController.php", date("Y-m-d H:i:s"));
                } else {
                    //get saveValue before and saveValue after Plus lPayed
                    $saveData = getSaveValueAndMins($_SESSION['saveid'], $sellbilltotalPayed);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];

                    //update save value after add sellbill
                    updateSave($saveId, $saveValueafter);

                    $specialSellbilltotalPayed = $sellbilltotalPayed * -1;

                    //insert into savedaily tbl from save
                    insertSavedailyupdate($saveValuebefore, $specialSellbilltotalPayed, 1, $saveId, "اضافة فاتورة مبيعات ومردودات", $sellbillId, $saveValueafter, "sellbillandruternController.php", date("Y-m-d H:i:s"));
                }
            }
        }






        //مبيعات
        //insert data into Sellbill tbl
        elseif ($sellbillPrice > 0 && $returnsellbillPrice <= 0) {
            $billtype = 1; //مبيعات


            $mySellbill->billnameid = $billnameId;
            $mySellbill->conditions = 0;
            $mySellbill->sellbildirectpayment = $sellbildirectPayment;
            $mySellbill->sellbillaftertotalbill = $sellbillAftertotalBill;
            $mySellbill->sellbillclientid = $sellbillclientId;
            $mySellbill->sellbillclientname = $clientName;
            $mySellbill->sellbilldate = $sellbillDate;
            $mySellbill->sellbilldiscount = $sellbillDiscount;
            $mySellbill->sellbilldiscounttype = $sellbillDiscountType;
            $mySellbill->sellbillfinalbill = $sellbillFinalbill;
            $mySellbill->sellbillsaveid = $_SESSION['saveid'];
            $mySellbill->sellbillserial = $sellbillSerial;
            $mySellbill->sellbillstoreid = $sellbillstoreId;
            $mySellbill->sellbillsysdate = date("Y-m-d H:i:s");
            $mySellbill->sellbilltotalbill = $sellbilltotalBill;
            $mySellbill->sellbilltotaldeptafter = $sellbilltotaldeptAfter;
            $mySellbill->sellbilltotaldeptbefor = $sellbilltotaldeptBefor;
            $mySellbill->sellbilltotalpayed = $sellbilltotalPayed;
            $mySellbill->sellerid = $sellerId;
            $mySellbill->userid = $_SESSION['userid'];
            $mySellbill->tempclientName = $tempClientName;
            $mySellbill->sellQuantity = $sellQuantity;
            $mySellbill->tax = $tax;
            $mySellbill->carnumber = $sellbillcarnumber;
            $mySellbill->cartype = $sellbillcartype;
            $mySellbill->carchase = $sellbillcarchase;
            $mySellbill->carmotor = $sellbillcarmotor;
            $mySellbill->costcenterid = $Costcenterid;

            $sellbillId = $mySellbillRecord->insert($mySellbill);

            $Costcenterdetail->costamount = $sellbillAftertotalBill;
            $Costcenterdetail->costcenterid = $Costcenterid;
            $Costcenterdetail->costdate = date('Y-m-d');
            $Costcenterdetail->del = 0;
            $Costcenterdetail->modelid = $sellbillId;
            $Costcenterdetail->processname = 'فاتوره مبيعات';
            $Costcenterdetail->tablename = 'sellbillController.php';
            $Costcenterdetail->type = '0';
            $Costcenterdetail->uesrid = $_SESSION['userid'];

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




            //insert Sell Data into Sellbilldetail tbl
            $sellbillItr = $_POST['hidden_itr'];
            $h = 1;
            for ($h = 1; $h <= $sellbillItr; $h++) {
                $parcode = $_POST['parcode' . $h . ''];
                $parcodeType = $_POST['parcodeType' . $h . ''];
                $productserailId = $_POST['productserailid' . $h . ''];
                $productId = $_POST['product' . $h . ''];
                $productunitId = $_POST['productunit' . $h . ''];
                $quantity = $_POST['pronum' . $h . ''];
                $price = $_POST['proprice' . $h . ''];
                $discountValue = $_POST['prodis' . $h . ''];
                $totalPrice = $_POST['hidden_prototal' . $h . ''];
                $comment = $_POST['comment' . $h . ''];
                $prstorid = $_POST['prstorid' . $h . ''];
                $discounttype = $_POST['discounttype' . $h . ''];




                if (isset($prstorid) && $prstorid != -1 && $prstorid != '') {

                    //print_r('in if prstorid'.$prstorid.'<br>');

                    $sellbillstoreId = $prstorid;
                } else {
                    $sellbillstoreId = $_POST['storeid'];
                    //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                }
                if ($productunitId == "") {
                    $productunitId = 0;
                }
                //print_r('the final'.$sellbillstoreId.'<br>');

                if (isset($productId) && $productId != '-1' && $productId != "") {
                    $productData = loadProductById($productId);


                    $mySellbilldetail->buyprice = $productData->productBuyPrice;
                    $mySellbilldetail->discountvalue = $discountValue;
                    $mySellbilldetail->note = $comment;
                    $mySellbilldetail->parcode = $parcode;
                    $mySellbilldetail->pricetype = $priceType;
                    $mySellbilldetail->productunitid = $productunitId;
                    $mySellbilldetail->sellbilldetailcatid = $productData->productCatId;
                    $mySellbilldetail->sellbilldetaildate = date("Y-m-d h:m:s");
                    $mySellbilldetail->sellbilldetailprice = $price;
                    $mySellbilldetail->sellbilldetailproductid = $productId;
                    $mySellbilldetail->sellbilldetailquantity = $quantity;
                    $mySellbilldetail->sellbilldetailtotalprice = $totalPrice;
                    $mySellbilldetail->sellbillid = $sellbillId;
                    $mySellbilldetail->buydiscount = $productData->buydiscount;
                    $mySellbilldetail->buydiscounttype = $productData->discounttype;
                    $mySellbilldetail->storeid = $sellbillstoreId;
                    $mySellbilldetail->discounttype = $discounttype;

                    $mySellbilldetailRecord->insert($mySellbilldetail);
                    //print("qty: ".$quantity.'<br>');
                    //print("<br>productserailId: ".$productserailId);
                    //update DON if is Serial

                    $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                    //print_r($productunitData);
                    $productnumber = $productunitData->productnumber;
                    $finalquantity = $quantity * $productnumber;
                    /* 	print("productnumber: ".$productnumber.'<br>');
                      print("quantity: ".$quantity.'<br>');
                      print("finalquantity: ".$finalquantity.'<br>'); */
                    if ($parcodeType == "serialnumber") {
                        //print("<br>serialnumber<br>");
                        //updateSerailDon($productserailId, 1, $sellbillId);
                        updateSerailQty($productserailId, $finalquantity);
                        insertIntoSoldSerialProduct($productserailId, $finalquantity, $sellbillId, 0);
                    }



                    //get store productquantity before change
                    $storedetailData = getStoredetailData($sellbillstoreId, $productId);

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

                    //print("qty: ".$finalquantity.'<br>');
                    if (count($allStoredetailData) > 0) {

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

                        //print("productquantityAfter: ".$productquantityAfter.'<br>');
                        //insert in storereport
                        insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", $sellbillDate);
                    } else {
                        $specialQuantityAfter = $finalquantity * -1;

                        //insert in storedetail tbl
                        insertStoredetailupdate($sellbillstoreId, $productId, $specialQuantityAfter, $sellbillDate);

                        //insert in storereport
                        insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $specialQuantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات", "sellbillController.php", $sellbillDate);
                    }
                }
            }

            if ($sellbillclientId != 0) {
                //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
                {

                    //update rawmaterialssupplierdebt
                    updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                    insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 0, "اضافة فاتورة مبيعات", $sellbillId, $sellbilltotaldeptAfter, "sellbillController.php", "اضافة فاتورة مبيعات", $sellbillAftertotalBill, $sellbillDate);
                }
            }


            //check if payed or not to change save value

            if ($sellbilltotalPayed > 0) {
                //get saveValue before and saveValue after Plus lPayed
                $saveData = getSaveValueAndPlus($_SESSION['saveid'], $sellbilltotalPayed);
                $saveId = $saveData[0];
                $saveValuebefore = $saveData[1];
                $saveValueafter = $saveData[2];

                //update save value after add sellbill
                updateSave($saveId, $saveValueafter);

                //insert into savedaily tbl from save
                insertSavedailyupdate($saveValuebefore, $sellbilltotalPayed, 0, $saveId, "اضافة فاتورة مبيعات", $sellbillId, $saveValueafter, "sellbillController.php", date("Y-m-d H:i:s"));
            }
        }




        //مردودات مبيعات
        //insert data into returnSellbill tbl
        elseif ($sellbillPrice <= 0 && $returnsellbillPrice > 0) {
            $billtype = 2; //مردودات مبيعات



            $myReturnsellbill->billnameid = $billnameId;
            $myReturnsellbill->conditions = 0;
            $myReturnsellbill->returnsellbildirectpayment = $sellbildirectPayment;
            $myReturnsellbill->returnsellbillaftertotalbill = $sellbillAftertotalBill * -1;
            $myReturnsellbill->returnsellbillclientid = $sellbillclientId;
            $myReturnsellbill->returnsellbillclientname = $clientName;
            $myReturnsellbill->returnsellbilldate = $sellbillDate;
            $myReturnsellbill->returnsellbilldiscount = $sellbillDiscount;
            $myReturnsellbill->returnsellbilldiscounttype = $sellbillDiscountType;

            $sellbillFinalbill = ($sellbillAftertotalBill * -1) - $sellbilltotalPayed;
            $myReturnsellbill->returnsellbillfinalbill = $sellbillFinalbill;
            $myReturnsellbill->returnsellbillsaveid = $_SESSION['saveid'];
            $myReturnsellbill->returnsellbillserial = $sellbillSerial;
            $myReturnsellbill->returnsellbillstoreid = $sellbillstoreId;
            $myReturnsellbill->returnsellbillsysdate = date("Y-m-d h:m:s");
            $myReturnsellbill->returnsellbilltotalbill = $sellbilltotalBill * -1;
            $myReturnsellbill->returnsellbilltotaldeptafter = $sellbilltotaldeptAfter;
            $myReturnsellbill->returnsellbilltotaldeptbefor = $sellbilltotaldeptBefor;
            $myReturnsellbill->returnsellbilltotalpayed = $sellbilltotalPayed;
            $myReturnsellbill->sellerid = $sellerId;
            $myReturnsellbill->userid = $_SESSION['userid'];
            $myReturnsellbill->tempclientName = $tempClientName;
            $myReturnsellbill->returnsellQuantity = $returnsellQuantity;
            $myReturnsellbill->tax = $tax;
            $myReturnsellbill->carnumber = $sellbillcarnumber;
            $myReturnsellbill->cartype = $sellbillcartype;
            $myReturnsellbill->carchase = $sellbillcarchase;
            $myReturnsellbill->carmotor = $sellbillcarmotor;
            $myReturnsellbill->costcenterid = $Costcenterid;



            $returnsellbillId = $myReturnsellbillRecord->insert($myReturnsellbill);

            $Costcenterdetail->costamount = $sellbillAftertotalBill;
            $Costcenterdetail->costcenterid = $Costcenterid;
            $Costcenterdetail->costdate = date('Y-m-d');
            $Costcenterdetail->del = 0;
            $Costcenterdetail->modelid = $returnsellbillId;
            $Costcenterdetail->processname = 'فاتوره مردودات مبيعات';
            $Costcenterdetail->tablename = 'returnsellbillController.php';
            $Costcenterdetail->type = 1;
            $Costcenterdetail->uesrid = $_SESSION['userid'];

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

            //insert Return Data into returnsellbilldetail tbl
            $returnSellbillItr = $_POST['returnhidden_itr'];
            $h = 1;
            for ($h = 1; $h <= $returnSellbillItr; $h++) {
                $parcode = $_POST['returnparcode' . $h . ''];
                $parcodeType = $_POST['returnparcodeType' . $h . ''];
                $productserailId = $_POST['returnproductserailid' . $h . ''];
                $productId = $_POST['returnproduct' . $h . ''];
                $productunitId = $_POST['returnproductunit' . $h . ''];
                $quantity = $_POST['returnpronum' . $h . ''];
                $price = $_POST['returnproprice' . $h . ''];
                $discountValue = $_POST['returnprodis' . $h . ''];
                $totalPrice = $_POST['returnhidden_prototal' . $h . ''];
                $comment = $_POST['returncomment' . $h . ''];
                $returndiscounttype = $_POST['returndiscounttype' . $h . ''];




                $reprstorid = $_POST['reprstorid' . $h . ''];
                if (isset($reprstorid) && $reprstorid != -1 && $reprstorid != '') {

                    $sellbillstoreId = $reprstorid;
                } else {
                    $sellbillstoreId = $_POST['storeid'];
                    //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                }

                if ($productunitId == "") {
                    $productunitId = 0;
                }


                if (isset($productId) && $productId != '-1' && $productId != "") {
                    $productData = loadProductById($productId);
                    $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);

                    $myReturnsellbilldetail->buyprice = $productData->productBuyPrice;
                    $myReturnsellbilldetail->conditions = 0;
                    $myReturnsellbilldetail->discountvalue = $discountValue;
                    $myReturnsellbilldetail->note = $comment;
                    $myReturnsellbilldetail->parcode = $parcode;
                    $myReturnsellbilldetail->pricetype = $priceType;
                    $myReturnsellbilldetail->productunitid = $productunitId;
                    $myReturnsellbilldetail->returnsellbilldetailcatid = $productData->productCatId;
                    $myReturnsellbilldetail->returnsellbilldetailprice = $price;
                    $myReturnsellbilldetail->returnsellbilldetailproductid = $productId;
                    $myReturnsellbilldetail->returnsellbilldetailquantity = $quantity;
                    $myReturnsellbilldetail->returnsellbilldetailtotalprice = $totalPrice;
                    $myReturnsellbilldetail->returnsellbillid = $returnsellbillId;
                    $myReturnsellbilldetail->buydiscount = $productData->buydiscount;
                    $myReturnsellbilldetail->buydiscounttype = $productData->discounttype;
                    $myReturnsellbilldetail->storeid = $sellbillstoreId;
                    $myReturnsellbilldetail->discounttype = $returndiscounttype;

                    $myReturnsellbilldetailRecord->insert($myReturnsellbilldetail);


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

                    //update DON if is Serial
                    if ($parcodeType == "serialnumber") {
                        //updateSerailDon($productserailId, 0, 0);
                        updateSerailQty_ForReturn($productserailId, $finalquantity);
                    }



                    //get storeto productquantity before change
                    $storedetailData = getStoredetailData($sellbillstoreId, $productId);

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

                    if (count($allStoredetailData) > 0) {

                        //update productquantity in storedetail
                        $productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity);


                        //insert in storereport
                        insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $returnsellbillId, "اضافة فاتورة مردودات مبيعات", "returnsellbillController.php", $sellbillDate);
                    } else {
                        //insert in storedetail tbl
                        insertStoredetailupdate($sellbillstoreId, $productId, $finalquantity, $sellbillDate);


                        //insert in storereport
                        insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $returnsellbillId, "اضافة فاتورة مردودات مبيعات", "returnsellbillController.php", $sellbillDate);
                    }
                }
            }



            if ($sellbillclientId != 0) {
                //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
                //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
                {

                    //update rawmaterialssupplierdebt

                    if ($sellbillclientId == 1) {

                    } else {

                    }
                    updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                    insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 1, "اضافة فاتورة مردوات مبيعات", $returnsellbillId, $sellbilltotaldeptAfter, "returnsellbillController.php", "اضافة فاتورة مردوات مبيعات", $sellbillAftertotalBill, $sellbillDate);
                }
            }


            //check if payed or not to change save value

            if ($sellbilltotalPayed > 0) {

                //get saveValue before and saveValue after mins sellbilltotalPayed
                $saveData = getSaveValueAndMins($_SESSION['saveid'], $sellbilltotalPayed);
                $saveId = $saveData[0];
                $saveValuebefore = $saveData[1];
                $saveValueafter = $saveData[2];

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

                //insert into savedaily tbl from savefrom

                $specialSellbilltotalPayed = $sellbilltotalPayed * -1;

                insertSavedailyupdate($saveValuebefore, $specialSellbilltotalPayed, 1, $saveId, "اضافة فاتورة مردوات مبيعات", $returnsellbillId, $saveValueafter, "returnsellbillController.php", date("Y-m-d H:i:s"));
            }
        }
    }

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



    return array($sellbillId, $returnsellbillId, $productsBeforeValid, $saveValuebeforeValid, $billtype);
}

function newadd($oldid, $controlname) {
    global $mySellbill;
    global $mySellbillRecord;
    global $mySellbillEx;

    global $mySellbilldetail;
    global $mySellbilldetailRecord;

    global $myReturnsellbill;
    global $myReturnsellbillRecord;
    global $myReturnsellbillEx;

    global $myReturnsellbilldetail;
    global $myReturnsellbilldetailRecord;


    global $mySellbillandrutern;
    global $mySellbillandruternRecord;
    global $mySellbillandruternEx;

    global $mySellandruternbilldetail;
    global $mySellandruternbilldetailRecord;

    global $soldSerialProduct;
    global $soldSerialProductDAO;

    global $ProductunitDAO;
    global $Productunit;
    global $myProductunitEx;

    global $myProductserialEx;

    global $CostcenterdetailDAO;
    global $Costcenterdetail;


    $billnameId = $_POST['billnameid'];

    $settingReturn = $_POST['settingreturn'];
    $settingClient = $_POST['settingclient'];
    $settingStore = $_POST['settingstore'];
    $settingSeller = $_POST['settingseller'];
    $settingParcode = $_POST['settingparcode'];
    $settingDate = $_POST['settingdate'];
    $settingNewproduct = $_POST['settingnewproduct'];
    $settingComment = $_POST['settingcomment'];
    $settingDiscount = $_POST['settingdiscount'];
    $settingQuantityCondition = $_POST['settingquantitycondition'];

    $tempClientName = $_POST['tempclientName'];
    $tax = $_POST["tax"];

    $sellbillcarnumber = $_POST['carNumber'];
    $sellbillcartype = $_POST['carType'];
    $sellbillcarchase = $_POST['carChase'];
    $sellbillcarmotor = $_POST['carMotor'];



    $sellbillclientId = $_POST['supplier'];


    $Costcenterid = $_POST["Costcenter"];

    $clientName = loadClientNameById($sellbillclientId);

    $sellbildirectPayment;
    //client
    if ($settingClient == 0 && $_POST['supplier'] != 1) {
        $sellbildirectPayment = 1;
    } else {
        $sellbildirectPayment = 0;
    }

    //Date
    if ($settingDate == 0) {
        $sellbillDate = $_POST['bn'];
    } else {
        $sellbillDate = date("Y-m-d h:m:s");
    }

    //Store
    if ($settingStore == 0) {
        $sellbillstoreId = 1; //;
    } else {
        $sellbillstoreId = 1; //;
    }

    //seller
    if ($settingSeller == 0) {
        $sellerId = $_POST['sellerid'];
        if ($sellerId == "-1" || $sellerId == "" || $sellerId == NULL) {
            $sellerId = 0;
        }
    } else {
        $sellerId = 0;
    }

    $sellbillSerial = $_POST['bns'];
    $priceType = $_POST['hiddenpricetype'];

    $sellbilltotalBill = $_POST['sellbilltotalbill']; //اجمالى الفاتورة قبل الخصم
    $sellbillDiscountType = $_POST['distype']; //نوع الخصم

    $sellbillDiscount = $_POST['gendis']; //قيمة الخصم
    $sellbillAftertotalBill = $_POST['sellbillaftertotalbill']; //القيمة بعد الخصم
    $sellbilltotalPayed = $_POST['genpay']; //المدفوع
    $sellbillFinalbill = $sellbillAftertotalBill - $sellbilltotalPayed; //المتبقى

    $sellbillPrice = $_POST['sellbillprice']; //اجمالى المبيعات
    $returnsellbillPrice = $_POST['returnsellbillprice']; //اجمالى مردودات المبيعات

    $sellQuantity = $_POST['sellQuantity'];
    $returnsellQuantity = $_POST['returnsellQuantity'];



    $clientdata = loadClientDataById($sellbillclientId);
    $sellbilltotaldeptBefor = $clientdata->clientdebt; //$_POST['hidden_debt'];
    $sellbilltotaldeptAfter = $sellbilltotaldeptBefor + ($sellbillAftertotalBill - $sellbilltotalPayed); //المتبقى$_POST['clientdebtafter'];




    $productsBeforeValid = 1;
    $saveValuebeforeValid = 1;

    //////////////////////////////////////////////////////////////////////////

    $sellbillItr = $_POST['hidden_itr'];
    $returnSellbillItr = $_POST['returnhidden_itr'];

    //check storerdetail value
    //check product quantity
    if ($sellbillPrice > 0) {
        $h = 1;
        for ($h = 1; $h <= $sellbillItr; $h++) {
            $productId = $_POST['product' . $h . ''];
            $productQuantity = $_POST['pronum' . $h . ''];

            if (isset($productId) && $productId != '-1' && $productId != "") {
                //get storefrom productquantity before change
                $storedetailData = getStoredetailData($sellbillstoreId, $productId);

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

                //check if productquantityFromBefore greater than 0 or not
                $productsBeforeValid = 1;
                if ($productquantityBefore > 0 && count($allStoredetailData) > 0) {
                    $productsAfterValid = $productquantityBefore - $productQuantity;

                    if ($productsAfterValid >= 0) {
                        $productsBeforeValid = 1;
                    } else {
                        $productsBeforeValid = 0;
                        //return $productsBeforeValid;
                    }
                } else {
                    $productsBeforeValid = 0;
                    //return $productsBeforeValid;
                }
            }
        }
    }




    /////////////////check savefrom value before transfer//////////////////////

    if ($returnsellbillPrice > 0 && ($sellbillPrice <= 0 || $sellbillAftertotalBill)) {
        $saveValueafterValid;

        //get save value
        $saveValueBefore = getSaveValueBefore($_SESSION['saveid']);

        $saveValueafterValid = $saveValueBefore - $sellbilltotalPayed;

        if ($saveValueafterValid >= 0) {
            $saveValuebeforeValid = 1;
        } else {
            $saveValuebeforeValid = 0;
            //return $saveValuebeforeValid;
        }
    }


    $billtype;
    // مبيعات و ومردودات
    //insert data into Sellbillandrutern tbl
    if ($sellbillPrice > 0 && $returnsellbillPrice > 0) {
        $billtype = 3; // مبيعات و ومردودات


        $mySellbillandrutern->deletedsellid = $oldid;
        $mySellbillandrutern->controlname = $controlname;


        $mySellbillandrutern->billnameid = $billnameId;
        $mySellbillandrutern->conditions = 0;
        $mySellbillandrutern->sellbildirectpayment = $sellbildirectPayment;
        $mySellbillandrutern->sellbillaftertotalbill = $sellbillAftertotalBill;
        $mySellbillandrutern->sellbillclientid = $sellbillclientId;
        $mySellbillandrutern->sellbillclientname = $clientName;
        $mySellbillandrutern->sellbilldate = $sellbillDate;
        $mySellbillandrutern->sellbilldiscount = $sellbillDiscount;
        $mySellbillandrutern->sellbilldiscounttype = $sellbillDiscountType;
        $mySellbillandrutern->tempclientName = $tempClientName;
        $mySellbillandrutern->sellQuantity = $sellQuantity;
        $mySellbillandrutern->returnsellQuantity = $returnsellQuantity;
        $mySellbillandrutern->tax = $tax;

        if ($sellbilltotalBill < 0) {
            $sellbillFinalbill = $sellbillAftertotalBill + $sellbilltotalPayed;
        }
        $mySellbillandrutern->sellbillfinalbill = $sellbillFinalbill;
        $mySellbillandrutern->sellbillsaveid = $_SESSION['saveid'];
        $mySellbillandrutern->sellbillserial = $sellbillSerial;
        $mySellbillandrutern->sellbillstoreid = $sellbillstoreId;
        $mySellbillandrutern->sellbillsysdate = date("Y-m-d H:i:s");
        $mySellbillandrutern->sellbilltotalbill = $sellbilltotalBill;
        $mySellbillandrutern->sellbilltotaldeptafter = $sellbilltotaldeptAfter;
        $mySellbillandrutern->sellbilltotaldeptbefor = $sellbilltotaldeptBefor;
        $mySellbillandrutern->sellbilltotalpayed = $sellbilltotalPayed;
        $mySellbillandrutern->sellerid = $sellerId;
        $mySellbillandrutern->userid = $_SESSION['userid'];
        $mySellbillandrutern->sellbillprice = $sellbillPrice;
        $mySellbillandrutern->returnsellbillprice = $returnsellbillPrice;
        $mySellbillandrutern->carnumber = $sellbillcarnumber;
        $mySellbillandrutern->cartype = $sellbillcartype;
        $mySellbillandrutern->carchase = $sellbillcarchase;
        $mySellbillandrutern->carmotor = $sellbillcarmotor;
        $mySellbillandrutern->costcenterid = $Costcenterid;



        $sellbillId = $mySellbillandruternEx->insertupdate($mySellbillandrutern);
        $Costcenterdetail->costamount = $sellbillAftertotalBill;
        $Costcenterdetail->costcenterid = $Costcenterid;
        $Costcenterdetail->costdate = date('Y-m-d');
        $Costcenterdetail->del = 0;
        $Costcenterdetail->modelid = $sellbillId;
        $Costcenterdetail->processname = 'فاتوره مبيعات ومردودات';
        $Costcenterdetail->tablename = 'sellbillandruternController.php';
        $Costcenterdetail->type = 2;
        $Costcenterdetail->uesrid = $_SESSION['userid'];

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


        //insert Sell Data into Sellandruternbilldetail tbl
        $sellbillItr = $_POST['hidden_itr'];
        $h = 1;
        for ($h = 1; $h <= $sellbillItr; $h++) {
            $parcode = $_POST['parcode' . $h . ''];
            $parcodeType = $_POST['parcodeType' . $h . ''];
            $productserailId = $_POST['productserailid' . $h . ''];
            $productId = $_POST['product' . $h . ''];
            $productunitId = $_POST['productunit' . $h . ''];
            $quantity = $_POST['pronum' . $h . ''];
            $price = $_POST['proprice' . $h . ''];
            $discountValue = $_POST['prodis' . $h . ''];
            $discounttype = $_POST['discounttype' . $h . ''];
            $totalPrice = $_POST['hidden_prototal' . $h . ''];
            $comment = $_POST['comment' . $h . ''];
            $prstorid = $_POST['prstorid' . $h . ''];

            if (isset($prstorid) && $prstorid != -1 && $prstorid != '') {

                $sellbillstoreId = $prstorid;
            } else {
                $sellbillstoreId = 1; //;
                //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
            }

            if ($productunitId == "") {
                $productunitId = 0;
            }



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


                $productData = loadProductById($productId);


                $mySellandruternbilldetail->buyprice = $productData->productBuyPrice;
                $mySellandruternbilldetail->discountvalue = $discountValue;
                $mySellandruternbilldetail->note = $comment;
                $mySellandruternbilldetail->parcode = $parcode;
                $mySellandruternbilldetail->pricetype = $priceType;
                $mySellandruternbilldetail->productunitid = $productunitId;
                $mySellandruternbilldetail->sellbilldetailcatid = $productData->productCatId;
                $mySellandruternbilldetail->sellbilldetaildate = $sellbillDate; //date("Y-m-d h:m:s");
                $mySellandruternbilldetail->sellbilldetailprice = $price;
                $mySellandruternbilldetail->sellbilldetailproductid = $productId;
                $mySellandruternbilldetail->sellbilldetailquantity = $quantity;
                $mySellandruternbilldetail->sellbilldetailtotalprice = $totalPrice;
                $mySellandruternbilldetail->sellbillid = $sellbillId;
                $mySellandruternbilldetail->selltype = 0; //مبيعات
                $mySellandruternbilldetail->buydiscount = $productData->buydiscount;
                $mySellandruternbilldetail->buydiscounttype = $productData->discounttype;
                $mySellandruternbilldetail->storeid = $sellbillstoreId;
                $mySellandruternbilldetail->discounttype = $discounttype;


                $mySellandruternbilldetailRecord->insert($mySellandruternbilldetail);


                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                $productnumber = $productunitData->productnumber;
                $finalquantity = $quantity * $productnumber;
                //update DON if is Serial
                if ($parcodeType == "serialnumber") {
                    //update don column (quantity) in productserial table
                    updateSerailQty($productserailId, $finalquantity);
                    insertIntoSoldSerialProduct($productserailId, $finalquantity, $sellbillId, 1);
                }



                //get store productquantity before change
                $storedetailData = getStoredetailData($sellbillstoreId, $productId);

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



                if (count($allStoredetailData) > 0) {

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


                    //insert in storereport
                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات (معدله)", "sellbillandruternController.php", $sellbillDate);
                } else {
                    $specialQuantityAfter = $finalquantity * -1;

                    //insert in storedetail tbl
                    insertStoredetailupdate($sellbillstoreId, $productId, $specialQuantityAfter, $sellbillDate);

                    //insert in storereport
                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $specialQuantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات (معدله)", "sellbillandruternController.php", $sellbillDate);
                }
            }
        }



        //insert Return Data into Sellandruternbilldetail tbl
        $returnSellbillItr = $_POST['returnhidden_itr'];
        $h = 1;
        for ($h = 1; $h <= $returnSellbillItr; $h++) {
            $parcode = $_POST['returnparcode' . $h . ''];
            $parcodeType = $_POST['returnparcodeType' . $h . ''];
            $productserailId = $_POST['returnproductserailid' . $h . ''];
            $productId = $_POST['returnproduct' . $h . ''];
            $productunitId = $_POST['returnproductunit' . $h . ''];
            $quantity = $_POST['returnpronum' . $h . ''];
            $price = $_POST['returnproprice' . $h . ''];
            $discountValue = $_POST['returnprodis' . $h . ''];
            $totalPrice = $_POST['returnhidden_prototal' . $h . ''];
            $comment = $_POST['returncomment' . $h . ''];
            $reprstorid = $_POST['reprstorid' . $h . ''];
            $returndiscounttype = $_POST['returndiscounttype' . $h . ''];

            if (isset($reprstorid) && $reprstorid != -1 && $reprstorid != '') {

                $sellbillstoreId = $reprstorid;
            } else {
                $sellbillstoreId = 1; //;
                //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
            }
            if ($productunitId == "") {
                $productunitId = 0;
            }

            if (isset($productId) && $productId != '-1' && $productId != "") {
                $productData = loadProductById($productId);


                $mySellandruternbilldetail->buyprice = $productData->productBuyPrice;
                $mySellandruternbilldetail->discountvalue = $discountValue;
                $mySellandruternbilldetail->note = $comment;
                $mySellandruternbilldetail->parcode = $parcode;
                $mySellandruternbilldetail->pricetype = $priceType;
                $mySellandruternbilldetail->productunitid = $productunitId;
                $mySellandruternbilldetail->sellbilldetailcatid = $productData->productCatId;
                $mySellandruternbilldetail->sellbilldetaildate = date("Y-m-d h:m:s");
                $mySellandruternbilldetail->sellbilldetailprice = $price;
                $mySellandruternbilldetail->sellbilldetailproductid = $productId;
                $mySellandruternbilldetail->sellbilldetailquantity = $quantity;
                $mySellandruternbilldetail->sellbilldetailtotalprice = $totalPrice;
                $mySellandruternbilldetail->sellbillid = $sellbillId;
                $mySellandruternbilldetail->selltype = 1; //مردودات
                $mySellandruternbilldetail->buydiscount = $productData->buydiscount;
                $mySellandruternbilldetail->buydiscounttype = $productData->discounttype;
                $mySellandruternbilldetail->storeid = $sellbillstoreId;
                $mySellandruternbilldetail->discounttype = $returndiscounttype;

                $mySellandruternbilldetailRecord->insert($mySellandruternbilldetail);

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

                //update DON if is Serial
                if ($parcodeType == "serialnumber") {
                    //update don column (quantity) in productserial table
                    updateSerailQty_ForReturn($productserailId, $finalquantity);
                }


                //get storeto productquantity before change
                $storedetailData = getStoredetailData($sellbillstoreId, $productId);

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

                if (count($allStoredetailData) > 0) {

                    //update productquantity in storedetail
                    $productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity);


                    //insert in storereport
                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $sellbillId, "اضافة فاتورة مردودات مبيعات (معدله)", "sellbillandruternController.php", $sellbillDate);
                } else {
                    //insert in storedetail tbl
                    insertStoredetailupdate($sellbillstoreId, $productId, $finalquantity, $sellbillDate);


                    //insert in storereport
                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $sellbillId, "اضافة فاتورة مردودات مبيعات (معدله)", "sellbillandruternController.php", $sellbillDate);
                }
            }
        }



        if ($sellbillclientId != 0) {
            //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
            //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
            {

                //update rawmaterialssupplierdebt
                updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                if ($sellbilltotalBill < 0) {
                    $sellbillFinalbill = $sellbillFinalbill * -1;
                    insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 1, "اضافة فاتورة مبيعات ومردودات", $sellbillId, $sellbilltotaldeptAfter, "sellbillandruternController.php", "اضافة فاتورة مبيعات ومردودات (معدله)", $sellbillAftertotalBill, $sellbillDate);
                } else {
                    insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 0, "اضافة فاتورة مبيعات ومردودات", $sellbillId, $sellbilltotaldeptAfter, "sellbillandruternController.php", "اضافة فاتورة مبيعات ومردودات (معدله)", $sellbillAftertotalBill, $sellbillDate);
                }
            }
        }


        //check if payed or not to change save value

        if ($sellbilltotalPayed > 0) {
            if ($sellbillAftertotalBill > 0) {

                //get saveValue before and saveValue after Plus lPayed
                $saveData = getSaveValueAndPlus($_SESSION['saveid'], $sellbilltotalPayed);
                $saveId = $saveData[0];
                $saveValuebefore = $saveData[1];
                $saveValueafter = $saveData[2];

                //update save value after add sellbill
                updateSave($saveId, $saveValueafter);

                //insert into savedaily tbl from save
                insertSavedailyupdate($saveValuebefore, $sellbilltotalPayed, 0, $saveId, "اضافة فاتورة مبيعات ومردودات (معدله)", $sellbillId, $saveValueafter, "sellbillandruternController.php", date("Y-m-d H:i:s"));
            } else {
                //get saveValue before and saveValue after Plus lPayed
                $saveData = getSaveValueAndMins($_SESSION['saveid'], $sellbilltotalPayed);
                $saveId = $saveData[0];
                $saveValuebefore = $saveData[1];
                $saveValueafter = $saveData[2];

                //update save value after add sellbill
                updateSave($saveId, $saveValueafter);

                $specialSellbilltotalPayed = $sellbilltotalPayed * -1;

                //insert into savedaily tbl from save
                insertSavedailyupdate($saveValuebefore, $specialSellbilltotalPayed, 1, $saveId, "اضافة فاتورة مبيعات ومردودات (معدله)", $sellbillId, $saveValueafter, "sellbillandruternController.php", date("Y-m-d H:i:s"));
            }
        }
    }






    //مبيعات
    //insert data into Sellbill tbl
    elseif ($sellbillPrice > 0 && $returnsellbillPrice <= 0) {
        $billtype = 1; //مبيعات


        $mySellbill->billnameid = $billnameId;
        $mySellbill->conditions = 0;
        $mySellbill->sellbildirectpayment = $sellbildirectPayment;
        $mySellbill->sellbillaftertotalbill = $sellbillAftertotalBill;
        $mySellbill->sellbillclientid = $sellbillclientId;
        $mySellbill->sellbillclientname = $clientName;
        $mySellbill->sellbilldate = $sellbillDate;
        $mySellbill->sellbilldiscount = $sellbillDiscount;
        $mySellbill->sellbilldiscounttype = $sellbillDiscountType;
        $mySellbill->sellbillfinalbill = $sellbillFinalbill;
        $mySellbill->sellbillsaveid = $_SESSION['saveid'];
        $mySellbill->sellbillserial = $sellbillSerial;
        $mySellbill->sellbillstoreid = $sellbillstoreId;
        $mySellbill->sellbillsysdate = date("Y-m-d H:i:s");
        $mySellbill->sellbilltotalbill = $sellbilltotalBill;
        $mySellbill->sellbilltotaldeptafter = $sellbilltotaldeptAfter;
        $mySellbill->sellbilltotaldeptbefor = $sellbilltotaldeptBefor;
        $mySellbill->sellbilltotalpayed = $sellbilltotalPayed;
        $mySellbill->sellerid = $sellerId;
        $mySellbill->userid = $_SESSION['userid'];
        $mySellbill->tempclientName = $tempClientName;
        $mySellbill->sellQuantity = $sellQuantity;
        $mySellbill->tax = $tax;
        $mySellbill->carnumber = $sellbillcarnumber;
        $mySellbill->cartype = $sellbillcartype;
        $mySellbill->carchase = $sellbillcarchase;
        $mySellbill->carmotor = $sellbillcarmotor;



        $mySellbill->deletedsellid = $oldid;
        $mySellbill->controlname = $controlname;
        $mySellbill->costcenterid = $Costcenterid;


        $sellbillId = $mySellbillEx->insertupdate($mySellbill);

        $Costcenterdetail->costamount = $sellbillAftertotalBill;
        $Costcenterdetail->costcenterid = $Costcenterid;
        $Costcenterdetail->costdate = date('Y-m-d');
        $Costcenterdetail->del = 0;
        $Costcenterdetail->modelid = $sellbillId;
        $Costcenterdetail->processname = 'فاتوره مبيعات';
        $Costcenterdetail->tablename = 'sellbillController.php';
        $Costcenterdetail->type = 0;
        $Costcenterdetail->uesrid = $_SESSION['userid'];

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



        //insert Sell Data into Sellbilldetail tbl
        $sellbillItr = $_POST['hidden_itr'];
        $h = 1;
        for ($h = 1; $h <= $sellbillItr; $h++) {
            $parcode = $_POST['parcode' . $h . ''];
            $parcodeType = $_POST['parcodeType' . $h . ''];
            $productserailId = $_POST['productserailid' . $h . ''];
            $productId = $_POST['product' . $h . ''];
            $productunitId = $_POST['productunit' . $h . ''];
            $quantity = $_POST['pronum' . $h . ''];
            $price = $_POST['proprice' . $h . ''];
            $discountValue = $_POST['prodis' . $h . ''];
            $totalPrice = $_POST['hidden_prototal' . $h . ''];
            $comment = $_POST['comment' . $h . ''];
            $prstorid = $_POST['prstorid' . $h . ''];
            $discounttype = $_POST['discounttype' . $h . ''];

            if (isset($prstorid) && $prstorid != -1 && $prstorid != '') {

                //print_r('in if prstorid'.$prstorid.'<br>');

                $sellbillstoreId = $prstorid;
            } else {
                $sellbillstoreId = 1; //;
                //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
            }
            if ($productunitId == "") {
                $productunitId = 0;
            }
            //print_r('the final'.$sellbillstoreId.'<br>');

            if (isset($productId) && $productId != '-1' && $productId != "") {
                $productData = loadProductById($productId);


                $mySellbilldetail->buyprice = $productData->productBuyPrice;
                $mySellbilldetail->discountvalue = $discountValue;
                $mySellbilldetail->note = $comment;
                $mySellbilldetail->parcode = $parcode;
                $mySellbilldetail->pricetype = $priceType;
                $mySellbilldetail->productunitid = $productunitId;
                $mySellbilldetail->sellbilldetailcatid = $productData->productCatId;
                $mySellbilldetail->sellbilldetaildate = $sellbillDate; //date("Y-m-d h:m:s");
                $mySellbilldetail->sellbilldetailprice = $price;
                $mySellbilldetail->sellbilldetailproductid = $productId;
                $mySellbilldetail->sellbilldetailquantity = $quantity;
                $mySellbilldetail->sellbilldetailtotalprice = $totalPrice;
                $mySellbilldetail->sellbillid = $sellbillId;
                $mySellbilldetail->buydiscount = $productData->buydiscount;
                $mySellbilldetail->buydiscounttype = $productData->discounttype;
                $mySellbilldetail->storeid = $sellbillstoreId;
                $mySellbilldetail->discounttype = $discounttype;


                $mySellbilldetailRecord->insert($mySellbilldetail);
                //print("qty: ".$quantity.'<br>');
                //print("<br>productserailId: ".$productserailId);
                //update DON if is Serial

                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                //print_r($productunitData);
                $productnumber = $productunitData->productnumber;
                $finalquantity = $quantity * $productnumber;
                /* 	print("productnumber: ".$productnumber.'<br>');
                  print("quantity: ".$quantity.'<br>');
                  print("finalquantity: ".$finalquantity.'<br>'); */
                if ($parcodeType == "serialnumber") {
                    //print("<br>serialnumber<br>");
                    //updateSerailDon($productserailId, 1, $sellbillId);
                    updateSerailQty($productserailId, $finalquantity);
                    insertIntoSoldSerialProduct($productserailId, $finalquantity, $sellbillId, 0);
                }



                //get store productquantity before change
                $storedetailData = getStoredetailData($sellbillstoreId, $productId);

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

                //print("qty: ".$finalquantity.'<br>');
                if (count($allStoredetailData) > 0) {

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

                    //print("productquantityAfter: ".$productquantityAfter.'<br>');
                    //insert in storereport
                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات (معدله)", "sellbillController.php", $sellbillDate);
                } else {
                    $specialQuantityAfter = $finalquantity * -1;

                    //insert in storedetail tbl
                    insertStoredetailupdate($sellbillstoreId, $productId, $specialQuantityAfter, $sellbillDate);

                    //insert in storereport
                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $specialQuantityAfter, 1, $sellbillId, "اضافة فاتورة مبيعات (معدله)", "sellbillController.php", $sellbillDate);
                }
            }
        }

        if ($sellbillclientId != 0) {
            //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
            //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
            {

                //update rawmaterialssupplierdebt
                updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 0, "اضافة فاتورة مبيعات (معدله)", $sellbillId, $sellbilltotaldeptAfter, "sellbillController.php", "اضافة فاتورة مبيعات (معدله)", $sellbillAftertotalBill, $sellbillDate);
            }
        }


        //check if payed or not to change save value

        if ($sellbilltotalPayed > 0) {
            //get saveValue before and saveValue after Plus lPayed
            $saveData = getSaveValueAndPlus($_SESSION['saveid'], $sellbilltotalPayed);
            $saveId = $saveData[0];
            $saveValuebefore = $saveData[1];
            $saveValueafter = $saveData[2];

            //update save value after add sellbill
            updateSave($saveId, $saveValueafter);

            //insert into savedaily tbl from save
            insertSavedailyupdate($saveValuebefore, $sellbilltotalPayed, 0, $saveId, "اضافة فاتورة مبيعات (معدله)", $sellbillId, $saveValueafter, "sellbillController.php", date("Y-m-d H:i:s"));
        }
    }





    //مردودات مبيعات
    //insert data into returnSellbill tbl
    elseif ($sellbillPrice <= 0 && $returnsellbillPrice > 0) {
        $billtype = 2; //مردودات مبيعات



        $myReturnsellbill->billnameid = $billnameId;
        $myReturnsellbill->conditions = 0;
        $myReturnsellbill->returnsellbildirectpayment = $sellbildirectPayment;
        $myReturnsellbill->returnsellbillaftertotalbill = $sellbillAftertotalBill * -1;
        $myReturnsellbill->returnsellbillclientid = $sellbillclientId;
        $myReturnsellbill->returnsellbillclientname = $clientName;
        $myReturnsellbill->returnsellbilldate = $sellbillDate;
        $myReturnsellbill->returnsellbilldiscount = $sellbillDiscount;
        $myReturnsellbill->returnsellbilldiscounttype = $sellbillDiscountType;
        $myReturnsellbill->tax = $tax;

        $sellbillFinalbill = ($sellbillAftertotalBill * -1) - $sellbilltotalPayed;
        $myReturnsellbill->returnsellbillfinalbill = $sellbillFinalbill;
        $myReturnsellbill->returnsellbillsaveid = $_SESSION['saveid'];
        $myReturnsellbill->returnsellbillserial = $sellbillSerial;
        $myReturnsellbill->returnsellbillstoreid = $sellbillstoreId;
        $myReturnsellbill->returnsellbillsysdate = date("Y-m-d h:m:s");
        $myReturnsellbill->returnsellbilltotalbill = $sellbilltotalBill * -1;
        $myReturnsellbill->returnsellbilltotaldeptafter = $sellbilltotaldeptAfter;
        $myReturnsellbill->returnsellbilltotaldeptbefor = $sellbilltotaldeptBefor;
        $myReturnsellbill->returnsellbilltotalpayed = $sellbilltotalPayed;
        $myReturnsellbill->sellerid = $sellerId;
        $myReturnsellbill->userid = $_SESSION['userid'];
        $myReturnsellbill->tempclientName = $tempClientName;
        $myReturnsellbill->returnsellQuantity = $returnsellQuantity;

        $myReturnsellbill->deletedsellid = $oldid;
        $myReturnsellbill->controlname = $controlname;
        $mySellbill->carnumber = $sellbillcarnumber;
        $myReturnsellbill->cartype = $sellbillcartype;
        $myReturnsellbill->carchase = $sellbillcarchase;
        $myReturnsellbill->carmotor = $sellbillcarmotor;
        $myReturnsellbill->costcenterid = $Costcenterid;


        $returnsellbillId = $myReturnsellbillEx->insertupdate($myReturnsellbill);

        $Costcenterdetail->costamount = $sellbillAftertotalBill;
        $Costcenterdetail->costcenterid = $Costcenterid;
        $Costcenterdetail->costdate = date('Y-m-d');
        $Costcenterdetail->del = 0;
        $Costcenterdetail->modelid = $returnsellbillId;
        $Costcenterdetail->processname = 'فاتوره مردودات مبيعات';
        $Costcenterdetail->tablename = 'returnsellbillController.php';
        $Costcenterdetail->type = 0;
        $Costcenterdetail->uesrid = $_SESSION['userid'];

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


        //insert Return Data into returnsellbilldetail tbl
        $returnSellbillItr = $_POST['returnhidden_itr'];
        $h = 1;
        for ($h = 1; $h <= $returnSellbillItr; $h++) {
            $parcode = $_POST['returnparcode' . $h . ''];
            $parcodeType = $_POST['returnparcodeType' . $h . ''];
            $productserailId = $_POST['returnproductserailid' . $h . ''];
            $productId = $_POST['returnproduct' . $h . ''];
            $productunitId = $_POST['returnproductunit' . $h . ''];
            $quantity = $_POST['returnpronum' . $h . ''];
            $price = $_POST['returnproprice' . $h . ''];
            $discountValue = $_POST['returnprodis' . $h . ''];
            $totalPrice = $_POST['returnhidden_prototal' . $h . ''];
            $comment = $_POST['returncomment' . $h . ''];
            $returndiscounttype = $_POST['returndiscounttype' . $h . ''];


            $reprstorid = $_POST['reprstorid' . $h . ''];
            if (isset($reprstorid) && $reprstorid != -1 && $reprstorid != '') {

                $sellbillstoreId = $reprstorid;
            } else {
                $sellbillstoreId = 1; //;
                //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
            }

            if ($productunitId == "") {
                $productunitId = 0;
            }


            if (isset($productId) && $productId != '-1' && $productId != "") {
                $productData = loadProductById($productId);
                $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);

                $myReturnsellbilldetail->buyprice = $productData->productBuyPrice;
                $myReturnsellbilldetail->conditions = 0;
                $myReturnsellbilldetail->discountvalue = $discountValue;
                $myReturnsellbilldetail->note = $comment;
                $myReturnsellbilldetail->parcode = $parcode;
                $myReturnsellbilldetail->pricetype = $priceType;
                $myReturnsellbilldetail->productunitid = $productunitId;
                $myReturnsellbilldetail->returnsellbilldetailcatid = $productData->productCatId;
                $myReturnsellbilldetail->returnsellbilldetailprice = $price;
                $myReturnsellbilldetail->returnsellbilldetailproductid = $productId;
                $myReturnsellbilldetail->returnsellbilldetailquantity = $quantity;
                $myReturnsellbilldetail->returnsellbilldetailtotalprice = $totalPrice;
                $myReturnsellbilldetail->returnsellbillid = $returnsellbillId;
                $myReturnsellbilldetail->buydiscount = $productData->buydiscount;
                $myReturnsellbilldetail->buydiscounttype = $productData->discounttype;
                $myReturnsellbilldetail->storeid = $sellbillstoreId;
                $myReturnsellbilldetail->discounttype = $returndiscounttype;


                $myReturnsellbilldetailRecord->insert($myReturnsellbilldetail);


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

                //update DON if is Serial
                if ($parcodeType == "serialnumber") {
                    //updateSerailDon($productserailId, 0, 0);
                    updateSerailQty_ForReturn($productserailId, $finalquantity);
                }



                //get storeto productquantity before change
                $storedetailData = getStoredetailData($sellbillstoreId, $productId);

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

                if (count($allStoredetailData) > 0) {

                    //update productquantity in storedetail
                    $productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity);


                    //insert in storereport
                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $returnsellbillId, "اضافة فاتورة مردودات مبيعات (معدله)", "returnsellbillController.php", $sellbillDate);
                } else {
                    //insert in storedetail tbl
                    insertStoredetailupdate($sellbillstoreId, $productId, $finalquantity, $sellbillDate);


                    //insert in storereport
                    insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $returnsellbillId, "اضافة فاتورة مردودات مبيعات (معدله)", "returnsellbillController.php", $sellbillDate);
                }
            }
        }



        if ($sellbillclientId != 0) {
            //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
            //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
            {

                //update rawmaterialssupplierdebt
                updateClientDebt($sellbillclientId, $sellbilltotaldeptAfter);

                insertClientdebtchangeupdate($sellbillclientId, $sellbilltotaldeptBefor, $sellbillFinalbill, 1, "اضافة فاتورة مردوات مبيعات (معدله)", $returnsellbillId, $sellbilltotaldeptAfter, "returnsellbillController.php", "اضافة فاتورة مردوات مبيعات (معدله)", $sellbillAftertotalBill, $sellbillDate);
            }
        }


        //check if payed or not to change save value

        if ($sellbilltotalPayed > 0) {

            //get saveValue before and saveValue after mins sellbilltotalPayed
            $saveData = getSaveValueAndMins($_SESSION['saveid'], $sellbilltotalPayed);
            $saveId = $saveData[0];
            $saveValuebefore = $saveData[1];
            $saveValueafter = $saveData[2];

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

            //insert into savedaily tbl from savefrom

            $specialSellbilltotalPayed = $sellbilltotalPayed * -1;

            insertSavedailyupdate($saveValuebefore, $specialSellbilltotalPayed, 1, $saveId, "اضافة فاتورة مردوات مبيعات (معدله)", $returnsellbillId, $saveValueafter, "returnsellbillController.php", date("Y-m-d H:i:s"));
        }
    }



    return array($sellbillId, $returnsellbillId, $productsBeforeValid, $saveValuebeforeValid, $billtype);
}

//load client by Id tbl
function loadClientNameById($clientId) {
    //to use the variable out side the funcion
    global $myClientRecord;

    //load client by Id tbl
    $clientData = $myClientRecord->load($clientId);
    $clientName = $clientData->clientname;

    return $clientName;
}

//load client by Id tbl
function loadClientDataById($clientId) {
    //to use the variable out side the funcion
    global $myClientRecord;

    //load client by Id tbl
    $clientData = $myClientRecord->load($clientId);

    return $clientData;
}

// load Product by id tbl
function loadProductById($productid) {
    //to use the variable out side the funcion
    global $myProductRecord;
    global $myProductEx;

    // load Product by id tbl
    $productData = $myProductEx->loadByProductId($productid);

    return $productData;
}

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 showAll() {
    global $mySellbillEx;
    global $myClientRecord;
    global $userDAO;
    global $smarty;


    $queryString = ' WHERE';
    $message = "";
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $sellbillSerial = $_REQUEST['sellbillserial'];
    $sellbillId = $_REQUEST['sellbillid'];
    $clientId = $_REQUEST['clientid'];
    $sellerid = $_REQUEST['sellerid'];
    $selleruserid = $_REQUEST['selleruserid'];

    if (isset($clientId) && $clientId != "-1") {


        $messageData = $myClientRecord->load($clientId);
        $message .= "<br> إسم العميل: " . $messageData->clientname;


        $queryString .= ' sellbill.sellbillclientid = ' . $clientId . ' AND';
    }

    if (isset($sellerid) && $sellerid != "-1") {


        $messageData = $userDAO->load($sellerid);
        $message .= "<br> إسم {if $Programsettingdata->delegate_seller eq 0} بائع {elseif $Programsettingdata->delegate_seller == 1}مندوب {elseif $Programsettingdata->delegate_seller == 2}طبيب {/if}: " . $messageData->employeename;


        $queryString .= ' sellbill.sellerid = ' . $sellerid . ' AND';
    }



    if (isset($selleruserid) && $selleruserid != "-1") {


        $messageData = $userDAO->load($selleruserid);
        $message .= "<br> إسم المستخدم: " . $messageData->employeename;


        $queryString .= ' sellbill.userid = ' . $selleruserid . ' AND';
    }

    if (isset($sellbillSerial) && $sellbillSerial != "") {

        $message .= "<br> رقم الفاتورة: " . $sellbillSerial;


        $queryString .= ' sellbill.sellbillserial = ' . $sellbillSerial . ' AND';
    }
    if (isset($sellbillId) && $sellbillId != "") {


        $message .= "<br> الرقم المتسلسل : " . $sellbillId;

        $queryString .= ' sellbill.sellbillid = ' . $sellbillId . ' AND';
    }
    if (isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "") {


        $message .= "<br> من تاريخ : " . $startDate . " إلى تاريخ : " . $endDate . "";

        $queryString .= ' sellbill.sellbilldate >= "' . $startDate . '" and sellbill.sellbilldate <= "' . $endDate . '" AND';
    }



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


    $arr = explode(' ', $queryString);
    //print_r($arr);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') {//remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }
        if ($lastWord == 'WHERE') {//remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }

        //print("<br>queryString: ".$queryString."<br>");
    }

    $totalBills = 0;


    if ($queryString == "") {


        //print_r('in if');
        $today = date("Y-m-d h:m:s");
        $queryString .= ' where  sellbill.sellbilldate >= "' . $today . '" and sellbill.sellbilldate <= "' . $today . '" ';
    }

    //print_r($queryString);

    $sellbillData = $mySellbillEx->queryallWithOrder($queryString);
    if (count($sellbillData) > 0) {
        foreach ($sellbillData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->sellbillaftertotalbill;
            }
        }
    }
    // assign your db results to the template
    $smarty->assign('sellbillData', $sellbillData);
    $smarty->assign('totalBills', $totalBills);
}

function showByClient($clientId) {
    global $mySellbillEx;
    global $smarty;

    $totalBills = 0;
    $sellbillData = $mySellbillEx->queryWithClientId($clientId);
    if (count($sellbillData) > 0) {
        foreach ($sellbillData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->sellbillaftertotalbill;
            }
        }
    }
    // assign your db results to the template
    $smarty->assign('sellbillData', $sellbillData);
    $smarty->assign('totalBills', $totalBills);
}

function showBySriral($serial) {
    global $mySellbillEx;
    global $smarty;

    $totalBills = 0;
    $sellbillData = $mySellbillEx->queryWithSerail($serial);
    if (count($sellbillData) > 0) {
        foreach ($sellbillData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->sellbillaftertotalbill;
            }
        }
    }

    // assign your db results to the template
    $smarty->assign('sellbillData', $sellbillData);
    $smarty->assign('totalBills', $totalBills);
}

function showBySellbillId($sellbillId) {
    global $mySellbillEx;
    global $smarty;

    $totalBills = 0;
    $sellbillData = $mySellbillEx->queryWithSellbillId($sellbillId);
    if (count($sellbillData) > 0) {
        foreach ($sellbillData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->sellbillaftertotalbill;
            }
        }
    }

    // assign your db results to the template
    $smarty->assign('sellbillData', $sellbillData);
    $smarty->assign('totalBills', $totalBills);
}

function showByDate($startDate, $endDate) {
    global $mySellbillEx;
    global $smarty;

    $totalBills = 0;
    $sellbillData = $mySellbillEx->queryWithDate($startDate, $endDate);
    if (count($sellbillData) > 0) {
        foreach ($sellbillData as $sell) {
            if ($sell->conditions == 0) {
                $totalBills += $sell->sellbillaftertotalbill;
            }
        }
    }

    // assign your db results to the template
    $smarty->assign('sellbillData', $sellbillData);
    $smarty->assign('totalBills', $totalBills);
}

function delete($sellbillid) {
    global $mySellbill;

    global $mySellbillRecord;
    global $mySellbillEx;
    global $mySellbilldetail;
    global $mySellbilldetailRecord;

    global $soldSerialProductDAO;
    global $soldSerialProductExt;
    global $soldSerialProduct;
    global $myProductserialEx;


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

    try {

        $sellbillData = $mySellbillRecord->load($sellbillid);
        $CostcenterdetailEX->updatedellbytypeandmodelid(0, $sellbillid, 1);


        $sellbilltotalPayed = $sellbillData->sellbilltotalpayed;
        $sellbillstoreId = $sellbillData->sellbillstoreid;
        $sellbilltotaldeptAfter = $sellbillData->sellbilltotaldeptafter;
        $sellbilltotaldeptBefor = $sellbillData->sellbilltotaldeptbefor;
        $sellbillclientId = $sellbillData->sellbillclientid;
        $sellbillFinalbill = $sellbillData->sellbillfinalbill;
        $sellbillsaveId = $sellbillData->sellbillsaveid;

        $totalOperationCost = $sellbillData->sellbillaftertotalbill;

        $note;
        $saveValuebeforeValid = 1;

        /////////////////check save value before //////////////
        //get save value
        $saveValueBefore = getSaveValueBefore($sellbillsaveId);
        $saveValueafterValid = $saveValueBefore - $sellbilltotalPayed;
        if ($saveValueafterValid >= 0) {
            $saveValuebeforeValid = 1;

            $note = "success";
        } else {
            $saveValuebeforeValid = 0;
            //return $saveValuebeforeValid;

            $note = "لا يوجد بالخزنة المبلغ الكافى لحذف الفاتورة";
        }



        $mySellbill->conditions = 1;
        $mySellbill->sellbillsysdate = date("Y-m-d H:i:s");
        $mySellbill->userid = $_SESSION['userid'];
        $mySellbill->sellbillid = $sellbillid;

        $mySellbillEx->updateConditions($mySellbill);


        $sellbilldetailData = $mySellbilldetailRecord->queryBySellbillid($sellbillid);

        foreach ($sellbilldetailData as $sellbilldetail) {
            $productId = $sellbilldetail->sellbilldetailproductid;
            $quantity = $sellbilldetail->sellbilldetailquantity;
            $productunitId = $sellbilldetail->productunitid;




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

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




                $parcode = $sellbilldetail->parcode;
                $issold = $myProductserialEx->queryallisdSerial($productId, $parcode);


                if (count($issold) > 0) {


                    $soldSerialProduct->quantity = $finalquantity;
                    $soldSerialProduct->sellbilltype = 0;
                    $soldSerialProduct->sellbillid = $sellbillid;
                    $soldSerialProduct->del = 1;

                    $mysoldSerialProduct = $soldSerialProductExt->selectsoldeserial($soldSerialProduct);
                    //print_r($mysoldSerialProduct);
                    if (count($mysoldSerialProduct) > 0) {


                        $soldSerialProductExt->updatedel($soldSerialProduct);
                        $productserailid = $mysoldSerialProduct->productserailid;

                        updateSerailQty_ForReturn($productserailid, $finalquantity);
                    }
                }



                //get storeto productquantity before change
                $storedetailData = getStoredetailData($sellbillstoreId, $productId);

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

                if (count($allStoredetailData) > 0) {

                    //update productquantity in storedetail
                    $productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity);


                    //insert in storereport
                    insertStorereport($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $sellbillid, "حذف فاتورة مبيعات", "sellbillController.php");
                } else {
                    //insert in storedetail tbl
                    insertStoredetail($sellbillstoreId, $productId, $finalquantity);


                    //insert in storereport
                    insertStorereport($productId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $sellbillid, "حذف فاتورة مبيعات", "sellbillController.php");
                }
            }
        }



        if ($sellbillclientId != 0) {
            //check if sellbilltotaldeptAfter change from sellbilltotaldeptBefor
            //if($sellbilltotaldeptAfter != $sellbilltotaldeptBefor)
            {

                $clientData = loadClientDataById($sellbillclientId);
                $clientdeptBefor = $clientData->clientdebt;
                $clientdeptAfter = ($clientData->clientdebt) - $sellbillFinalbill;

                //update rawmaterialssupplierdebt
                updateClientDebt($sellbillclientId, $clientdeptAfter);

                insertClientdebtchange($sellbillclientId, $clientdeptBefor, $sellbillFinalbill, 1, "حذف فاتورة مبيعات", $sellbillid, $clientdeptAfter, "sellbillController.php", "حذف فاتورة مبيعات", $totalOperationCost);
            }
        }


        //check if payed or not to change save value

        if ($sellbilltotalPayed > 0) {

            //get saveValue before and saveValue after mins sellbilltotalPayed
            $saveData = getSaveValueAndMins($sellbillsaveId, $sellbilltotalPayed);
            $saveId = $saveData[0];
            $saveValuebefore = $saveData[1];
            $saveValueafter = $saveData[2];

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

            //insert into savedaily tbl from savefrom
            insertSavedaily($saveValuebefore, $sellbilltotalPayed, 1, $saveId, "حذف فاتورة مبيعات", $sellbillid, $saveValueafter, "sellbillController.php");
        }
    } catch (Exception $e) {
        $note = "حدث خطأ اثناء حذف الفاتورة";
    }

    return array($saveValuebeforeValid, $note);
}

function executeOperation() {
    //to use the variable out side the funcion
    global $mySellbillRecord;
    global $smarty;

    $outputString;

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

    $choosedItemArr = $_POST['choosedItem'];
    //print_r($choosedItemArr);
    if (count($choosedItemArr) > 0) {
        foreach ($choosedItemArr as $sellbillId) {

            //get store name
            $sellbillData = $mySellbillRecord->load($sellbillId);
            $sellbillSerial = $sellbillData->sellbillserial;

            if ($operationType == '1') {
                //tempdelete
                $note = delete($sellbillId);
                if ($note[1] != "success") {
                    $outputString .= $sellbillSerial . ": " . $note[1] . "<br/>";
                } else {
                    $outputString .= $sellbillSerial . ": تمت العملية بنجاح <br/>";
                }
            }
        }

        $smarty->assign("outputString", $outputString);
    }
}

function loadProductCat() {
    global $myProductEx;

    $allParents = $myProductEx->queryAllCategories();

    return $allParents;
}

function loadUnit() {
    global $myUnitRecord;

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

////////////////////////////save///////////////////////////
// get savecurrentvalue from save tbl
function getSaveValueBefore($saveid) {

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveRecord;

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

    return $saveValuebefore;
}

// get initialvalue and plus from save tbl
function getSaveValueAndPlus($saveid, $savevaluechanged) {

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveRecord;

    $saveData = $mySaveRecord->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) {

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveRecord;

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

    $saveValueafter = $saveValuebefore - $savevaluechanged;

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

// update in Save tbl
function updateSave($saveid, $savevalueafter) {

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveEx;

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

    $mySaveEx->updateSaveValue($mySave);
}

// insert in Savedaily tbl
function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename) {

    //to use the variable out side the funcion
    global $mySavedaily;
    global $mySavedailyRecord;

    //insert in Savedaily tbl
    $mySavedaily->savedailydate = date("Y-m-d H:i:s");
    $mySavedaily->userid = $_SESSION['userid'];
    $mySavedaily->savedailysavebefore = $savedailysavebefore;
    $mySavedaily->savedailychangeamount = $savedailychangeamount;
    $mySavedaily->savedailychangetype = $savedailychangetype;
    $mySavedaily->saveid = $saveid;
    $mySavedaily->processname = $processname;
    $mySavedaily->savedailymodelid = $savedailymodelid;
    $mySavedaily->savedailysaveafter = $savedailysaveafter;
    $mySavedaily->tablename = $tablename;

    $mySavedailyRecord->insert($mySavedaily);
}

/////////////////////supplier///////////////////////
// update in rawmaterialssuppliers tbl
function updateSupplierDebt($supplierid, $supplierdebtAfter) {

    //to use the variable out side the funcion
    global $myRawmaterialssuppliers;
    global $myRawmaterialssuppliersEx;

    //update rawmaterialssupplierdebt in rawmaterialssuppliers tbl
    $myRawmaterialssuppliers->userid = $_SESSION['userid'];
    $myRawmaterialssuppliers->rawmaterialssupplierdebt = $supplierdebtAfter;
    $myRawmaterialssuppliers->rawmaterialssupplierid = $supplierid;

    $myRawmaterialssuppliersEx->updateSupplierDebt($myRawmaterialssuppliers);
}

/////////////////////////////////store////////////////////////////
// get productquantity from storedetail tbl
function getStoredetailData($storeid, $productid) {

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

    //select data from storerawmaterialdetails by storeid and rawmaterialid
    $storedetailData = $myStoredetailEx->queryWithStoreAndProduct($productid, $storeid);

    $storedetailId = $storedetailData->storedetailid;
    $productquantityBefore = $storedetailData->productquantity;

    return array($storedetailData, $storedetailId, $productquantityBefore);
}

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

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

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

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

    $myStoredetailEx->updateProductquantity($myStoredetail);

    return $productquantityAfter;
}

//update and decrease Rawmaterialamount in storerawmaterialdetails tbl
function decreaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount) {

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

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

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

    $myStoredetailEx->updateProductquantity($myStoredetail);

    return $productquantityAfter;
}

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

    global $myStoredetail;
    global $myStoredetailRecord;

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

    $myStoredetailRecord->insert($myStoredetail);
}

//add in Storemovement tbl
function insertStorereport($productid, $storeid, $productChangeAmount, $productbefore, $productafter, $storereporttype, $storereportmodelid, $processname, $tablename) {
    global $myStorereport;
    global $myStorereportRecord;

    $myStorereport->processname = $processname;
    $myStorereport->productafter = $productafter;
    $myStorereport->productbefore = $productbefore;
    $myStorereport->productquantity = $productChangeAmount;
    $myStorereport->productid = $productid;
    $myStorereport->storeid = $storeid;
    $myStorereport->storereportdate = date("Y-m-d h:m:s");
    $myStorereport->storereportmodelid = $storereportmodelid;
    $myStorereport->storereporttype = $storereporttype;
    $myStorereport->tablename = $tablename;
    $myStorereport->userid = $_SESSION['userid'];

    $myStorereportRecord->insert($myStorereport);
}

///////////////////////////////////clients//////////////////////
// update in rawmaterialssuppliers tbl
function updateClientDebt($clientid, $clientdebtAfter) {

    //to use the variable out side the funcion
    global $myClient;
    global $myClientEx;

    //update clientdebt in client tbl
    $myClient->userid = $_SESSION['userid'];
    $myClient->clientdebt = $clientdebtAfter;
    $myClient->clientid = $clientid;

    $myClientEx->updateClientdebt($myClient);
}

// insert data into Clientdebtchange tbl
function insertClientdebtchange($clientid, $clientdebtchangebefore, $clientdebtchangeamount, $clientdebtchangetype, $processname, $clientdebtchangemodelid, $clientdebtchangeafter, $tablename, $comment, $totalOperationCost) {

    //to use the variable out side the funcion
    global $myClientdebtchange;
    global $myClientdebtchangeRecord;

    $myClientdebtchange->clientdebtchangeafter = $clientdebtchangeafter;
    $myClientdebtchange->clientdebtchangeamount = $clientdebtchangeamount;
    $myClientdebtchange->clientdebtchangebefore = $clientdebtchangebefore;
    $myClientdebtchange->clientdebtchangedate = date("Y-m-d h:m:s");
    $myClientdebtchange->clientdebtchangemodelid = $clientdebtchangemodelid;
    $myClientdebtchange->clientdebtchangetype = $clientdebtchangetype;
    $myClientdebtchange->clientid = $clientid;
    $myClientdebtchange->comment = $comment;
    $myClientdebtchange->processname = $processname;
    $myClientdebtchange->tablename = $tablename;
    $myClientdebtchange->userid = $_SESSION['userid'];
    $myClientdebtchange->totalOperationCost = $totalOperationCost;

    $myClientdebtchangeRecord->insert($myClientdebtchange);
}

function updateSerailDon($productserailid, $don, $billId) {
    global $myProductserial;
    global $myProductserialEx;

    $myProductserial->productserailid = $productserailid;
    $myProductserial->don = $don;
    $myProductserial->sellbillid = $billId;

    $myProductserialEx->updateDonExt($myProductserial);
}

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

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

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

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

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

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

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

function insertIntoSoldSerialProduct($productserailId, $soldQuantity, $sellbillId, $sellbilltype) {
    global $soldSerialProduct;
    global $soldSerialProductDAO;

    $soldSerialProduct->productserailid = $productserailId;
    $soldSerialProduct->quantity = $soldQuantity;
    $soldSerialProduct->sellbilltype = $sellbilltype;
    $soldSerialProduct->sellbillid = $sellbillId;
    $soldSerialProduct->del = 0;
    //print("<br>");
    //print_r($soldSerialProduct);
    $soldSerialProductDAO->insert($soldSerialProduct);
}

function showDetailreturn($sellbillid) {
    global $mySellbillandruternEx;
    global $mySellandruternbilldetailEx;

    //load Sellbillandrutern data by id
    $sellbillandruternData = $mySellbillandruternEx->loadSellbillandruternById($sellbillid);

    $sellbilldetailData = $mySellandruternbilldetailEx->queryWithSellBillIdAndSellType($sellbillid, 0);

    $sellQuantity = 0;
    foreach ($sellbilldetailData as $sellbilldetail) {
        $sellQuantity = $sellQuantity + $sellbilldetail->sellbilldetailquantity;
    }

    $ruternbilldetailData = $mySellandruternbilldetailEx->queryWithSellBillIdAndSellType($sellbillid, 1);

    $returnQuantity = 0;
    foreach ($ruternbilldetailData as $ruternbilldetail) {
        $returnQuantity = $returnQuantity + $ruternbilldetail->sellbilldetailquantity;
    }

    return array($sellbillandruternData, $sellbilldetailData, $ruternbilldetailData, $sellQuantity, $returnQuantity);
}

function addtocostcenter($costamount, $costcenterid, $modelid, $processname, $tablename, $type) {

    $Costcenterdetail->costamount = $costamount;
    $Costcenterdetail->costcenterid = $costcenterid;
    $Costcenterdetail->costdate = date('Y-m-d');
    $Costcenterdetail->del = 0;
    $Costcenterdetail->modelid = $modelid;
    $Costcenterdetail->processname = $processname;
    $Costcenterdetail->tablename = $tablename;
    $Costcenterdetail->type = $type;
    $Costcenterdetail->uesrid = $_SESSION['userid'];

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