<?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");


//here the db files that include in the file
// GOES HERE ....................
include("../public/include_dao.php");
include_once("../library/num_to_ar.php");
include_once("../library/phpqrcode/qrlib.php");

//Sellbill
require_once('../models/dao/SellbillDAO.class.php');
require_once('../models/dto/Sellbill.class.php');
require_once('../models/mysql/SellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillMySqlExtDAO.class.php');

//Sellbilldetail
require_once('../models/dao/SellbilldetailDAO.class.php');
require_once('../models/dto/Sellbilldetail.class.php');
require_once('../models/mysql/SellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbilldetailMySqlExtDAO.class.php');


//Returnsellbill
require_once('../models/dao/ReturnsellbillDAO.class.php');
require_once('../models/dto/Returnsellbill.class.php');
require_once('../models/mysql/ReturnsellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbillMySqlExtDAO.class.php');

//Returnsellbilldetail
require_once('../models/dao/ReturnsellbilldetailDAO.class.php');
require_once('../models/dto/Returnsellbilldetail.class.php');
require_once('../models/mysql/ReturnsellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbilldetailMySqlExtDAO.class.php');

//Sellbillandrutern
require_once('../models/dao/SellbillandruternDAO.class.php');
require_once('../models/dto/Sellbillandrutern.class.php');
require_once('../models/mysql/SellbillandruternMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillandruternMySqlExtDAO.class.php');

//Sellandruternbilldetail
require_once('../models/dao/SellandruternbilldetailDAO.class.php');
require_once('../models/dto/Sellandruternbilldetail.class.php');
require_once('../models/mysql/SellandruternbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SellandruternbilldetailMySqlExtDAO.class.php');

//Storereport
require_once('../models/dao/StorereportDAO.class.php');
require_once('../models/dto/Storereport.class.php');
require_once('../models/mysql/StorereportMySqlDAO.class.php');
require_once('../models/mysql/ext/StorereportMySqlExtDAO.class.php');

//Storedetail
require_once('../models/dao/StoredetailDAO.class.php');
require_once('../models/dto/Storedetail.class.php');
require_once('../models/mysql/StoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/StoredetailMySqlExtDAO.class.php');

//Store
require_once('../models/dao/StoreDAO.class.php');
require_once('../models/dto/Store.class.php');
require_once('../models/mysql/StoreMySqlDAO.class.php');
require_once('../models/mysql/ext/StoreMySqlExtDAO.class.php');

//Product
require_once('../models/dao/ProductDAO.class.php');
require_once('../models/dto/Product.class.php');
require_once('../models/mysql/ProductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductMySqlExtDAO.class.php');



//Save
require_once('../models/dao/SaveDAO.class.php');
require_once('../models/dto/Save.class.php');
require_once('../models/mysql/SaveMySqlDAO.class.php');
require_once('../models/mysql/ext/SaveMySqlExtDAO.class.php');

//Savedaily
require_once('../models/dao/SavedailyDAO.class.php');
require_once('../models/dto/Savedaily.class.php');
require_once('../models/mysql/SavedailyMySqlDAO.class.php');
require_once('../models/mysql/ext/SavedailyMySqlExtDAO.class.php');

//Client
require_once('../models/dao/ClientDAO.class.php');
require_once('../models/dto/Client.class.php');
require_once('../models/mysql/ClientMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientMySqlExtDAO.class.php');

//Clientdebtchange
require_once('../models/dao/ClientdebtchangeDAO.class.php');
require_once('../models/dto/Clientdebtchange.class.php');
require_once('../models/mysql/ClientdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientdebtchangeMySqlExtDAO.class.php');

//Billname
require_once('../models/dao/BillnameDAO.class.php');
require_once('../models/dto/Billname.class.php');
require_once('../models/mysql/BillnameMySqlDAO.class.php');
require_once('../models/mysql/ext/BillnameMySqlExtDAO.class.php');

//Billsetting
require_once('../models/dao/BillsettingsDAO.class.php');
require_once('../models/dto/Billsetting.class.php');
require_once('../models/mysql/BillsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsettingsMySqlExtDAO.class.php');

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

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

//Productcat
require_once('../models/dao/ProductcatDAO.class.php');
require_once('../models/dto/Productcat.class.php');
require_once('../models/mysql/ProductcatMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatMySqlExtDAO.class.php');

//Unit
require_once('../models/dao/UnitDAO.class.php');
require_once('../models/dto/Unit.class.php');
require_once('../models/mysql/UnitMySqlDAO.class.php');
require_once('../models/mysql/ext/UnitMySqlExtDAO.class.php');

//Productserial
require_once('../models/dao/ProductserialDAO.class.php');
require_once('../models/dto/Productserial.class.php');
require_once('../models/mysql/ProductserialMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductserialMySqlExtDAO.class.php');

//Programsetting
require_once('../models/dao/ProgramsettingsDAO.class.php');
require_once('../models/dto/Programsetting.class.php');
require_once('../models/mysql/ProgramsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProgramsettingsMySqlExtDAO.class.php');
////////////////////////////////////////////////////////////////////////////////
//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');
//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');
//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');
//Branch
require_once('../models/dao/BranchDAO.class.php');
require_once('../models/dto/Branch.class.php');
require_once('../models/mysql/BranchMySqlDAO.class.php');
require_once('../models/mysql/ext/BranchMySqlExtDAO.class.php');

//Sellbilldetailoffer
require_once('../models/dao/SellbilldetailofferDAO.class.php');
require_once('../models/dto/Sellbilldetailoffer.class.php');
require_once('../models/mysql/SellbilldetailofferMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbilldetailofferMySqlExtDAO.class.php');
//Sellbilloffer
require_once('../models/dao/SellbillofferDAO.class.php');
require_once('../models/dto/Sellbilloffer.class.php');
require_once('../models/mysql/SellbillofferMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillofferMySqlExtDAO.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');
//Billoperation
require_once('../models/dao/BilloperationDAO.class.php');
require_once('../models/dto/Billoperation.class.php');
require_once('../models/mysql/BilloperationMySqlDAO.class.php');
require_once('../models/mysql/ext/BilloperationMySqlExtDAO.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');
//Currency
require_once('../models/dao/CurrencyDAO.class.php');
require_once('../models/dto/Currency.class.php');
require_once('../models/mysql/CurrencyMySqlDAO.class.php');
require_once('../models/mysql/ext/CurrencyMySqlExtDAO.class.php');
//Returnsellbillcurr
require_once('../models/dao/ReturnsellbillcurrDAO.class.php');
require_once('../models/dto/Returnsellbillcurr.class.php');
require_once('../models/mysql/ReturnsellbillcurrMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbillcurrMySqlExtDAO.class.php');
//Sellbillandruterncurr
require_once('../models/dao/SellbillandruterncurrDAO.class.php');
require_once('../models/dto/Sellbillandruterncurr.class.php');
require_once('../models/mysql/SellbillandruterncurrMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillandruterncurrMySqlExtDAO.class.php');
//Sellbillcurr
require_once('../models/dao/SellbillcurrDAO.class.php');
require_once('../models/dto/Sellbillcurr.class.php');
require_once('../models/mysql/SellbillcurrMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillcurrMySqlExtDAO.class.php');


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

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

  Controller Name :- propertiesCTRL

  OPERTATION in Controller

  1-display add form
  2- add in properity tbl
  3- select data from usergroup tbl
  4-add in relusergroupproperties tbl
  5-display sucess or error

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


//here the global templates
//here goes the instances and general variables
//Sellbill
$mySellbill = new Sellbill();
$mySellbillRecord = new SellbillMySqlDAO();
$mySellbillEx = new SellbillMySqlExtDAO();

//Sellbilldetail
$mySellbilldetail = new Sellbilldetail();
$mySellbilldetailRecord = new SellbilldetailMySqlDAO();
$mySellbilldetailEx = new SellbilldetailMySqlExtDAO();


//Returnsellbill
$myReturnsellbill = new Returnsellbill();
$myReturnsellbillRecord = new ReturnsellbillMySqlDAO();
$myReturnsellbillEx = new ReturnsellbillMySqlExtDAO();

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

//Sellbillandrutern
$mySellbillandrutern = new Sellbillandrutern();
$mySellbillandruternRecord = new SellbillandruternMySqlDAO();
$mySellbillandruternEx = new SellbillandruternMySqlExtDAO();

//Sellandruternbilldetail
$mySellandruternbilldetail = new Sellandruternbilldetail();
$mySellandruternbilldetailRecord = new SellandruternbilldetailMySqlDAO();
$mySellandruternbilldetailEx = new SellandruternbilldetailMySqlExtDAO();
//Storereport
$myStorereport = new Storereport();
$myStorereportRecord = new StorereportMySqlDAO();
$myStorereportEx = new StorereportMySqlExtDAO();

//Storedetail
$myStoredetailEx = new StoredetailMySqlExtDAO();
$myStoredetailRecord = new StoredetailMySqlDAO();

//Store
$myStoreRecord = new StoreMySqlDAO();


//Product
$myProductRecord = new ProductMySqlDAO();
$myProductEx = new ProductMySqlExtDAO();


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

//savedaily
$mySavedaily = new Savedaily();
$mySavedailyRecord = new SavedailyMySqlDAO();
$mySavedailyEx = new SavedailyMySqlExtDAO();

//Client
$myClientRecord = new ClientMySqlDAO();
$myClient = new Client();
$myClientEx = new ClientMySqlExtDAO();


//Clientdebtchange
$myClientdebtchange = new Clientdebtchange();
$myClientdebtchangeRecord = new ClientdebtchangeMySqlDAO();
$clientDeptChangeExt = new ClientdebtchangeMySqlExtDAO();


//Billname
$myBillnameRecord = new BillnameMySqlDAO();
$myBillnameEx = new BillnameMySqlExtDAO();

//Billsetting
$myBillsettingEx = new BillsettingsMySqlExtDAO();

//User
$userDAO = new UserMySqlDAO();
$myUserEx = new UserMySqlExtDAO();

//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();

//Productcat
$myProductcatRecord = new ProductcatMySqlDAO();
$myProductcatEx = new ProductcatMySqlExtDAO();


//Unit
$myUnitRecord = new UnitMySqlDAO();


//Productserial
$myProductserial = new Productserial();
$myProductserialEx = new ProductserialMySqlExtDAO();
////////////////////////////////////////////////////////////////////////////////
//Restauranttable
$restaurantTable = new Restauranttable();
$restaurantTableDAO = new RestauranttableMySqlDAO();
$restaurantTableEX = new RestauranttableMySqlExtDAO();
//Restauranthall
$restaurantHall = new Restauranthall();
$restaurantHallDAO = new RestauranthallMySqlDAO();
$restaurantHallEX = new RestauranthallMySqlExtDAO();
//Restaurantorder
$restaurantOrder = new Restaurantorder();
$restaurantOrderDAO = new RestaurantorderMySqlDAO();
$restaurantOrderEX = new RestaurantorderMySqlExtDAO();
//Restaurantorderdetail
$restaurantOrderDetails = new Restaurantorderdetail();
$restaurantOrderDetailsDAO = new RestaurantorderdetailsMySqlDAO();
$restaurantOrderDetailsEX = new RestaurantorderdetailsMySqlExtDAO();
//Restaurantorderdeliverydetail
$restaurantOrderDeliveryDetail = new Restaurantorderdeliverydetail();
$restaurantOrderDeliveryDetailDAO = new RestaurantorderdeliverydetailsMySqlDAO();
$restaurantOrderDeliveryDetailEX = new RestaurantorderdeliverydetailsMySqlExtDAO();
//Restaurantplaystationplay
$restaurantPlaystationPlay = new Restaurantplaystationplay();
$restaurantPlaystationPlayDAO = new RestaurantplaystationplayMySqlDAO();
$restaurantPlaystationPlayEX = new RestaurantplaystationplayMySqlExtDAO();
//Billoperation
$billOperation = new Billoperation();
$billOperationDAO = new BilloperationMySqlDAO();
$billOperationEX = new BilloperationMySqlExtDAO();
//Branch
$Branch = new Branch();
$BranchDAO = new BranchMySqlDAO();
$BranchEX = new BranchMySqlExtDAO();

