<?php

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

// get the config file
include_once("../public/config.php");

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

//here the global templates
$smarty->assign("billjs", 0);
//$smarty->display("header.html");
$smarty->assign("sessionUserId", $_SESSION['userid']);
$smarty->display("header-bill.html");
//$smarty->display("maintennanceHeader.html");
//here goes the instances and general variables
//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');
//Restaurantplaystation
require_once('../models/dao/RestaurantplaystationDAO.class.php');
require_once('../models/dto/Restaurantplaystation.class.php');
require_once('../models/mysql/RestaurantplaystationMySqlDAO.class.php');
require_once('../models/mysql/ext/RestaurantplaystationMySqlExtDAO.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');
//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');
//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');
//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');
//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');
//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');
//check and use the condetion that suite this action
//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$programSettingEX = new ProgramsettingsMySqlExtDAO();
//Restauranttable
$restaurantTable = new Restauranttable();
$restaurantTableDAO = new RestauranttableMySqlDAO();
$restaurantTableEX = new RestauranttableMySqlExtDAO();
//Restauranthall
$restaurantHall = new Restauranthall();
$restaurantHallDAO = new RestauranthallMySqlDAO();
$restaurantHallEX = new RestauranthallMySqlExtDAO();
//Restaurantplaystation
$restaurantPlaystation = new Restaurantplaystation();
$restaurantPlaystationDAO = new RestaurantplaystationMySqlDAO();
$restaurantPlaystationEX = new RestaurantplaystationMySqlExtDAO();
//Restaurantplaystationplay
$restaurantPlaystationPlay = new Restaurantplaystationplay();
$restaurantPlaystationPlayDAO = new RestaurantplaystationplayMySqlDAO();
$restaurantPlaystationPlayEX = new RestaurantplaystationplayMySqlExtDAO();
//Productcat
$productCat = new Productcat();
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();
//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productEX = new ProductMySqlExtDAO();
//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();
//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientEX = new ClientMySqlExtDAO();
//Restaurantorder
$restaurantOrder = new Restaurantorder();
$restaurantOrderDAO = new RestaurantorderMySqlDAO();
$restaurantOrderEX = new RestaurantorderMySqlExtDAO();

//Restaurantorderdetail
$restaurantOrderDetails = new Restaurantorderdetail();
$restaurantOrderDetailsDAO = new RestaurantorderdetailsMySqlDAO();
$restaurantOrderDetailsEX = new RestaurantorderdetailsMySqlExtDAO();


$programsetting = $ProgramsettingDAO->load(1);
$noOfDecimalPlaces = ($programsetting->roundnumbers == 0) ? 0 : (int) $programsetting->noOfDecimalPlaces;