//Sellbilldetailoffer
$sellBillDetailOffer = new Sellbilldetailoffer();
$sellBillDetailOfferDAO = new SellbilldetailofferMySqlDAO();
$sellBillDetailOfferEX = new SellbilldetailofferMySqlExtDAO();
//Sellbilloffer
$sellBillOffer = new Sellbilloffer();
$sellBillOfferDAO = new SellbillofferMySqlDAO();
$sellBillOfferEX = new SellbillofferMySqlExtDAO();
//Usergroup
$Usergroup = new Usergroup();
$UsergroupDAO = new UsergroupMySqlDAO();
$UsergroupEX = new UsergroupMySqlExtDAO();
//Currency
$currency = new Currency();
$currencyDAO = new CurrencyMySqlDAO();
$currencyEX = new CurrencyMySqlExtDAO();
//Returnsellbillcurr
$returnSellBillCurr = new Returnsellbillcurr();
$returnSellBillCurrDAO = new ReturnsellbillcurrMySqlDAO();
$returnSellBillCurrEX = new ReturnsellbillcurrMySqlExtDAO();
//Sellbillandruterncurr
$sellBillAndRuternCurr = new Sellbillandruterncurr();
$sellBillAndRuternCurrDAO = new SellbillandruterncurrMySqlDAO();
$sellBillAndRuternCurrEX = new SellbillandruterncurrMySqlExtDAO();
//Sellbillcurr
$sellBillCurr = new Sellbillcurr();
$sellBillCurrDAO = new SellbillcurrMySqlDAO();
$sellBillCurrEX = new SellbillcurrMySqlExtDAO();

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

//check and use the condetion that suite this action


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

//
$Usergroupdata = $UsergroupDAO->load($_SESSION['usergroupid']);
$smarty->assign("Usergroupdata", $Usergroupdata);
if (empty($do)) {
    //here the permssion check
    //include_once("../public/authentication.php");

    $billnameData = loadBillname();
    $smarty->assign("billnameData", $billnameData);


    //here the smarty templates
    $smarty->display("sellbillview/billname.html");
} elseif ($do == "printmultibills") {
    $IDS = filter_input(INPUT_GET, 'id');
    $billType = filter_input(INPUT_GET, 'type');
    $IDS = explode(',', $IDS);
    $itr = 1;
    $billnameid;
    foreach ($IDS as $sellbillId) {
        $billnameid = prepareMultiPrint($sellbillId, $itr);
        $itr++;
    }
    $smarty->assign('noOfBills', $itr);
    $smarty->assign('billnameid', $billnameid);
    $smarty->display("sellbillview/editprint2a4multi.html");
}