if (empty($do) || $do == "show") {
    if (isset($_SESSION["printPlaystationPlay"]) && !empty($_SESSION["printPlaystationPlay"])) {
        $smarty->assign("printPlaystationPlay", $_SESSION['printPlaystationPlay']);
        unset($_SESSION["printPlaystationPlay"]);
    } else {
        $smarty->assign("printPlaystationPlay", 0);
    }
    if (isset($_SESSION["printPlaystationPlayOrderId"]) && !empty($_SESSION["printPlaystationPlayOrderId"])) {
        $smarty->assign("printPlaystationPlayOrderId", $_SESSION['printPlaystationPlayOrderId']);
        unset($_SESSION["printPlaystationPlayOrderId"]);
    } else {
        $smarty->assign("printPlaystationPlayOrderId", 0);
    }
    //get ps devices
    $allRestaurantPlaystation = $restaurantPlaystationEX->queryAllRestaurantPlaystationWithPlayData();
    $smarty->assign("allRestaurantPlaystation", $allRestaurantPlaystation);
    $smarty->assign("employeename", $_SESSION['employeename']);
    $smarty->assign("now", date('Y-m-d H:i:s'));

    $smarty->display("restaurantplaystationplay/bill.html");
    //handleExpiredCards
    CURL_IT2(array('clientId' => 0), 'playStationCardController.php?do=handleExpiredCards');
} elseif ($do == "endplaystationplay") {
    $id = (int) $_POST["psid"];
    $client = (int) $_POST["client"];
    $printBill = (int) $_POST["printBill"];
    $totalPrice = round((float) $_POST["totalPrice"], $noOfDecimalPlaces);
    $discount = round((float) $_POST["discount"], $noOfDecimalPlaces);
    $netPrice = round((float) $_POST["netPrice"], $noOfDecimalPlaces);
    $payed = round((float) $_POST["payed"], $noOfDecimalPlaces);
    //card, cash payed
    if (isset($_POST["payed"])) {
        $cardPayed = 0;
//        $psClientCardId = 0;
        $cashPayed = $payed;
    }
    if (isset($_POST["cardPayed"])) {//&& isset($_POST["PSCard"])
        $cardPayed = round((float) $_POST["cardPayed"], $noOfDecimalPlaces);
        $cashPayed = round((float) $_POST["cashPayed"], $noOfDecimalPlaces);
//        $psClientCardId = (int) $_POST["PSCard"]; //it is playstationclientcard_id
        $payed = round(($cardPayed + $cashPayed), $noOfDecimalPlaces);
    }
    $billComment = $_POST["billComment"];
    $endRestaurantTable = (int) $_POST["endRestaurantTable"];
    $playstationTableId = (int) $_POST["playstationTableId"];


    if (empty($client)) {
        $client = 1;
    }

    createClientInUseSP(2);

    //Transaction
    $mytransactions = new Transaction();
    try {
        //
        $restaurantPlaystationPlay = $restaurantPlaystationPlayEX->getUnFinishedPlaystationPlay($id);
        if (isset($restaurantPlaystationPlay->id) && $restaurantPlaystationPlay->id > 0) {
            $restaurantPlaystation = $restaurantPlaystationDAO->load($restaurantPlaystationPlay->playstationid);
            $restaurantPlaystation->beingUsed = 0;
            $restaurantPlaystationDAO->update($restaurantPlaystation);
            //
            $restaurantPlaystationPlay->finished = 1;
            $restaurantPlaystationPlay->totalPrice = $totalPrice;
            $restaurantPlaystationPlay->discount = $discount;
            $restaurantPlaystationPlay->netPrice = $netPrice;
            $restaurantPlaystationPlay->payed = $payed;
            $restaurantPlaystationPlay->cardPayed = $cardPayed;
            $restaurantPlaystationPlay->cashPayed = $cashPayed;
            $restaurantPlaystationPlay->psClientCardId = $psClientCardId; /////i may use it that way 1-20.2,5-30.5   cardid-cardusedval
            $restaurantPlaystationPlay->note = $billComment;
            $restaurantPlaystationPlayDAO->update($restaurantPlaystationPlay);
            //
            $restaurantOrder = $restaurantOrderEX->queryByTableIdNotFinishedEX($restaurantPlaystation->tableId);
            if (count($restaurantOrder) > 0) {
                $restaurantOrder = $restaurantOrder[0];
                $restaurantOrderEX->updateRestaurantPlaystationplayId($restaurantOrder->id, $restaurantPlaystationPlay->id);
            }
            //if cardid , pay card
            ##################### why payment of modal is added to total of table and card payment no?????????????
            if ($cardPayed > 0) {//&& $psClientCardId > 0
                $res = CURL_IT2(array('psClientCardId' => $psClientCardId, 'cardPayed' => $cardPayed, 'restaurantPlaystationPlayId' => $restaurantPlaystationPlay->id, 'client' => $client), 'playStationCardController.php?do=payfromcard');
            }

            //
            $clientdata = $clientDAO->load($client);
            $sellBillId = (int) addSellBill($clientdata, $serviceData, $restaurantPlaystationPlay);

            $restaurantPlaystationPlay->sellBillId = $sellBillId;
            $restaurantPlaystationPlay->allMovesUnitedSellBillId = $sellBillId;
            $restaurantPlaystationPlayDAO->update($restaurantPlaystationPlay);
            //save allMovesUnitedSellBillId
            while ($restaurantPlaystationPlay->oldPsPlayid > 0) {
                $restaurantPlaystationPlay = $restaurantPlaystationPlayEX->loadEX($restaurantPlaystationPlay->oldPsPlayid);
                $restaurantPlaystationPlay->allMovesUnitedSellBillId = $sellBillId;
                $restaurantPlaystationPlayEX->setAllMovesUnitedSellBillId($restaurantPlaystationPlay->id, $sellBillId);
            }


            $mytransactions->commit();
            $orderId = 0;
            if ($endRestaurantTable == 1) {
                //printBill = 0 as we will print it here ,it would be un needed processing
                $tableDiscount = 0;
                $thereIsRestTax = $programsetting->thereIsRestTax; //this is the tax flag "there is tax or no"
                $restTaxVal = $programsetting->restTaxVal; //this is the tax percentage
                $restTaxVal_hidden = 0; //this is the tax value
                //get orderid to => getOrderDetailsTotal
                $order = $restaurantOrderEX->queryByTableIdNotFinishedEX($playstationTableId);
                $orderId = 0;
                if (count($order) > 0) {
                    $order = $order[0];
                    $orderId = $order->id;
                }
                $orderDetailsTotal = $restaurantOrderDetailsEX->getOrderDetailsTotal($orderId);
                $restTaxVal_hidden = (($orderDetailsTotal - $tableDiscount) * ($restTaxVal / 100));
                $netBill = $orderDetailsTotal - $tableDiscount + $restTaxVal_hidden;
                $orderDetailsTotal = round($orderDetailsTotal, $noOfDecimalPlaces);
                $restTaxVal_hidden = round($restTaxVal_hidden, $noOfDecimalPlaces);
                $netBill = round($netBill, $noOfDecimalPlaces);
                $res = CURL_IT2(array('tableId' => $playstationTableId, 'printBill' => 0, 'thereIsRestTax' => $thereIsRestTax, 'restTaxVal_hidden' => $restTaxVal_hidden,
                    'client' => $client, 'totalBill_hidden' => $orderDetailsTotal, 'discount' => $tableDiscount, 'netBill_hidden' => $netBill, 'payed' => $netBill, 'billComment' => ''), 'sellbillController.php?do=endKitchenBill');
            }

            if ($printBill == 1) {
                $_SESSION["printPlaystationPlay"] = $sellBillId; //$restaurantPlaystationPlay->id; //sellbillprintController.php?do=printResBill&id=
                $_SESSION["printPlaystationPlayOrderId"] = $orderId;
            }
        }



        $note = " تمت العملية بنجاح";
        $url = "restaurantplaystationpaly.php";
        $smarty->assign('urldirect', $url);
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $sellbillclientId = 1; //$_POST['supplier'];
        if (isset($_POST["client"]) && !empty($_POST["client"])) {
            $sellbillclientId = $_POST["client"];
        }
        markClientAsNOTInUse($sellbillclientId);
//        echo($ex);
//        die();
        $note = " لقد حدث خطأ";
        $url = "restaurantplaystationpaly.php";
        $smarty->assign('urldirect', $url);
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    }
} elseif ($do == "moveplaystationplay") {
    $fromDevice = (int) $_POST["fromDevice"];
    $toDevice = (int) $_POST["toDevice"];
    $newFromDevicePriceIs = (int) $_POST["newFromDevicePriceIs"];
    $oldFromDevicePriceIs = (int) $_POST["oldFromDevicePriceIs"];

    if ($toDevice == 0 && ($newFromDevicePriceIs != $oldFromDevicePriceIs)) {
        $toDevice = $fromDevice;
    }
    $oldTable = 0;
    $newTable = 0;

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

        $restaurantPlaystationPlay = $restaurantPlaystationPlayEX->getUnFinishedPlaystationPlay($fromDevice);
        if (isset($restaurantPlaystationPlay->id) && $restaurantPlaystationPlay->id > 0) {
            //1-close fromDevice
            $restaurantPlaystation = $restaurantPlaystationDAO->load($restaurantPlaystationPlay->playstationid);
            $restaurantPlaystation->beingUsed = 0;
            $restaurantPlaystationDAO->update($restaurantPlaystation);
            $oldTable = $restaurantPlaystation->tableId;

            ##do close calculation
            $restaurantPlaystationPlay->endsysDate = date('Y-m-d H:i:s');
            $hourPrice = $restaurantPlaystationPlay->hourPrice;
            if ($restaurantPlaystationPlay->priceIs == 1) {
                $hourPrice = $restaurantPlaystationPlay->hourPriceMulti;
            }
            //recalc moveDuration for old table as if we open close modal it will be messy data so //calc duration for move time
            $datetime1 = new DateTime($restaurantPlaystationPlay->moveStartSysDate);
            $datetime2 = new DateTime($restaurantPlaystationPlay->endsysDate);
            $interval = $datetime1->diff($datetime2);
            $restaurantPlaystationPlay->moveDuration = $interval->format('%h') . ":" . $interval->format('%i') . ":" . $interval->format('%s');
            //$restaurantPlaystationPlay->moveDurationInMin = round((abs(strtotime($restaurantPlaystationPlay->endsysDate) - strtotime($restaurantPlaystationPlay->moveStartSysDate)) / 60), 2);
            //calc duration for all time
            $datetime1 = new DateTime($restaurantPlaystationPlay->startsysDate);
            $datetime2 = new DateTime($restaurantPlaystationPlay->endsysDate);
            $interval = $datetime1->diff($datetime2);

            $restaurantPlaystationPlay->durationInMin = round((abs(strtotime($restaurantPlaystationPlay->endsysDate) - strtotime($restaurantPlaystationPlay->startsysDate)) / 60), 2);
            $restaurantPlaystationPlay->duration = $interval->format('%h') . ":" . $interval->format('%i') . ":" . $interval->format('%s');
            ## note re calc totalPrice to make it pure without startprice
            $durationSplitted = explode(":", $restaurantPlaystationPlay->moveDuration); //duration
            $restaurantPlaystationPlay->hourNum = $durationSplitted[0] + ($durationSplitted[1] / 60) + (($durationSplitted[2] / 60) / 60);
            //$restaurantPlaystationPlay->totalPrice = ($restaurantPlaystationPlay->durationInMin / 60) * $restaurantPlaystationPlay->hourPrice;
            $restaurantPlaystationPlay->totalPrice = $restaurantPlaystationPlay->hourNum * $hourPrice;
            $restaurantPlaystationPlay->totalPrice = round($restaurantPlaystationPlay->totalPrice, $noOfDecimalPlaces);



            $restaurantPlaystationPlay->finished = 1;
            $restaurantPlaystationPlay->discount = 0;
            $restaurantPlaystationPlay->payed = 0;
            $restaurantPlaystationPlay->note = '';
            $restaurantPlaystationPlay->netPrice = $restaurantPlaystationPlay->totalPrice;
            $restaurantPlaystationPlayDAO->update($restaurantPlaystationPlay);


            //2-open toDevice
            $theType = $restaurantPlaystationPlay->reservationType;
            $hoursResrvation = $restaurantPlaystationPlay->reservationHours;
            $minutesResrvation = $restaurantPlaystationPlay->reservationMinutes;
            $endTime = $restaurantPlaystationPlay->reservationEndDateTime;
            $startsysDate = $restaurantPlaystationPlay->startsysDate;
            $oldPsPlayid = $restaurantPlaystationPlay->id;
            #startPrice is important in calculating close price
            $startPrice = $restaurantPlaystationPlay->netPrice; //$restaurantPlaystationPlay->startPrice +
            $oldPsPlayidOfWhileLoop = $restaurantPlaystationPlay->oldPsPlayid;
            while ($oldPsPlayidOfWhileLoop > 0) {
                $temp = $restaurantPlaystationPlayEX->loadEX($oldPsPlayidOfWhileLoop);
                $startPrice += $temp->netPrice;
                $oldPsPlayidOfWhileLoop = $temp->oldPsPlayid;
            }
            #
            $restaurantPlaystation = $restaurantPlaystationDAO->load($toDevice);
            $restaurantPlaystation->beingUsed = 1;
            $restaurantPlaystationDAO->update($restaurantPlaystation);
            $newTable = $restaurantPlaystation->tableId;

            //make new play
            $restaurantPlaystationPlay = $restaurantPlaystationPlayEX->getUnFinishedPlaystationPlay($toDevice);
            $restaurantPlaystationPlay->playstationid = $restaurantPlaystation->id;
            $restaurantPlaystationPlay->hourPrice = $restaurantPlaystation->hourPrice;
            $restaurantPlaystationPlay->startsysDate = $startsysDate; //same time as old psplay
            $restaurantPlaystationPlay->endsysDate = "";
            $restaurantPlaystationPlay->duration = 0;
            $restaurantPlaystationPlay->note = "";
            $restaurantPlaystationPlay->totalPrice = 0;
            $restaurantPlaystationPlay->discount = 0;
            $restaurantPlaystationPlay->tax = 0;
            $restaurantPlaystationPlay->netPrice = 0;
            $restaurantPlaystationPlay->payed = 0;
            $restaurantPlaystationPlay->finished = 0;
            $restaurantPlaystationPlay->sellBillId = 0;
            $restaurantPlaystationPlay->userId = $_SESSION['userid'];
            $restaurantPlaystationPlay->sysdate = date('Y-m-d H:i:s');
            $restaurantPlaystationPlay->del = 0;
            $restaurantPlaystationPlay->reservationType = $theType;
            $restaurantPlaystationPlay->reservationHours = $hoursResrvation;
            $restaurantPlaystationPlay->reservationMinutes = $minutesResrvation;
            $restaurantPlaystationPlay->reservationEndDateTime = $endTime;
            $restaurantPlaystationPlay->priceIs = $newFromDevicePriceIs;
            $restaurantPlaystationPlay->hourPriceMulti = $restaurantPlaystation->hourPriceMulti;

            if (isset($restaurantPlaystationPlay->id) && $restaurantPlaystationPlay->id > 0) {
                $restaurantPlaystationPlayDAO->update($restaurantPlaystationPlay);
            } else {
                $restaurantPlaystationPlay->oldPsPlayid = $oldPsPlayid;
                $restaurantPlaystationPlay->startPrice = $startPrice;
                $restaurantPlaystationPlay->moveStartSysDate = $restaurantPlaystationPlay->sysdate;
                $restaurantPlaystationPlayDAO->insert($restaurantPlaystationPlay);
            }
            if ($oldTable > 0 && $newTable > 0 && $oldTable != $newTable) {
                $res = CURL_IT2(array('oldTable' => $oldTable, 'tableId' => $newTable), 'sellbillAjaxController.php?do=moveTable');
            }
        }
        $mytransactions->commit();


        $note = " تمت العملية بنجاح";
        $url = "restaurantplaystationpaly.php";
        $smarty->assign('urldirect', $url);
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $sellbillclientId = 1; //$_POST['supplier'];
        if (isset($_POST["client"]) && !empty($_POST["client"])) {
            $sellbillclientId = $_POST["client"];
        }
        markClientAsNOTInUse($sellbillclientId);
//        echo($ex);
        die();
        $note = " لقد حدث خطأ";
        $url = "restaurantplaystationpaly.php";
        $smarty->assign('urldirect', $url);
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    }
} elseif ($do == "sucess") {

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

    //here the smarty templates
    $smarty->display("error.html");
}
$smarty->assign("restaurantplaystationpaly", 1);
$smarty->display("footer.html");