//sellbill
elseif ($do == "showDetail2") {

    //here the permssion check
    //include_once("../public/authentication.php");
    // here the function that do the action

    $sellbillId = $_GET['id'];
    $ordertype = $_GET['ordertype'];
    $sellorder = $_GET['sellorder'];
    $smarty->assign('sellorder', $sellorder);

    $showDetailData = showDetail($sellbillId, $ordertype);

    //check if sellbilldetails has many stores
    $manyStores = 0;
    $storeArray = [];
    $loop = 1;
    if (count($showDetailData[1]) > 1) {
        foreach ($showDetailData[1] as $data) {
            if ($loop > 1) {
                if (!in_array($data->storeid, $storeArray)) {
                    $manyStores = 1;
                    break;
                }
            }
            $storeArray[]  = $data->storeid;
            $loop++;
        }
    }
    $smarty->assign('manyStores', $manyStores);

    if ($Programsettingdata->qrerp > 1) {
        $base64qr = base64qr($showDetailData[0]->qrerpid);
        $smarty->assign('base64qr', $base64qr);
        $qrdata = $Programsettingdata->companyname . "\n"
            . 'الرقم الضريبي  : ' . $Programsettingdata->taxcard . "\n"
            . ' العميل  : ' . $showDetailData[0]->sellbillclientname . "\n"
            . '  الرقم الضريبي للعميل  : ' . $showDetailData[0]->taxnumber . "\n"
            . ' رقم الفاتوره  : ' . $showDetailData[0]->sellbillid . "\n"
            . ' التاريخ  ' . $showDetailData[0]->sellbilldate . "\n"
            . ' المبلغ  ' . ($showDetailData[0]->sellbilltotalbill) . "\n"
            . ' الضريبه  ' . ($showDetailData[0]->sellbillaftertotalbill - $showDetailData[0]->sellbilltotalbill) . "\n"
            . ' الاجمالى  ' . $showDetailData[0]->sellbillaftertotalbill;
        $base64qrs = base64qrs($showDetailData[0]->qrerpids, $qrdata, $Programsettingdata->qrcodesh);
        $smarty->assign('base64qrs', $base64qrs);
    }
    $smarty->assign('qrerp', $Programsettingdata->qrerp);

    //$clientdata = $myClientRecord->load($showDetailData[0]->sellbillclientid);
    $clientdata = $myClientEx->loadGetalldata2($showDetailData[0]->sellbillclientid);
    $smarty->assign('clientdata', $clientdata);

    $showDetailData[0]->sellbilldateOnly = explode(" ", $showDetailData[0]->sellbilldate)[0];
    $showDetailData[0]->sellbilltimeOnly = explode(" ", $showDetailData[0]->sellbilldate)[1];
    $smarty->assign('sellbillData', $showDetailData[0]);
    $smarty->assign('billPayments', $showDetailData[3]);
    $billsettingsData = loadBillProperty($showDetailData[0]->billnameid);
    //var_dump($billsettingsData);
    /*
      print_r('<pre>');

      print_r($billsettingsData);
      print_r('<pre>'); */
    if ($billsettingsData[88]->billsettingsvalue == 1) {
        $billsettingsData[60]->billsettingsvalue = 1;
        $showDetailData[1] = collectProductsintoItsCat($showDetailData[1]);
    }

    if (isset($_GET['playstation']) && $_GET['playstation'] == 1) {

        foreach ($showDetailData[1] as $sellbilldetail) {
            //getstart , end time in form H:i
            $sellbilldetail->startTime = date('H:i', strtotime($sellbilldetail->moveStartSysDate)); //date('H:i', strtotime($sellbilldetail->startsysDate));//
            $sellbilldetail->endTime = date('H:i', strtotime($sellbilldetail->endsysDate));

            //calc duration for all time
            $datetime1 = new DateTime($sellbilldetail->moveStartSysDate); //new DateTime($sellbilldetail->startsysDate);
            $datetime2 = new DateTime($sellbilldetail->endsysDate);
            $interval = $datetime1->diff($datetime2);
            $sellbilldetail->duration = $interval->format('%h') . ":" . $interval->format('%i'); //. ":" . $interval->format('%s');
        }
    }
    if ($billsettingsData[69]->billsettingsvalue == 8) {
        $sellbilldetailDatachunk = array_chunk($showDetailData[1], 21, true);
        $smarty->assign('sellbilldetailData', $sellbilldetailDatachunk);
    } else {
        $smarty->assign('sellbilldetailData', $showDetailData[1]);
    }


    $smarty->assign("quantity", $showDetailData[2]);

    $billUserData = $userDAO->load($showDetailData[0]->userid);
    $smarty->assign("billUserData", $billUserData);

    $taxvalue = 0;


    //getalldiscount
    $sellbilldiscount = $showDetailData[0]->sellbilldiscount;
    $sellbilldiscounttype = $showDetailData[0]->sellbilldiscounttype; //1 مباشر
    $sellbilltotalbill = $showDetailData[0]->sellbilltotalbill;
    $sellbillaftertotalbill = $showDetailData[0]->sellbillaftertotalbill;
    $extraDiscountVal = $showDetailData[0]->extraDiscountVal;
    $taxOfDiscountVal = $showDetailData[0]->taxOfDiscountVal;
    $tax = $showDetailData[0]->tax;


    if ($sellbilldiscounttype == 1) {

        //tax
        $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($taxOfDiscountVal + $sellbilldiscount + $extraDiscountVal));
        $discountvalue = $sellbilldiscount;
    } else {
        //discount
        $discountvalue = ($sellbilltotalbill / 100) * $sellbilldiscount;
        //tax
        $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($taxOfDiscountVal + $discountvalue + $extraDiscountVal));
    }

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





    $billnameAddData = $myBillnameRecord->load($showDetailData[0]->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);

    $Programsettingdata = $ProgramsettingDAO->load(1);

    $smarty->assign("Programsettingdata", $Programsettingdata);
    $smarty->assign("currency", $Programsettingdata->currancy);

    $userData = $userDAO->load($_SESSION['userid']);
    $smarty->assign("userData", $userData);
    if ($userData->branchId != 0 && $userData->branchId != -1) {
        $branchData = $BranchDAO->load($userData->branchId);
        $smarty->assign("branchData", $branchData);
    }

    #################
    ##فى حالة العميل نقدى اخفى الدين قبل وبعد المتبقى والمدفوع
    if ($showDetailData[0]->sellbillclientid == 1) {
        $billsettingsData[18]->billsettingsvalue = 1;
        $billsettingsData[19]->billsettingsvalue = 1;
        $billsettingsData[55]->billsettingsvalue = 1;
        $billsettingsData[54]->billsettingsvalue = 1;
    }
    //every html with $billsettingsData[25] value 0 give shape and value 1 give another shape
    //editprint2a4fatma.html is like editprint2.html but total shape is different in backgrounded case
    if (isset($_GET['playstation']) && $_GET['playstation'] == 1) {
        ///////// copy paste from     $do == "printResBill"
        $orderId = (int) $_GET["psOrder"];
        $restaurantOrder = $restaurantOrderDAO->load($orderId);
        $restaurantOrder->opened = strtotime($restaurantOrder->sysdate) - (15 * 60); //this is sysdate 15 minutes ageo
        $restaurantOrder->opened = date("Y-m-d H:i:s", $restaurantOrder->opened);
        $restaurantOrderDetails = $restaurantOrderDetailsEX->queryByOrderIdEX($orderId);
        $userData = $userDAO->load($restaurantOrder->userId);
        $clientFlag = 0;
        if ($restaurantOrder->tableId == -1 || $restaurantOrder->tableId == -2) {
            //check if there is delivery details
            $restaurantOrderDeliveryDetail = $restaurantOrderDeliveryDetailDAO->queryByOrderId($orderId);
            if (count($restaurantOrderDeliveryDetail) > 0) {
                $restaurantOrderDeliveryDetail = clone $restaurantOrderDeliveryDetail[0];
                $client = $myClientRecord->load($restaurantOrderDeliveryDetail->clientId);
                $smarty->assign("client", $client);
                $smarty->assign("delivery", $restaurantOrderDeliveryDetail);
                $clientFlag = 1;
            }
        }
        //tableName
        if ($restaurantOrder->tableId == -2) {
            $restaurantOrder->tableName = 'دليفرى';
        } elseif ($restaurantOrder->tableId == -1) {
            $restaurantOrder->tableName = 'تيك أواى';
        } else {
            $restTable = $restaurantTableDAO->load($restaurantOrder->tableId);
            $restaurantOrder->tableName = $restTable->name;
        }


        //getplaystationpaly data
        $playstation = $restaurantPlaystationPlayDAO->load($restaurantOrder->restaurantplaystationplayid);
        $smarty->assign("playstation", $playstation);

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

        $smarty->assign("userData", $userData);
        $smarty->assign("restaurantOrder", $restaurantOrder);
        $smarty->assign("restaurantOrderDetails", $restaurantOrderDetails);
        ///////// copy paste from     $do == "printResBill" END.

        $billsettingsData[25]->billsettingsvalue = 0;
        $smarty->assign("billsettingsData", $billsettingsData);
        $smarty->display("restaurantplaystationplay/printBill.html");
    } else {
        $ar_number = new convert_ar($showDetailData[0]->sellbillaftertotalbill, "male");
        $totalWritten = $ar_number->convert_number();
        $totalWritten .= ' ' . $Programsettingdata->currancy . ' فقط لاغير';
        $smarty->assign('totalWritten', $totalWritten);
        switch ($billsettingsData[69]->billsettingsvalue) {
            case '0':
                $billsettingsData[25]->billsettingsvalue = 0;
                $smarty->assign("billsettingsData", $billsettingsData);
                $smarty->display("sellbillview/editprint2.html");
                break;
            case '1':
                $billsettingsData[25]->billsettingsvalue = 1;
                $smarty->assign("billsettingsData", $billsettingsData);
                $smarty->display("sellbillview/editprint2.html");
                break;
            case '2':
                $billsettingsData[25]->billsettingsvalue = 0;
                $smarty->assign("billsettingsData", $billsettingsData);
                $smarty->display("sellbillview/deltaeditprint2.html");
                break;
            case '3':
                $billsettingsData[25]->billsettingsvalue = 1;
                $smarty->assign("billsettingsData", $billsettingsData);
                $smarty->display("sellbillview/deltaeditprint2.html");
                break;
            case '4': //this case is like case 0 but total shape is diffrent
                $billsettingsData[25]->billsettingsvalue = 0;

                $sellbilldetail->sellbilldetailprice = (float) $sellbilldetail->sellbilldetailprice;

                $smarty->assign("billsettingsData", $billsettingsData);
                $smarty->display("sellbillview/editprint2a4fatma.html");
                break;
            case '5': //this case is like case 0 but total shape is diffrent
                //
                $smarty->assign("billsettingsData", $billsettingsData);
                $smarty->display("sellbillview/print-abozied.html");
                break;
            case '6': //this case is like case 0 but total shape is diffrent
                $smarty->assign("billsettingsData", $billsettingsData);
                $smarty->display("sellbillview/print-abozied2.html");
                break;
            case '7': //ايصال كبير
                $billsettingsData[25]->billsettingsvalue = 1;
                $smarty->assign("billsettingsData", $billsettingsData);

                $smarty->display("sellbillview/editprint2a4.html");
                break;
            case '8': //ايصال كبير
                $billsettingsData[25]->billsettingsvalue = 0;
                $smarty->assign("billsettingsData", $billsettingsData);
                $smarty->display("sellbillview/print9.html");
                break;

            case '9':
                //last payed dept
                $sql = "AND (clientdebtchange.tablename = 'premiumController.php' or clientdebtchange.tablename = 'clientPayedDeptController.php' or (clientdebtchange.tablename = 'sellbillController.php' and clientdebtchangemodelid != " . $showDetailData[0]->sellbillid . "))";
                $lastPayment = $clientDeptChangeExt->selectByClientIdOrderByDateDESC($showDetailData[0]->sellbillclientid, $sql);
                if ($lastPayment->tablename == "sellbillController.php")
                    $lastPayment->clientdebtchangeamount = abs($lastPayment->totalOperationCost) - abs($lastPayment->clientdebtchangeamount);
                $smarty->assign("lastPayment", $lastPayment);
                //
                $smarty->assign("billsettingsData", $billsettingsData);
                $smarty->display("sellbillview/print10.html");
                break;

                //by def use case 0
            default:
                $billsettingsData[25]->billsettingsvalue = 0;
                $smarty->assign("billsettingsData", $billsettingsData);
                $smarty->display("sellbillview/editprint2.html");
                break;
        }
    }
    //    if ($billsettingsData[66]->billsettingsvalue == 0) {
    //        $smarty->display("sellbillview/editprint2a4fatma.html");
    //    } else
    //    if ($billsettingsData[35]->billsettingsvalue == 0) {
    //        $smarty->display("sellbillview/deltaeditprint2.html");
    //    } else {
    //        //here the smarty templates
    //        $smarty->display("sellbillview/editprint2.html");
    //    }
} elseif ($do == "showDetail2Bulk") {

    //here the permssion check
    //include_once("../public/authentication.php");
    // here the function that do the action

    $sellbillId = $_GET['id'];
    $sellbillId = trim($sellbillId, ",");

    $showDetailData = showDetailBulk($sellbillId);
    $clientdata = $myClientRecord->load($showDetailData[0]->sellbillclientid);

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

    $smarty->assign('sellbillData', $showDetailData[0]);
    $smarty->assign('sellbilldetailData', $showDetailData[1]);
    $smarty->assign("quantity", $showDetailData[2]);

    $billUserData = $userDAO->load($showDetailData[0]->userid);
    $smarty->assign("billUserData", $billUserData);

    $taxvalue = 0;


    //getalldiscount
    $sellbilldiscount = $showDetailData[0]->sellbilldiscount;
    $sellbilldiscounttype = $showDetailData[0]->sellbilldiscounttype; //1 مباشر
    $sellbilltotalbill = $showDetailData[0]->sellbilltotalbill;
    $sellbillaftertotalbill = $showDetailData[0]->sellbillaftertotalbill;
    $extraDiscountVal = $showDetailData[0]->extraDiscountVal;
    $tax = $showDetailData[0]->tax;


    if ($sellbilldiscounttype == 1) {

        //tax
        $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($sellbilldiscount + $extraDiscountVal));
    } else {
        //discount
        $discountvalue = ($sellbilltotalbill / 100) * $sellbilldiscount;
        //tax
        $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($discountvalue + $extraDiscountVal));
    }

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



    $billsettingsData = loadBillProperty($showDetailData[0]->billnameid);

    /*
      print_r('<pre>');

      print_r($billsettingsData);
      print_r('<pre>'); */

    $clientdata = $myClientRecord->load($showDetailData[0]->sellbillclientid);
    //  print_r($clientdata);
    $smarty->assign("clientdata", $clientdata);

    $billnameAddData = $myBillnameRecord->load($showDetailData[0]->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);

    $Programsettingdata = $ProgramsettingDAO->load(1);

    $smarty->assign("Programsettingdata", $Programsettingdata);
    $smarty->assign("currency", $Programsettingdata->currancy);

    $userData = $userDAO->load($_SESSION['userid']);
    $smarty->assign("userData", $userData);
    if ($userData->branchId != 0 && $userData->branchId != -1) {
        $branchData = $BranchDAO->load($userData->branchId);
        $smarty->assign("branchData", $branchData);
    }

    #################
    ##فى حالة العميل نقدى اخفى الدين قبل وبعد المتبقى والمدفوع
    if ($showDetailData[0]->sellbillclientid == 1) {
        $billsettingsData[18]->billsettingsvalue = 1;
        $billsettingsData[19]->billsettingsvalue = 1;
        $billsettingsData[55]->billsettingsvalue = 1;
        $billsettingsData[54]->billsettingsvalue = 1;
    }
    //every html with $billsettingsData[25] value 0 give shape and value 1 give another shape
    //editprint2a4fatma.html is like editprint2.html but total shape is different in backgrounded case
    switch ($billsettingsData[69]->billsettingsvalue) {
        case '0':
            $billsettingsData[25]->billsettingsvalue = 0;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillview/editprint2.html");
            break;
        case '1':
            $billsettingsData[25]->billsettingsvalue = 1;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillview/editprint2.html");
            break;
        case '2':
            $billsettingsData[25]->billsettingsvalue = 0;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillview/deltaeditprint2.html");
            break;
        case '3':
            $billsettingsData[25]->billsettingsvalue = 1;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillview/deltaeditprint2.html");
            break;
        case '4': //this case is like case 0 but total shape is diffrent
            $billsettingsData[25]->billsettingsvalue = 0;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillview/editprint2a4fatma.html");
            break;
        case '5': //this case is like case 0 but total shape is diffrent
            $ar_number = new convert_ar($showDetailData[0]->sellbillaftertotalbill, "male");
            $totalWritten = $ar_number->convert_number();
            $totalWritten .= ' ' . $Programsettingdata->currancy . ' فقط لاغير';
            $smarty->assign('totalWritten', $totalWritten);
            //
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillview/print-abozied.html");
            break;
        case '6': //this case is like case 0 but total shape is diffrent
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillview/print-abozied2.html");
            break;
        case '7': //ايصال كبير
            $billsettingsData[25]->billsettingsvalue = 1;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillview/editprint2a4.html");
            break;
        case '8': //ايصال كبير
            $billsettingsData[25]->billsettingsvalue = 0;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillview/print9.html");
            break;

            //this case is repeated like case 2
            //        case 'xxxxxxxxx'://
            //            $billsettingsData[25]->billsettingsvalue = 1;
            //            $smarty->assign("billsettingsData", $billsettingsData);
            //            $smarty->display("sellbillview/editprint2a4fatma.html");
            //            break;
            //by def use case 0
        default:
            $billsettingsData[25]->billsettingsvalue = 0;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillview/editprint2.html");
            break;
    }
    //    if ($billsettingsData[66]->billsettingsvalue == 0) {
    //        $smarty->display("sellbillview/editprint2a4fatma.html");
    //    } else
    //    if ($billsettingsData[35]->billsettingsvalue == 0) {
    //        $smarty->display("sellbillview/deltaeditprint2.html");
    //    } else {
    //        //here the smarty templates
    //        $smarty->display("sellbillview/editprint2.html");
    //    }
} elseif ($do == "showDetail3") {

    //here the permssion check
    //include_once("../public/authentication.php");
    // here the function that do the action

    $sellbillId = $_GET['id'];
    $totaltax = 0;

    $showDetailData = showDetail($sellbillId);

    $clientdata = $myClientRecord->load($showDetailData[0]->sellbillclientid);

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

    $smarty->assign('sellbillData', $showDetailData[0]);
    $smarty->assign('sellbilldetailData', $showDetailData[1]);
    $smarty->assign("quantity", $showDetailData[2]);
    $smarty->assign('billPayments', $showDetailData[3]);

    if (count($showDetailData[0]) > 0) {

        //getalldiscount
        $sellbilldiscount = $showDetailData[0]->sellbilldiscount;
        $sellbilldiscounttype = $showDetailData[0]->sellbilldiscounttype; //1 مباشر
        $sellbilltotalbill = $showDetailData[0]->sellbilltotalbill;
        $sellbillaftertotalbill = $showDetailData[0]->sellbillaftertotalbill;
        $extraDiscountVal = $showDetailData[0]->extraDiscountVal;
        $tax = $showDetailData[0]->tax;
        if ($sellbilldiscounttype == 1) {

            //tax
            $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($sellbilldiscount + $extraDiscountVal));
            $discountvalue = $sellbilldiscount;
            $totaltax = $taxvalue;
        } else {
            //discount
            $discountvalue = ($sellbilltotalbill / 100) * $sellbilldiscount;
            //tax
            $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($discountvalue + $extraDiscountVal));
            $totaltax = $taxvalue;
        }

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

    //check if sellbilldetails has many stores
    $manyStores = 0;
    $storeArray = [];
    $loop = 1;
    if (count($showDetailData[1]) > 1) {
        foreach ($showDetailData[1] as $data) {
            if ($loop > 1) {
                if (!in_array($data->storeid, $storeArray)) {
                    $manyStores = 1;
                    break;
                }
            }
            $storeArray[]  = $data->storeid;
            $loop++;
        }
    }
    $smarty->assign('manyStores', $manyStores);

    $billnameAddData = $myBillnameRecord->load($showDetailData[0]->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);

    $billsettingsData = loadBillProperty($showDetailData[0]->billnameid);
    $smarty->assign("billsettingsData", $billsettingsData);


    $billnameAddData = $myBillnameRecord->load($showDetailData[0]->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);

    $Programsettingdata = $ProgramsettingDAO->load(1);
    $smarty->assign("Programsettingdata", $Programsettingdata);
    //here the smarty templates
    $smarty->display("sellbillview/editprint2a4.html");
}

//return sellbill
elseif ($do == "returnshowDetail") {
    //here the permssion check
    // here the function that do the action
    $returnsellbillId = $_GET['id'];

    $showDetailData = returnsshowDetail($returnsellbillId);
    $smarty->assign('returnsellbillData', $showDetailData[0]);
    $smarty->assign('returnsellbilldetailData', $showDetailData[1]);
    $smarty->assign('quantity', $showDetailData[2]);
    //getalldiscount

    $taxvalue = 0;
    $sellbilldiscount = $showDetailData[0]->returnsellbilldiscount;
    $sellbilldiscounttype = $showDetailData[0]->returnsellbilldiscounttype; //1 مباشر
    $sellbilltotalbill = $showDetailData[0]->returnsellbilltotalbill;
    $sellbillaftertotalbill = $showDetailData[0]->returnsellbillaftertotalbill;
    $extraDiscountVal = $showDetailData[0]->extraDiscountVal;
    $tax = $showDetailData[0]->tax;


    $billUserData = $userDAO->load($showDetailData[0]->userid);
    $smarty->assign("billUserData", $billUserData);

    if ($sellbilldiscounttype == 1) {

        //tax
        $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($sellbilldiscount + $extraDiscountVal));
        $discountvalue = $sellbilldiscount;
    } else {
        //discount
        $discountvalue = ($sellbilltotalbill / 100) * $sellbilldiscount;
        //tax
        $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($discountvalue + $extraDiscountVal));
    }

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

    $billsettingsData = loadBillProperty($showDetailData[0]->billnameid);
    $smarty->assign("billsettingsData", $billsettingsData);
    //    var_dump($billsettingsData);

    if ($billsettingsData[88]->billsettingsvalue == 1) {
        $billsettingsData[60]->billsettingsvalue = 1;
        $showDetailData[1] = collectProductsintoItsCat($showDetailData[1]);
    }

    $billnameAddData = $myBillnameRecord->load($showDetailData[0]->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);

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

    $clientdata = $myClientRecord->load($showDetailData[0]->returnsellbillclientid);

    //  print_r($Programsettingdata);
    $smarty->assign("clientdata", $clientdata);

    $userData = $userDAO->load($_SESSION['userid']);
    $smarty->assign("userData", $userData);
    if ($userData->branchId != 0 && $userData->branchId != -1) {
        $branchData = $BranchDAO->load($userData->branchId);
        $smarty->assign("branchData", $branchData);
    }

    #################
    ##فى حالة العميل نقدى اخفى الدين قبل وبعد المتبقى والمدفوع
    if ($showDetailData[0]->returnsellbillclientid == 1) {
        $billsettingsData[18]->billsettingsvalue = 1;
        $billsettingsData[19]->billsettingsvalue = 1;
        $billsettingsData[55]->billsettingsvalue = 1;
        $billsettingsData[54]->billsettingsvalue = 1;
    }

    switch ($billsettingsData[69]->billsettingsvalue) {
        case '0':
            $billsettingsData[25]->billsettingsvalue = 0;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("returnsellbillview/editprint2.html");
            break;
        case '1':
            $billsettingsData[25]->billsettingsvalue = 1;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("returnsellbillview/editprint2.html");
            break;
        case '2':
            $billsettingsData[25]->billsettingsvalue = 0;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("returnsellbillview/deltaeditprint2.html");
            break;
        case '3':
            $billsettingsData[25]->billsettingsvalue = 1;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("returnsellbillview/deltaeditprint2.html");
            break;

        case '5': //this case is like case 0 but total shape is diffrent
            //
            $ar_number = new convert_ar(abs($showDetailData[0]->returnsellbillaftertotalbill), "male");
            $totalWritten = $ar_number->convert_number();
            $totalWritten .= ' ' . $Programsettingdata->currancy . ' فقط لاغير';
            $smarty->assign('totalWritten', $totalWritten);
            //
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("returnsellbillview/print-abozied.html");
            break;
        case '6': //this case is like case 0 but total shape is diffrent
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("returnsellbillview/print-abozied2.html");
            break;
        case '7': //ايصال كبير
            $billsettingsData[25]->billsettingsvalue = 1;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("returnsellbillview/editprint2a4.html");
            break;
            //by def use case 0
        default:
            $billsettingsData[25]->billsettingsvalue = 0;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("returnsellbillview/editprint2.html");
            break;
    }
    //    if ($billsettingsData[70]->billsettingsvalue == 0) {
    //        $smarty->display("returnsellbillview/editprint2a4fatma.html");
    //    } elseif ($billsettingsData[35]->billsettingsvalue == 0) {
    //        $smarty->display("returnsellbillview/deltaeditprint2.html");
    //    } else {
    //        //here the smarty templates
    //        $smarty->display("returnsellbillview/editprint2.html");
    //    }
} elseif ($do == "returnshowDetail1") {
    //here the permssion check
    // here the function that do the action
    $returnsellbillId = $_GET['id'];

    $showDetailData = returnsshowDetail($returnsellbillId);
    $smarty->assign('returnsellbillData', $showDetailData[0]);
    $smarty->assign('returnsellbilldetailData', $showDetailData[1]);
    $smarty->assign('quantity', $showDetailData[2]);

    $taxvalue = 0;
    $sellbilldiscount = $showDetailData[0]->returnsellbilldiscount;
    $sellbilldiscounttype = $showDetailData[0]->returnsellbilldiscounttype; //1 مباشر
    $sellbilltotalbill = $showDetailData[0]->returnsellbilltotalbill;
    $sellbillaftertotalbill = $showDetailData[0]->returnsellbillaftertotalbill;
    $extraDiscountVal = $showDetailData[0]->extraDiscountVal;
    $tax = $showDetailData[0]->tax;

    if ($sellbilldiscounttype == 1) {

        //tax
        $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($sellbilldiscount + $extraDiscountVal));
        $discountvalue = $sellbilldiscount;
    } else {
        //discount
        $discountvalue = ($sellbilltotalbill / 100) * $sellbilldiscount;
        //tax
        $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($discountvalue + $extraDiscountVal));
    }

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

    $billsettingsData = loadBillProperty($showDetailData[0]->billnameid);
    $smarty->assign("billsettingsData", $billsettingsData);


    $billnameAddData = $myBillnameRecord->load($showDetailData[0]->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);

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


    //here the smarty templates
    //here the smarty templates
    $clientdata = $myClientRecord->load($showDetailData[0]->sellbillclientid);
    //  print_r($clientdata);
    $smarty->assign("clientdata", $clientdata);
    //  print_r('4444444444444444444444444'.$billsettingsData[35]->billsettingsvalue );
    if (($billsettingsData[35]->billsettingsvalue) == 0) {
        $smarty->display("returnsellbillview/deltaeditprint2.html");
        //$smarty->display("returnsellbillview/editprint2a4.html");
    } elseif (($billsettingsData[35]->billsettingsvalue) == 1) {
        //here the smarty templates
        //$smarty->display("returnsellbillview/editprint2.html");
        $smarty->display("returnsellbillview/editprint2a4.html");
    }
}