////****************************  Functions  ********************///

/* ===============================
  function in this CONTROLLER
  ================================ */
function createClientInUseSP($clientid) {
    global $clientEX;
    if ((int) $clientid > 1) {
        $clientEX->createClientInUseSP();
    }
}

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

function addSellBill($clientdata, $serviceData, $restaurantPlaystationPlay) {
    global $productDAO;
    global $myProductunitEx;
    global $restaurantPlaystationPlayEX;
    global $noOfDecimalPlaces;

    $totalPrice = $restaurantPlaystationPlay->totalPrice;
    $discount = $restaurantPlaystationPlay->discount;
    $netPrice = $restaurantPlaystationPlay->netPrice;
    $payed = $restaurantPlaystationPlay->payed - $restaurantPlaystationPlay->cardPayed;
    $note = $restaurantPlaystationPlay->note;
    //
    $allDevicePlayArr = array();
    array_push($allDevicePlayArr, $restaurantPlaystationPlay);
    while ($restaurantPlaystationPlay->oldPsPlayid > 0) {
        $restaurantPlaystationPlay = $restaurantPlaystationPlayEX->loadEX($restaurantPlaystationPlay->oldPsPlayid);
        array_push($allDevicePlayArr, $restaurantPlaystationPlay);
    }
    //
    $post = array(
        'bns' => uniqid("0"),
        'bn' => date('Y-m-d H:i:s'),
        'tempclientName' => $clientdata->clientname,
        'carNumber' => '',
        'carType' => '',
        'carChase' => '',
        'carMotor' => '',
        'Costcenter' => '-1',
        'supplier' => $clientdata->clientid,
        'hidden_debt' => $clientdata->clientdebt,
        'pricetype' => 0,
        'hiddenpricetype' => 0,
        'hiddenpritype' => 1,
        'userstoreid' => 0,
        'userstoreidForClient' => 1,
        'storeid' => 1,
        'sellerid' => $_SESSION['userid'],
        'newproductItr' => '',
        'newproductTabIndex' => '',
        'billnameid' => 3,
        'settingreturn' => 1,
        'settingclient' => 0,
        'settingstore' => 0,
        'settingseller' => 1,
        'settingparcode' => 0,
        'settingdate' => 0,
        'settingnewproduct' => 1,
        'settingcomment' => 1,
        'settingdiscount' => 1,
        'settingQuantitiyFocus' => 1,
        'settingUnit' => 1,
        'settingQuantityAlert' => 0,
        'morestore' => 1,
        'sumSameProductForStore' => 0,
        'usePriceTypeOfClient' => 0,
        'saveBtnGoesTo' => 1,
        'printURL' => '',
        'sellerIsRequired' => 0,
        'searchvalue' => 1,
        'directDiscount' => 0,
        'percentageDiscount' => 10,
        'ordertype' => 0,
        'saveeffect' => 0,
        'discountrowtype' => 0,
        'multiclient' => 1,
        'showdiscountrow' => 1,
        'showbouns' => 1,
        'showclientdetail' => 1,
        'showtotal' => 0,
        'shownumber' => 0,
        'payedSetting' => 0,
        'returnhidden_itr' => 1,
        'returnparcode1' => '',
        'returnparcodeType1' => '',
        'returnproductserailid1' => '',
        'returnproductQty1' => '',
        'reprstorid1' => -1,
        'returnproduct1' => '',
        'returncomment1' => '',
        'returnproductunit1' => -1,
        'returnpronum1' => 1,
        'returnscunitname1' => 0,
        'returnproprice1' => 0,
        'returnprodis1' => 0,
        'returndiscounttype1' => 0,
        'returnhidden_prototal1' => 0,
        'returnsellbillprice' => 0,
        'returnsellQuantity' => 0,
        'genpay2' => '',
        'round_numbers' => 0,
        'previousPriceStatus' => 0,
        'storenegative' => 1,
        'sellbilltotalbill' => $totalPrice,
        'sellbillprice' => $totalPrice,
        'distype' => 1,
        'gendis' => $discount,
        'tax' => 0,
        'sellbillaftertotalbill' => $netPrice,
        'genpay' => $payed,
        'gen4totalinput' => $netPrice - $payed,
        'clientdebtafter' => $clientdata->clientdebt + $netPrice - $payed,
        'comment' => $note,
        'hidden_itr' => count($allDevicePlayArr),
    );
    $i = 1;
    $totQuantity = 0;
    foreach ($allDevicePlayArr as $value) {
        //
        $serviceData = $productDAO->load($value->serviceId);
        $myunitdata = $myProductunitEx->queryWithProductIdAndCondition($value->serviceId);
        $serviceData->productunitid = $myunitdata[0]->productunitid;
        //
        $duration = $value->moveDuration;
        if ($duration == "00:00:00") {
            $duration = $value->duration;
        }
        $durationSplitted = explode(":", $duration); //duration
        $value->hourNum = $durationSplitted[0] + ($durationSplitted[1] / 60) + (($durationSplitted[2] / 60) / 60);
        /* $timeDiffInSeconds = abs(strtotime($restaurantPlaystationPlay->endsysDate) - strtotime($restaurantPlaystationPlay->moveStartSysDate));
          $value->hourNum = ($timeDiffInSeconds / 60) / 60; */
        $value->totalPrice = $value->hourNum * $value->hourPrice;
        if ($value->priceIs == 1) {
            $value->totalPrice = $value->hourNum * $value->hourPriceMulti;
        }
        $value->totalPrice = round($value->totalPrice, $noOfDecimalPlaces);

        //
        $post['parcode' . $i] = $serviceData->parcode;
        $post['parcodeType' . $i] = 'parcode';
        $post['productserailid' . $i] = 0;
        $post['productQty' . $i] = 'undefined';
        $post['prstorid' . $i] = -1;
        $post['comment' . $i] = '';
        $post['product' . $i] = $serviceData->productId;
        $post['productunit' . $i] = $serviceData->productunitid;
        $post['pronum' . $i] = $value->hourNum;
        $post['scunitname' . $i] = 0;
        $post['bouns' . $i] = 0;
        $post['proprice' . $i] = $value->hourPrice;
        if ($value->priceIs == 1) {
            $post['proprice' . $i] = $value->hourPriceMulti;
        }
        $post['quantity' . $i] = '';
        $post['productpricetype' . $i] = 0;
        $post['prodis' . $i] = 0;
        $post['discounttype' . $i] = 0.00;
        $post['hidden_prototal' . $i] = $value->totalPrice;
        $post['playstationPlayId' . $i] = $value->id;
        $totQuantity += $value->hourNum;
        $i++;
    }
    $post['sellQuantity'] = $totQuantity;
    $res = CURL_IT2($post, 'sellbillController.php?do=add');
    return $res;
}

function CURL_IT2($data_arr, $url) {
    ##preparing session data
    //$projectURL = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/';
    $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $url;

    ##appending necessary data
    $data_arr['curlpost'] = '1';
    $data_arr['sessionlist'] = json_encode($_SESSION);


    // set post fields
//    $post = [
//        'data_arr' => json_encode($data_arr), //encode it as it is array
//    ];
    $post = $data_arr;
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        //echo 'Error : ' . curl_error($ch);
    }

    // close the connection, release resources used
    curl_close($ch);
    // do anything you want with your response
    //var_dump($response);
    //print_r($response);
    return $response;
}

?>