//sell and return sellbill
elseif ($do == "returnandselshowDetail") {
    //here the permssion check
    // here the function that do the action

    $sellbillId = $_GET['id'];
    $totaltax = 0;

    $showDetailData = sellbillandruternshowDetail($sellbillId);
    $smarty->assign('sellbillandruternData', $showDetailData[0]);
    $smarty->assign('sellbilldetailData', $showDetailData[1]);
    $smarty->assign('ruternbilldetailData', $showDetailData[2]);
    $smarty->assign('sellQuantity', $showDetailData[3]);
    $smarty->assign('returnQuantity', $showDetailData[4]);

    if (count($showDetailData[0]) > 0) {

        //getalldiscount
        $sellbilldiscount = $showDetailData[0]->sellbilldiscount;
        $sellbilldiscounttype = $showDetailData[0]->sellbilldiscounttype; //1 مباشر
        $sellbilltotalbill = $showDetailData[0]->sellbilltotalbill;
        $sellbillaftertotalbill = $showDetailData[0]->sellbillaftertotalbill;
        $extraDiscountVal = $showDetailData[0]->extraDiscountVal;
        $tax = $showDetailData[0]->tax;
        if ($sellbilldiscounttype == 1) {

            //tax
            $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($sellbilldiscount + $extraDiscountVal));
            $totaltax = $taxvalue;
            $discountvalue = $sellbilldiscount;
        } else {
            //discount
            $discountvalue = ($sellbilltotalbill / 100) * $sellbilldiscount;
            //tax
            $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($discountvalue + $extraDiscountVal));
            $totaltax = $taxvalue;
        }

        $smarty->assign('totaltax', $totaltax);
        $smarty->assign('discountvalue', $discountvalue);
    }
    $billsettingsData = loadBillProperty($showDetailData[0]->billnameid);



    $billnameAddData = $myBillnameRecord->load($showDetailData[0]->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);


    //here the smarty templates


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


    //here the smarty templates
    $clientdata = $myClientRecord->load($showDetailData[0]->sellbillclientid);
    //  print_r($clientdata);
    $smarty->assign("clientdata", $clientdata);

    $userData = $userDAO->load($_SESSION['userid']);
    $smarty->assign("userData", $userData);
    if ($userData->branchId != 0 && $userData->branchId != -1) {
        $branchData = $BranchDAO->load($userData->branchId);
        $smarty->assign("branchData", $branchData);
    }

    #################
    ##فى حالة العميل نقدى اخفى الدين قبل وبعد المتبقى والمدفوع
    if ($showDetailData[0]->sellbillclientid == 1) {
        $billsettingsData[18]->billsettingsvalue = 1;
        $billsettingsData[19]->billsettingsvalue = 1;
        $billsettingsData[55]->billsettingsvalue = 1;
        $billsettingsData[54]->billsettingsvalue = 1;
    }
    switch ($billsettingsData[69]->billsettingsvalue) {
        case '0':
            $billsettingsData[25]->billsettingsvalue = 0;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillandruternview/editprint2.html");
            break;
        case '1':
            $billsettingsData[25]->billsettingsvalue = 1;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillandruternview/editprint2.html");
            break;
        case '2':
            $billsettingsData[25]->billsettingsvalue = 0;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillandruternview/deltaeditprint2.html");
            break;
        case '3':
            $billsettingsData[25]->billsettingsvalue = 1;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillandruternview/deltaeditprint2.html");
            break;
        case '5': //this case is like case 0 but total shape is diffrent
            //
            $ar_number = new convert_ar(abs($showDetailData[0]->sellbillaftertotalbill), "male");
            $totalWritten = $ar_number->convert_number();
            $totalWritten .= ' ' . $Programsettingdata->currancy . ' فقط لاغير';
            $smarty->assign('totalWritten', $totalWritten);
            //
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillandruternview/print-abozied.html");
            break;
        case '6': //this case is like case 0 but total shape is diffrent
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillandruternview/print-abozied2.html");
            break;
        case '7': //ايصال كبير
            $billsettingsData[25]->billsettingsvalue = 1;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillandruternview/editprint2a4.html");
            break;
            //by def use case 0
        default:
            $billsettingsData[25]->billsettingsvalue = 0;
            $smarty->assign("billsettingsData", $billsettingsData);
            $smarty->display("sellbillandruternview/editprint2.html");
            break;
    }
    //    if ($billsettingsData[35]->billsettingsvalue == 0) {
    //        $smarty->display("sellbillandruternview/deltaeditprint2.html");
    //    } else {
    //        //here the smarty templates
    //        $smarty->display("sellbillandruternview/editprint2.html");
    //    }
} elseif ($do == "returnandselshowDetail2") {
    //here the permssion check
    // here the function that do the action

    $sellbillId = $_GET['id'];
    $totaltax = 0;

    $showDetailData = sellbillandruternshowDetail($sellbillId);
    $smarty->assign('sellbillandruternData', $showDetailData[0]);
    $smarty->assign('sellbilldetailData', $showDetailData[1]);
    $smarty->assign('ruternbilldetailData', $showDetailData[2]);
    $smarty->assign('sellQuantity', $showDetailData[3]);
    $smarty->assign('returnQuantity', $showDetailData[4]);


    $billsettingsData = loadBillProperty($showDetailData[0]->billnameid);
    $smarty->assign("billsettingsData", $billsettingsData);

    if (count($showDetailData[0]) > 0) {

        //getalldiscount
        $sellbilldiscount = $showDetailData[0]->sellbilldiscount;
        $sellbilldiscounttype = $showDetailData[0]->sellbilldiscounttype; //1 مباشر
        $sellbilltotalbill = $showDetailData[0]->sellbilltotalbill;
        $sellbillaftertotalbill = $showDetailData[0]->sellbillaftertotalbill;
        $extraDiscountVal = $showDetailData[0]->extraDiscountVal;
        $tax = $showDetailData[0]->tax;
        if ($sellbilldiscounttype == 1) {

            //tax
            $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($sellbilldiscount + $extraDiscountVal));
            $totaltax = $taxvalue;
            $discountvalue = $sellbilldiscount;
        } else {
            //discount
            $discountvalue = ($sellbilltotalbill / 100) * $sellbilldiscount;
            //tax
            $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($discountvalue + $extraDiscountVal));
            $totaltax = $taxvalue;
        }

        $smarty->assign('totaltax', $totaltax);
        $smarty->assign('discountvalue', $discountvalue);
    }

    $billnameAddData = $myBillnameRecord->load($showDetailData[0]->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);



    //here the smarty templates


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



    //here the smarty templates
    $smarty->display("sellbillandruternview/editprint2a4.html");
} elseif ($do == "returnshowpermission") {
    //here the permssion check
    // here the function that do the action

    $sellbillId = $_GET['id'];

    $showDetailData = sellbillandruternshowDetail($sellbillId);
    $smarty->assign('sellbillandruternData', $showDetailData[0]);
    $smarty->assign('sellbilldetailData', $showDetailData[1]);
    $smarty->assign('ruternbilldetailData', $showDetailData[2]);
    $smarty->assign('sellQuantity', $showDetailData[3]);
    $smarty->assign('returnQuantity', $showDetailData[4]);


    $billsettingsData = loadBillProperty($showDetailData[0]->billnameid);
    $smarty->assign("billsettingsData", $billsettingsData);



    $billnameAddData = $myBillnameRecord->load($showDetailData[0]->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);



    //here the smarty templates


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


    //here the smarty templates
    $smarty->display("sellbillandruternview/editpermission.html");
} elseif ($do == "returnshowmorepermission") {
    //here the permssion check
    // here the function that do the action

    $sellbillId = $_GET['id'];

    returnshowmorepermission($sellbillId);




    //here the smarty templates
    $Programsettingdata = $ProgramsettingDAO->load(1);
    $smarty->assign("Programsettingdata", $Programsettingdata);


    //here the smarty templates
    $smarty->display("sellbillandruternview/editpermissionmore.html");
} elseif ($do == "showpermission") {

    //here the permssion check
    //include_once("../public/authentication.php");
    // here the function that do the action

    $sellbillId = $_GET['id'];

    $showDetailData = showDetail($sellbillId);

    $smarty->assign('sellbillData', $showDetailData[0]);
    $smarty->assign('sellbilldetailData', $showDetailData[1]);
    $smarty->assign("quantity", $showDetailData[2]);

    //check if sellbilldetails has many stores
    $manyStores = 0;
    $storeArray = [];
    $loop = 1;
    if (count($showDetailData[1]) > 1) {
        foreach ($showDetailData[1] as $data) {
            if ($loop > 1) {
                if (!in_array($data->storeid, $storeArray)) {
                    $manyStores = 1;
                    break;
                }
            }
            $storeArray[]  = $data->storeid;
            $loop++;
        }
    }
    $smarty->assign('manyStores', $manyStores);


    $billsettingsData = loadBillProperty($showDetailData[0]->billnameid);
    $smarty->assign("billsettingsData", $billsettingsData);



    $billnameAddData = $myBillnameRecord->load($showDetailData[0]->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);

    $Programsettingdata = $ProgramsettingDAO->load(1);
    $smarty->assign("Programsettingdata", $Programsettingdata);
    //here the smarty templates
    $smarty->display("sellbillview/editpermission.html");
} elseif ($do == "showmorepermission") {

    //here the permssion check
    //include_once("../public/authentication.php");
    // here the function that do the action

    $sellbillId = $_GET['id'];

    showmorepermission($sellbillId);

    /* $smarty->assign('sellbillData',$showDetailData[0]);
      $smarty->assign('sellbilldetailData',$showDetailData[1]);
      $smarty->assign("quantity",$showDetailData[2]);
     */




    $Programsettingdata = $ProgramsettingDAO->load(1);
    $smarty->assign("Programsettingdata", $Programsettingdata);
    //here the smarty templates
    $smarty->display("sellbillview/editpermissionmore.html");
} elseif ($do == "sucess") {

    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {

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

//print restaurant
elseif ($do == "printResBill") {
    $orderId = (int) $_GET["id"];
    $restaurantOrder = $restaurantOrderDAO->load($orderId);
    $restaurantOrder->opened = strtotime($restaurantOrder->sysdate) - (15 * 60); //this is sysdate 15 minutes ageo
    $restaurantOrder->opened = date("Y-m-d H:i:s", $restaurantOrder->opened);
    $restaurantOrderDetails = $restaurantOrderDetailsEX->queryByOrderIdEX($orderId);
    $userData = $userDAO->load($restaurantOrder->userId);
    $clientFlag = 0;
    if ($restaurantOrder->tableId == -1 || $restaurantOrder->tableId == -2) {
        //check if there is delivery details
        $restaurantOrderDeliveryDetail = $restaurantOrderDeliveryDetailDAO->queryByOrderId($orderId);
        if (count($restaurantOrderDeliveryDetail) > 0) {
            $restaurantOrderDeliveryDetail = clone $restaurantOrderDeliveryDetail[0];
            $client = $myClientRecord->load($restaurantOrderDeliveryDetail->clientId);
            $smarty->assign("client", $client);
            $smarty->assign("delivery", $restaurantOrderDeliveryDetail);
            $clientFlag = 1;
        }
    }
    //tableName
    if ($restaurantOrder->tableId == -2) {
        $restaurantOrder->tableName = 'دليفرى';
    } elseif ($restaurantOrder->tableId == -1) {
        $restaurantOrder->tableName = 'تيك أواى';
    } else {
        $restTable = $restaurantTableDAO->load($restaurantOrder->tableId);
        $restaurantOrder->tableName = $restTable->name;
    }


    //getplaystationpaly data
    $playstation = $restaurantPlaystationPlayDAO->load($restaurantOrder->restaurantplaystationplayid);
    $smarty->assign("playstation", $playstation);



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

    $smarty->assign("userData", $userData);
    $smarty->assign("restaurantOrder", $restaurantOrder);
    $smarty->assign("restaurantOrderDetails", $restaurantOrderDetails);
    $smarty->assign("showserial", $Programsettingdata->showserial);
    $smarty->assign("Programsettingdata", $Programsettingdata);


    $sellbillData = $mySellbillRecord->load($restaurantOrder->sellBillId);
    if ($Programsettingdata->qrerp > 1) {
        $clientdata = $myClientRecord->load($sellbillData->sellbillclientid);
        $base64qr = base64qr($sellbillData->qrerpid);
        $smarty->assign('base64qr', $base64qr);
        $qrdata = $Programsettingdata->companyname . "\n"
            . 'الرقم الضريبي  : ' . $Programsettingdata->taxcard . "\n"
            . ' العميل  : ' . $clientdata->clientname . "\n"
            . ' رقم  الضريبه  : ' . $clientdata->taxnumber . "\n"
            . ' رقم الفاتوره  : ' . $sellbillData->sellbillid . "\n"
            . ' التاريخ  ' . $sellbillData->sellbilldate . "\n"
            . ' المبلغ  ' . ($sellbillData->sellbilltotalpayed - $sellbillData->tax) . "\n"
            . ' الضريبه  ' . $sellbillData->tax . "\n"
            . ' الاجمالى  ' . $sellbillData->sellbilltotalpayed;
        $base64qrs = base64qrs($sellbillData->qrerpids, $qrdata, $Programsettingdata->qrcodesh);
        $smarty->assign('base64qrs', $base64qrs);
    }
    $smarty->assign('sellbillData', $sellbillData);
    $smarty->assign('qrerp', $Programsettingdata->qrerp);
    if ($Programsettingdata->numberprint == 1) {
        $smarty->display("resturant/printBill2.html");
    } else {
        if ($Programsettingdata->restPrintLang == 0) {
            $smarty->display("resturant/printBill.html");
        } else {
            $smarty->display("resturant/printBillEn.html");
        }
    }
} elseif ($do == "printResBillonly") {
    $tableid = (int) $_GET["id"];
    $billTax =  $_GET["billTax"];
    $smarty->assign("billTax", $billTax);
    $smarty->assign("printResBillonly", 1);
    $restaurantOrder = $restaurantOrderEX->queryOrderGetByTableEX($tableid);
    $orderId = $restaurantOrder->id;
    $restaurantOrder->opened = strtotime($restaurantOrder->sysdate) - (15 * 60); //this is sysdate 15 minutes ageo
    $restaurantOrder->opened = date("Y-m-d H:i:s", $restaurantOrder->opened);
    $restaurantOrderDetails = $restaurantOrderDetailsEX->queryByOrderIdEX($orderId);
    $userData = $userDAO->load($restaurantOrder->userId);
    $clientFlag = 0;
    if ($restaurantOrder->tableId == -1 || $restaurantOrder->tableId == -2) {
        //check if there is delivery details
        $restaurantOrderDeliveryDetail = $restaurantOrderDeliveryDetailDAO->queryByOrderId($orderId);
        if (count($restaurantOrderDeliveryDetail) > 0) {
            $restaurantOrderDeliveryDetail = clone $restaurantOrderDeliveryDetail[0];
            $client = $myClientRecord->load($restaurantOrderDeliveryDetail->clientId);
            $smarty->assign("client", $client);
            $smarty->assign("delivery", $restaurantOrderDeliveryDetail);
            $clientFlag = 1;
        }
    }
    //tableName
    if ($restaurantOrder->tableId == -2) {
        $restaurantOrder->tableName = 'دليفرى';
    } elseif ($restaurantOrder->tableId == -1) {
        $restaurantOrder->tableName = 'تيك أواى';
    } else {
        $restTable = $restaurantTableDAO->load($restaurantOrder->tableId);
        $restaurantOrder->tableName = $restTable->name;
    }


    //getplaystationpaly data
    $playstation = $restaurantPlaystationPlayDAO->load($restaurantOrder->restaurantplaystationplayid);
    $smarty->assign("playstation", $playstation);



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

    $smarty->assign("userData", $userData);
    $smarty->assign("restaurantOrder", $restaurantOrder);
    $smarty->assign("restaurantOrderDetails", $restaurantOrderDetails);
    $smarty->assign("showserial", $Programsettingdata->showserial);
    $smarty->assign("Programsettingdata", $Programsettingdata);


    $sellbillData = $mySellbillRecord->load($restaurantOrder->sellBillId);
    if ($Programsettingdata->qrerp > 1) {
        $clientdata = $myClientRecord->load($sellbillData->sellbillclientid);
        $base64qr = base64qr($sellbillData->qrerpid);
        $smarty->assign('base64qr', $base64qr);
        $qrdata = $Programsettingdata->companyname . "\n"
            . 'الرقم الضريبي  : ' . $Programsettingdata->taxcard . "\n"
            . ' العميل  : ' . $clientdata->clientname . "\n"
            . ' رقم  الضريبه  : ' . $clientdata->taxnumber . "\n"
            . ' رقم الفاتوره  : ' . $sellbillData->sellbillid . "\n"
            . ' التاريخ  ' . $sellbillData->sellbilldate . "\n"
            . ' المبلغ  ' . ($sellbillData->sellbilltotalpayed - $sellbillData->tax) . "\n"
            . ' الضريبه  ' . $sellbillData->tax . "\n"
            . ' الاجمالى  ' . $sellbillData->sellbilltotalpayed;
        $base64qrs = base64qrs($sellbillData->qrerpids, $qrdata, $Programsettingdata->qrcodesh);
        $smarty->assign('base64qrs', $base64qrs);
    }
    $smarty->assign('sellbillData', $sellbillData);
    $smarty->assign('qrerp', $Programsettingdata->qrerp);
    if ($Programsettingdata->numberprint == 1) {
        $smarty->display("resturant/printBill2.html");
    } else {
        if ($Programsettingdata->restPrintLang == 0) {
            $smarty->display("resturant/printBill.html");
        } else {
            $smarty->display("resturant/printBillEn.html");
        }
    }
}


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

//here the global templates


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

//select data from client tbl


function sellbillandruternshowDetail($sellbillid)
{
    //to use the variable out side the funcion
    global $mySellbillandruternEx;
    global $mySellandruternbilldetailEx;
    global $sellBillAndRuternCurrEX;

    //load Sellbillandrutern data by id
    $sellbillandruternData = $mySellbillandruternEx->loadSellbillandruternById($sellbillid);
    $billCurrData = $sellBillAndRuternCurrEX->queryOneBySellbillid($sellbillid);
    $sellbillandruternData->sellQuantity = (float) $sellbillandruternData->sellQuantity;
    $sellbillandruternData->returnsellQuantity = (float) $sellbillandruternData->returnsellQuantity;
    $sellbillandruternData->sellbilltotalbill = (float) $sellbillandruternData->sellbilltotalbill;
    $sellbillandruternData->sellbilldiscount = (float) $sellbillandruternData->sellbilldiscount;
    $sellbillandruternData->tax = (float) $sellbillandruternData->tax;
    $sellbillandruternData->sellbillaftertotalbill = (float) $sellbillandruternData->sellbillaftertotalbill;
    $sellbillandruternData->sellbilltotalpayed = (float) $sellbillandruternData->sellbilltotalpayed;
    $sellbillandruternData->sellbillfinalbill = (float) $sellbillandruternData->sellbillfinalbill;
    $sellbillandruternData->sellbilltotaldeptafter = (float) $sellbillandruternData->sellbilltotaldeptafter;
    $sellbillandruternData->sellbillprice = (float) $sellbillandruternData->sellbillprice;
    $sellbillandruternData->returnsellbillprice = (float) $sellbillandruternData->returnsellbillprice;

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

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

    $ruternbilldetailData = $mySellandruternbilldetailEx->queryWithSellBillIdAndSellType($sellbillid, 1);
    $returnQuantity = 0;
    foreach ($ruternbilldetailData as $ruternbilldetail) {
        $returnQuantity = $returnQuantity + $ruternbilldetail->sellbilldetailquantity;
    }

    ##use currency values
    if (isset($billCurrData) && !empty($billCurrData)) {
        $sellbillandruternData->sellbilldiscount = $billCurrData->sellbilldiscountC;
        $sellbillandruternData->sellbilltotalbill = $billCurrData->sellbilltotalbillC;
        $sellbillandruternData->sellbillaftertotalbill = $billCurrData->sellbillaftertotalbillC;
        $sellbillandruternData->sellbilltotalpayed = $billCurrData->sellbilltotalpayedC;
        $sellbillandruternData->sellbillfinalbill = $billCurrData->sellbillfinalbillC;
        $sellbillandruternData->sellbildirectpayment = $billCurrData->sellbildirectpaymentC;
        $sellbillandruternData->sellbillprice = $billCurrData->sellbillpriceC;
        $sellbillandruternData->returnsellbillprice = $billCurrData->returnsellbillpriceC;
        $sellbillandruternData->cashPayed = $billCurrData->cashPayedC;
        $sellbillandruternData->visaPayed = $billCurrData->visaPayedC;
        $sellbillandruternData->extraDiscountVal = $billCurrData->extraDiscountValC;
        $sellbillandruternData->taxOfDiscountVal = $billCurrData->taxOfDiscountValC;
        ##
        $sellbillandruternData->sellbilltotaldeptbefor = $sellbillandruternData->sellbilltotaldeptbefor * $billCurrData->conversionFactor;
        $sellbillandruternData->sellbilltotaldeptafter = $sellbillandruternData->sellbilltotaldeptafter * $billCurrData->conversionFactor;
        foreach ($sellbilldetailData as $value) {
            $value->sellbilldetailprice = $value->sellbilldetailpriceC;
            $value->sellbilldetailtotalprice = $value->sellbilldetailtotalpriceC;
            $value->discountvalue = $value->discountvalueC;
        }
        foreach ($ruternbilldetailData as $value) {
            $value->sellbilldetailprice = $value->sellbilldetailpriceC;
            $value->sellbilldetailtotalprice = $value->sellbilldetailtotalpriceC;
            $value->discountvalue = $value->discountvalueC;
        }
    }

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

function loadClient()
{
    //to use the variable out side the funcion
    global $myClientRecord;

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

    return $clientData;
}

//select data from client tbl
function loadAllClient()
{
    //to use the variable out side the funcion
    global $myClientRecord;

    // select all data from client tbl $clientData = $myClientRecord->queryAll();

    return $clientData;
}

//select data from client tbl
function loadAllSellBill()
{
    //to use the variable out side the funcion
    global $mySellbillRecord;

    // select all data from sellbill tbl
    $sellbillSearchData = $mySellbillRecord->queryAll();

    return $sellbillSearchData;
}

// select from Store tbl
function loadStore()
{

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

    // select all data from Storetbl
    $storeData = $myStoreRecord->queryByConditions(
        0
    );

    return $storeData;
}

// select from Product tbl
function loadProduct()
{

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



    // select all data from producttbl
    $productData = $myProductEx->queryWithCoditionsAndCatConditions();

    foreach ($productData as $product) {
        $productcatName;

        $product->productName = loadProductCatNameById($product->productCatId, $productcatName, 1) . "/" . $product->productName;
    }

    return $productData;
}

// select from Product tbl
function loadProductCatNameById($productCatId, $productcatName, $itr)
{
    //to use the variable out side the funcion
    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 = $productcatData->productCatName . "/" . $productcatNamex;
        }



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

    return $productcatNamex;
}

// select from Billname tbl
function loadBillname()
{

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

    // select all data from Billname
    $billnameData = $myBillnameEx->queryByType(0);

    return $billnameData;
}

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

// select from user tbl
function loadseller()
{

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

    // select all data from user
    $userData = $myUserEx->queryWithLevel(3);

    return $userData;
}

//load sellbill detail
function showDetail($sellbillid, $ordertype)
{
    //to use the variable out side the funcion
    global $mySellbillEx;
    global $mySellbilldetailEx;
    global $sellBillOfferEX;
    global $sellBillDetailOfferEX;
    global $clientDeptChangeExt;
    global $myBillsettingEx;
    global $billOperationDAO;
    global $sellBillCurrEX;

    //load purchasebillreturn data by id
    if ($ordertype == 0) { //bill
        $sellbillData = $mySellbillEx->loadSellBillById($sellbillid);
        $billCurrData = $sellBillCurrEX->queryOneBySellbillid($sellbillid);
        $printFormData = $myBillsettingEx->queryByBillidAndBillpropertyid($sellbillData->billnameid, 73);
        $order = ' order by sellbilldetail.sellbilldetailid asc';
        if ($printFormData[0]->billsettingsvalue == '9') { //from 10 make order by category
            $order = ' order by productcat.productCatName asc';
        }
        if (isset($_GET['playstation']) && $_GET['playstation'] == 1) {
            $sellbilldetailData = $mySellbilldetailEx->queryWithSellBillIdforpermationWithPlayStationData($sellbillid, $order);
        } else {
            $sellbilldetailData = $mySellbilldetailEx->queryWithSellBillIdforpermation($sellbillid, $order);
        }
        ########################################################################
        //Get Payments on a Bill At Controller clientPayedDeptSellBillsController.php
        //and this is like do=="show_details"
        $client_dept_Bills = $clientDeptChangeExt->selectByBillIdAndControl($sellbillid, 'clientPayedDeptSellBillsController.php');
        $client_bills = array();

        $finalnetbillvalue = $sellbillData->sellbillaftertotalbill;
        $waitvalue = $sellbillData->sellbillfinalbill;
        $payed = $sellbillData->sellbilltotalpayed;
        $x = 1;
        foreach ($client_dept_Bills as $cli_bill_val) {
            $clientdebtchangeamount = $cli_bill_val->clientdebtchangeamount;
            $paytype = $cli_bill_val->paytype;
            $date = $cli_bill_val->clientdebtchangedate;

            if ($x == 1) {
                $wait_before = $waitvalue;
                $wait_aftre = $wait_before - ($clientdebtchangeamount); //$wait_before - ( $payed + $clientdebtchangeamount );
            } else {
                $wait_before = $wait_aftre;

                $wait_aftre = $wait_before - $clientdebtchangeamount;
            }
            //if( $waitvalue > 0 ){
            $client_bills[] = array(
                'itra' => $x,
                'finalnetbillvalue' => $finalnetbillvalue,
                'wait_before' => $wait_before,
                'clientdebtchangeamount' => $clientdebtchangeamount,
                'wait_after' => $wait_aftre,
                'date' => $date,
                'paytype' => $paytype,
            );

            $x++;
        }
        ########################################################################
    } elseif ($ordertype == 1) { //offer
        $sellbillData = $sellBillOfferEX->loadSellBillById($sellbillid);
        $sellbilldetailData = $sellBillDetailOfferEX->queryWithSellBillIdforpermation($sellbillid);
    }
    $sellbillData->sellQuantity = (float) $sellbillData->sellQuantity;
    $sellbillData->sellbilltotalbill = (float) $sellbillData->sellbilltotalbill;
    $sellbillData->sellbilldiscount = (float) $sellbillData->sellbilldiscount;
    $sellbillData->tax = (float) $sellbillData->tax;
    $sellbillData->sellbillaftertotalbill = (float) $sellbillData->sellbillaftertotalbill;
    $sellbillData->sellbilltotalpayed = (float) $sellbillData->sellbilltotalpayed;
    $sellbillData->sellbillfinalbill = (float) $sellbillData->sellbillfinalbill;
    $sellbillData->sellbilltotaldeptafter = (float) $sellbillData->sellbilltotaldeptafter;


    $quantity = 0;
    foreach ($sellbilldetailData as $sellbilldetail) {
        $quantity = $quantity + ($sellbilldetail->sellbilldetailquantity);
        $sellbilldetail->discountvalue = (float) $sellbilldetail->discountvalue;
        $sellbilldetail->discounttype = (float) $sellbilldetail->discounttype;
    }
    //
    if ($sellbillData->billoperationid > 0) {
        $billOperationData = $billOperationDAO->load($sellbillData->billoperationid);
        $sellbillData->billoperationName = $billOperationData->name;
    }

    ##use currency values
    if (isset($billCurrData)) {
        $sellbillData->sellbilldiscount = $billCurrData->sellbilldiscountC;
        $sellbillData->sellbilltotalbill = $billCurrData->sellbilltotalbillC;
        $sellbillData->sellbillaftertotalbill = $billCurrData->sellbillaftertotalbillC;
        $sellbillData->sellbilltotalpayed = $billCurrData->sellbilltotalpayedC;
        $sellbillData->sellbillfinalbill = $billCurrData->sellbillfinalbillC;
        $sellbillData->sellbildirectpayment = $billCurrData->sellbildirectpaymentC;
        $sellbillData->tax = $billCurrData->taxC;
        $sellbillData->delivery = $billCurrData->deliveryC;
        $sellbillData->totalafterdelivery = $billCurrData->totalafterdeliveryC;
        $sellbillData->cashPayed = $billCurrData->cashPayedC;
        $sellbillData->visaPayed = $billCurrData->visaPayedC;
        $sellbillData->extraDiscountVal = $billCurrData->extraDiscountValC;
        $sellbillData->taxOfDiscountVal = $billCurrData->taxOfDiscountValC;
        ##
        $sellbillData->sellbilltotaldeptbefor = $sellbillData->sellbilltotaldeptbefor * $billCurrData->conversionFactor;
        $sellbillData->sellbilltotaldeptafter = $sellbillData->sellbilltotaldeptafter * $billCurrData->conversionFactor;
        foreach ($sellbilldetailData as $value) {
            $value->sellbilldetailprice = $value->sellbilldetailpriceC;
            $value->sellbilldetailtotalprice = $value->sellbilldetailtotalpriceC;
            $value->discountvalue = $value->discountvalueC;
        }
    }

    return array($sellbillData, $sellbilldetailData, $quantity, $client_bills, $billCurrData);
}

function showDetailBulk($sellbillid)
{
    //to use the variable out side the funcion
    global $mySellbillEx;
    global $mySellbilldetailEx;

    //load purchasebillreturn data by id
    $sellbillData = $mySellbillEx->loadSellBillByIdMany($sellbillid);
    //loop $sellbillData to get totals
    $sellbilltotalbill = 0;
    $sellbilltotalpayed = 0;
    $sellbilltotaldeptbefor = 0;
    $sellbillaftertotalbill = 0;
    $sellQuantity = 0;
    $i = 1;
    foreach ($sellbillData as $value) {
        $sellbilltotalbill += $value->sellbilltotalbill;
        $sellbilltotalpayed += $value->sellbilltotalpayed;
        if ($i == 1) {
            $sellbilltotaldeptbefor = $value->sellbilltotaldeptbefor;
        }
        $sellbillaftertotalbill += $value->sellbillaftertotalbill;
        $sellQuantity += $value->sellQuantity;
        $i++;
    }
    $sellbillData[0]->sellbilltotalbill = $sellbilltotalbill;
    $sellbillData[0]->sellbilltotalpayed = $sellbilltotalpayed;
    $sellbillData[0]->sellbilltotaldeptbefor = $sellbilltotaldeptbefor;
    $sellbillData[0]->sellbillaftertotalbill = $sellbillaftertotalbill;
    $sellbillData[0]->sellbillfinalbill = $sellbillaftertotalbill - $sellbilltotalpayed;
    $sellbillData[0]->sellQuantity = $sellQuantity;
    $sellbillData[0]->sellbilltotaldeptafter = $sellbilltotaldeptbefor + $sellbillaftertotalbill - $sellbilltotalpayed;
    //
    $sellbilldetailData = $mySellbilldetailEx->queryWithSellBillIdforpermation($sellbillid);
    $quantity = 0;
    //sum quantity of same produc and same unit
    $sellbilldetailDataArr = array();
    foreach ($sellbilldetailData as $sellbilldetail) {
        $quantity = $quantity + ($sellbilldetail->sellbilldetailquantity);
        ##check if product is here
        if (!isset($sellbilldetailDataArr[$sellbilldetail->sellbilldetailproductid][$sellbilldetail->productunitid])) {
            $sellbilldetailDataArr[$sellbilldetail->sellbilldetailproductid][$sellbilldetail->productunitid] = $sellbilldetail;
        } else {
            $sellbilldetailDataArr[$sellbilldetail->sellbilldetailproductid][$sellbilldetail->productunitid]->sellbilldetailtotalprice += $sellbilldetail->sellbilldetailtotalprice;
            $sellbilldetailDataArr[$sellbilldetail->sellbilldetailproductid][$sellbilldetail->productunitid]->discountvalue += $sellbilldetail->discountvalue;
            $sellbilldetailDataArr[$sellbilldetail->sellbilldetailproductid][$sellbilldetail->productunitid]->otherdetailquantity += $sellbilldetail->otherdetailquantity;
            $sellbilldetailDataArr[$sellbilldetail->sellbilldetailproductid][$sellbilldetail->productunitid]->sellbilldetailquantity += $sellbilldetail->sellbilldetailquantity;
        }
    }
    $sellbilldetailDataFinalArr = array();
    foreach ($sellbilldetailDataArr as $key => $value) {
        foreach ($value as $key1 => $value1) {
            array_push($sellbilldetailDataFinalArr, $value1);
        }
    }
    return array($sellbillData[0], $sellbilldetailDataFinalArr, $quantity);
}

function returnshowmorepermission($sellbillid)
{
    //to use the variable out side the funcion
    global $smarty;
    global $mySellbillandruternEx;
    global $mySellandruternbilldetailEx;


    global $myBillnameRecord;


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






    $billnameAddData = $myBillnameRecord->load($sellbillandruternData->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);



    //print_r($sellbillandruternData->billnameid);
    $billsettingsData = loadBillProperty($sellbillandruternData->billnameid);
    $smarty->assign("billsettingsData", $billsettingsData);

    $allstor = $mySellandruternbilldetailEx->queryAllsellstor($sellbillid);
    $smarty->assign("allstor", $allstor);
    $i = 1;
    foreach ($allstor as $myallstor) {


        $sellbilldetailData = $mySellandruternbilldetailEx->queryWithSellBillIdAndSellTypeandstor($sellbillid, 0, $myallstor->storeid);
        $sellQuantity = 0;
        foreach ($sellbilldetailData as $sellbilldetail) {
            $sellQuantity = $sellQuantity + $sellbilldetail->sellbilldetailquantity;
        }



        $smarty->assign("sellbilldetailData" . $i, $sellbilldetailData);

        //print_r("sellbilldetailData".$i.'<br>');
        $smarty->assign("sellQuantity" . $i, $sellQuantity);
        $i++;
        /* $ruternbilldetailData=$mySellandruternbilldetailEx->queryWithSellBillIdAndSellTypeandstor($sellbillid,1,$myallstor->storeid);

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

    $smarty->assign("storitr", (count($allstor)));
    //return array($sellbillandruternData,$sellbilldetailData, $ruternbilldetailData, $sellQuantity, $returnQuantity);
}

function showmorepermission($sellbillid)
{
    //to use the variable out side the funcion
    global $smarty;
    global $mySellbillEx;
    global $mySellbilldetailEx;

    global $myBillnameRecord;

    //load purchasebillreturn data by id
    $sellbillData = $mySellbillEx->loadSellBillById($sellbillid);
    $smarty->assign("sellbillData", $sellbillData);

    $billsettingsData = loadBillProperty($sellbillData->billnameid);
    $smarty->assign("billsettingsData", $billsettingsData);



    $billnameAddData = $myBillnameRecord->load($sellbillData->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);
    $allstor = $mySellbilldetailEx->queryAllsellstor($sellbillid);
    $smarty->assign("allst or", $allstor);




    $i = 1;
    foreach ($allstor as $myallstor) {

        $sellbilldetailData = $mySellbilldetailEx->queryWithSellBillIdforpermationandstor($sellbillid, $myallstor->storeid);
        $quantity = 0;
        foreach ($sellbilldetailData as $sellbilldetail) {
            $quantity = $quantity + ($sellbilldetail->sellbilldetailquantity);
        }

        $smarty->assign("sellbilldetailData" . $i, $sellbilldetailData);

        //print_r("sellbilldetailData".$i.'<br>');
        $smarty->assign("quantity" . $i, $quantity);
        $i++;
    }

    $smarty->assign("storitr", (count(
        $allstor
    )));
    //	return array($sellbillData, $quantity);
}

function returnsshowDetail($returnsellbillId)
{
    //to use the variable out side the funcion
    global $myReturnsellbillEx;
    global $myReturnsellbilldetailEx;
    global $returnSellBillCurrEX;


    //load purchasebillreturn data by id
    $returnsellbillData = $myReturnsellbillEx->loadReturnsellbillById($returnsellbillId);
    $billCurrData = $returnSellBillCurrEX->queryOneByReturnsellbillid($returnsellbillId);
    $returnsellbillData->returnsellQuantity = (float) $returnsellbillData->returnsellQuantity;
    $returnsellbillData->returnsellbilltotalbill = (float) $returnsellbillData->returnsellbilltotalbill;
    $returnsellbillData->returnsellbilldiscount = (float) $returnsellbillData->returnsellbilldiscount;
    $returnsellbillData->tax = (float) $returnsellbillData->tax;
    $returnsellbillData->returnsellbillaftertotalbill = (float) $returnsellbillData->returnsellbillaftertotalbill;
    $returnsellbillData->returnsellbilltotalpayed = (float) $returnsellbillData->returnsellbilltotalpayed;
    $returnsellbillData->returnsellbillfinalbill = (float) $returnsellbillData->returnsellbillfinalbill;
    $returnsellbillData->returnsellbilltotaldeptafter = (float) $returnsellbillData->returnsellbilltotaldeptafter;

    $returnsellbilldetailData = $myReturnsellbilldetailEx->queryWithReturnsellbillId($returnsellbillId);
    $quantity = 0;
    foreach ($returnsellbilldetailData as $returnsellbilldetail) {
        $quantity = $quantity + ($returnsellbilldetail->returnsellbilldetailquantity);
    }

    ##use currency values
    if (isset($billCurrData)) {
        $returnsellbillData->returnsellbilldiscount = $billCurrData->returnsellbilldiscountC;
        $returnsellbillData->returnsellbilltotalbill = $billCurrData->returnsellbilltotalbillC;
        $returnsellbillData->returnsellbillaftertotalbill = $billCurrData->returnsellbillaftertotalbillC;
        $returnsellbillData->returnsellbilltotalpayed = $billCurrData->returnsellbilltotalpayedC;
        $returnsellbillData->returnsellbillfinalbill = $billCurrData->returnsellbillfinalbillC;
        $returnsellbillData->returnsellbildirectpayment = $billCurrData->returnsellbildirectpaymentC;
        $returnsellbillData->cashPayed = $billCurrData->cashPayedC;
        $returnsellbillData->visaPayed = $billCurrData->visaPayedC;
        $returnsellbillData->extraDiscountVal = $billCurrData->extraDiscountValC;
        $returnsellbillData->taxOfDiscountVal = $billCurrData->taxOfDiscountValC;
        ##
        $returnsellbillData->returnsellbilltotaldeptbefor = $returnsellbillData->returnsellbilltotaldeptbefor * $billCurrData->conversionFactor;
        $returnsellbillData->returnsellbilltotaldeptafter = $returnsellbillData->returnsellbilltotaldeptafter * $billCurrData->conversionFactor;
        foreach ($returnsellbilldetailData as $value) {
            $value->returnsellbilldetailprice = $value->returnsellbilldetailpriceC;
            $value->returnsellbilldetailtotalprice = $value->returnsellbilldetailtotalpriceC;
            $value->discountvalue = $value->discountvalueC;
        }
    }
    return array($returnsellbillData, $returnsellbilldetailData, $quantity);
}

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

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

    return $clientName;
}

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

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

    return $clientData;
}

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

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

    return $productData;
}

function loadProductUnitWithProductAndUnit($productId, $unitId)
{

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

    // select all data from productunit tbl
    $productunitData = $myProductunitEx->queryWithProductIdAndUnitId($productId, $unitId);
    return $productunitData;
}

function showAll($startDate, $endDate)
{
    //to use the variable out side the funcion
    global $mySellbillEx;

    global $smarty;


    // get the all colums number
    $sellbillData = $mySellbillEx->queryWithDate($startDate, $endDate);

    // assign your db results to the template


    $smarty->assign('sellbillData', $sellbillData);
}

function showByClient($clientId)
{
    //to use the variable out side the funcion
    global $mySellbillEx;
    global $smarty;

    // get the all colums number
    $sellbillData = $mySellbillEx->queryWithClientId($clientId);

    // assign your db results to the template


    $smarty->assign('sellbillData', $sellbillData);
}

function showBySriral($serial)
{
    //to use the variable out side the funcion
    global $mySellbillEx;
    global $smarty;

    // get the all colums number
    $sellbillData = $mySellbillEx->queryWithSerail($serial);

    // assign your db results to the template


    $smarty->assign('sellbillData', $sellbillData);
}

function showBySellbillId($sellbillId)
{
    //to use the variable out side the funcion
    global $mySellbillEx;
    global $smarty;


    // get the all colums number
    $sellbillData = $mySellbillEx->queryWithSellbillId($sellbillId);

    // assign your db results to the template


    $smarty->assign('sellbillData', $sellbillData);
}

function showByDate($startDate, $endDate)
{
    //to use the variable out side the funcion
    global $mySellbillEx;
    global $smarty;

    // get the all colums number
    $sellbillData = $mySellbillEx->queryWithDate($startDate, $endDate);

    // assign your db results to the template


    $smarty->assign('sellbillData', $sellbillData);
}

function delete($sellbillid)
{

    //to use the variable out side the funcion
    global $mySellbill;
    global $mySellbillRecord;
    global $mySellbillEx;
    global $mySellbilldetail;
    global $mySellbilldetailRecord;

    try {

        $sellbillData = $mySellbillRecord->load($sellbillid);

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


        $note;
        $saveValuebeforeValid = 1;

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

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

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



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

        $mySellbillEx->updateConditions($mySellbill);


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

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

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

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

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

                if (count($allStoredetailData) > 0) {

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


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


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



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

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

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


        //check if payed or not to change save value

        if ($sellbilltotalPayed > 0) {

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

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

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

    return array($saveValuebeforeValid, $note);
}

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

    $outputString;

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

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

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

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

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

function loadProductCat()
{
    global $myProductEx;

    $allParents = $myProductEx->queryAllCategories();

    return $allParents;
}

function loadUnit()
{
    global $myUnitRecord;

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

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

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

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

    return

        $saveValuebefore;
}

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

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

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

    $saveValueafter = $saveValuebefore + $savevaluechanged;

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

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

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

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

    $saveValueafter = $saveValuebefore - $savevaluechanged;

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

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

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

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

    $mySaveEx
        ->updateSaveValue($mySave);
}

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

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

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

    $mySavedailyRecord->insert($mySavedaily);
}

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

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

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

    $myRawmaterialssuppliersEx->updateSupplierDebt($myRawmaterialssuppliers);
}

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

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

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

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

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

//update and increase productquantity in storedetail tbl

function increaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount)
{

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

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

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

    $myStoredetailEx->updateProductquantity($myStoredetail);

    return $productquantityAfter;
}

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

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

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

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

    $myStoredetailEx->updateProductquantity($myStoredetail);

    return

        $productquantityAfter;
}

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

    global $myStoredetail;
    global $myStoredetailRecord;

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

    $myStorereportRecord->insert($myStorereport);
}

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

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

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

    $myClientEx->updateClientdebt($myClient);
}

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

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

    $myClientdebtchange->clientdebtchangeafter = $clientdebtchangeafter;
    $myClientdebtchange->clientdebtchangeamount = $clientdebtchangeamount;
    $myClientdebtchange->clientdebtchangebefore = $clientdebtchangebefore;
    $myClientdebtchange->clientdebtchangedate = date("Y-m-d");
    $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);
}

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

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

    $myProductserialEx->updateDon($myProductserial);
}

function prepareMultiPrint($sellbillId, $itr)
{
    global $myClientRecord;
    global $myBillnameRecord;
    global $ProgramsettingDAO;
    global $smarty;
    $totaltax = 0;

    $showDetailData = showDetail($sellbillId);
    $clientdata = $myClientRecord->load($showDetailData[0]->sellbillclientid);

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

    $smarty->assign('sellbillData', $showDetailData[0]);
    $smarty->assign('sellbilldetailData', $showDetailData[1]);
    $smarty->assign("quantity", $showDetailData[2]);

    if (count($showDetailData[0]) > 0) {

        //getalldiscount
        $sellbilldiscount = $showDetailData[0]->sellbilldiscount;
        $sellbilldiscounttype = $showDetailData[0]->sellbilldiscounttype; //1 مباشر
        $sellbilltotalbill = $showDetailData[0]->sellbilltotalbill;
        $sellbillaftertotalbill = $showDetailData[0]->sellbillaftertotalbill;
        $extraDiscountVal = $showDetailData[0]->extraDiscountVal;
        $tax = $showDetailData[0]->tax;
        if ($sellbilldiscounttype == 1) {

            //tax
            $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($sellbilldiscount + $extraDiscountVal));
            $totaltax = $taxvalue;
        } else {
            //discount
            $discountvalue = ($sellbilltotalbill / 100) * $sellbilldiscount;
            //tax
            $taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - ($discountvalue + $extraDiscountVal));
            $totaltax = $taxvalue;
        }

        $smarty->assign('totaltax', $totaltax);
    }


    $billnameAddData = $myBillnameRecord->load($showDetailData[0]->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);

    $billsettingsData = loadBillProperty($showDetailData[0]->billnameid);
    $smarty->assign("billsettingsData", $billsettingsData);


    $billnameAddData = $myBillnameRecord->load($showDetailData[0]->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);

    $Programsettingdata = $ProgramsettingDAO->load(1);
    $smarty->assign("Programsettingdata", $Programsettingdata);
    $smarty->assign("multiClientBillPrint", 1);
    //here the smarty templates
    $output = $smarty->fetch('sellbillview/editprint2a4.html');


    $billnameid = $showDetailData[0]->billnameid;
    $smarty->assign("bill" . $itr, $output);
    return $billnameid;
}

function collectProductsintoItsCat($sellbillDetails)
{
    $retArr = array();
    foreach ($sellbillDetails as $value) {
        if (!isset($retArr[$value->sellbilldetailcatid])) {
            $retArr[$value->sellbilldetailcatid] = $value;
        } else {
            $retArr[$value->sellbilldetailcatid]->sellbilldetailquantity += $value->sellbilldetailquantity;
            $retArr[$value->sellbilldetailcatid]->sellbilldetailtotalprice += $value->sellbilldetailtotalprice;
        }
        $retArr[$value->sellbilldetailcatid]->productName = $value->productCatName;
        $retArr[$value->sellbilldetailcatid]->productCatName = "";
    }
    return $retArr;
}

function base64qr($qrerpid)
{
    $content = "https://shop.gt4host.com/qrerp/index/$qrerpid";
    ob_start();
    QRcode::png($content, false, 'L', 12, 2);
    $result_qr_content_in_png = ob_get_contents();
    ob_end_clean();
    header("Content-type: text/html");
    $result_qr_content_in_base64 = base64_encode($result_qr_content_in_png);
    // echo '<img src="data:image/jpeg;base64,'.$result_qr_content_in_base64.'" style="margin:100px 499px"/><hr/>';
    return $result_qr_content_in_base64;
}

function base64qrs($qrerpids, $qrdata = '', $qrcodesh = '')
{
    // if ($qrcodesh == 1) {
    // $content = $qrerpids . "\n" .$qrdata;
    // }else{
    $content = $qrerpids;
    // }

    ob_start();
    QRcode::png($content, false, 'L', 12, 2);
    $result_qr_content_in_png = ob_get_contents();
    ob_end_clean();
    header("Content-type: text/html");
    $result_qr_content_in_base64 = base64_encode($result_qr_content_in_png);
    return $result_qr_content_in_base64;
}
