<?php
// it is sell billoffer at erp
require_once '_master/apiHandler.php'; // الكلاس الأساسي
require_once '_helper/store.php'; // الكلاس الأساسي
require_once '_helper/client.php'; // الكلاس الأساسي
// to be continued doOfferDailyEntry();
class pageClass extends apiHandler
{
    public function __construct()
    {
        parent::__construct();
        // $this->checkERPAccess();
        //$this->checkTokenClient();
    }

    function index(){
        try {
            $clientId = isset($this->getrequest->id) ? (int) $this->getrequest->id : 0;

            $response = array();
            if ($clientId > 0) {
                $offerData = R::findOne('sellbilloffer', 'conditions=0 and orderSavedBillId=0 and sellbillclientid= ? order by sellbillid desc limit 1', array($clientId));
                if (isset($offerData)) {
                    $offerDetails = (object) R::find('sellbilldetailoffer', 'sellbillid', array($offerData->sellbillid));
                    $response = array(
                        "id" => $offerData->sellbillid,
                        "subtotal" => $offerData->sellbilltotalbill,
                        "total_discount" => $offerData->sellbilldiscount,
                        "total" => $offerData->sellbillaftertotalbill,
                        "items_num" => count($offerDetails),//(float) R::count('sellbilldetailoffer', 'sellbillid', array($offerData->sellbillid)),
                        "items" => array(),
                    );
                    foreach($offerDetails as $offerDetail){
                        $product = R::getRow('SELECT productName, productNameE, discount, logo FROM product WHERE productId= ?', array($offerDetail->sellbilldetailproductid));
                        if($offerDetail->sizeid > 0 && $offerDetail->colorid > 0){
                            $stockQuantity = R::getcell("select sum(quantity) from sizecolorstoredetail where productid = $offerDetail->sellbilldetailproductid and sizeid = $offerDetail->sizeid and colorid = $offerDetail->colorid");
                        }else{
                            $stockQuantity = R::getcell('select sum(productquantity) from storedetail where productid ='. $offerDetail->sellbilldetailproductid);
                        }
                        $response['items'][] = array(
                            "product" => array(
                                "id" => $offerDetail->sellbilldetailproductid,
                                "name_ar" => $product['productName'],
                                "name_en" => $product['productNameE'],
                                "price" => $offerDetail->sellbilldetailprice,
                                "discount" => $product['discount'],
                                "images" => $this->hosturl . '/views/default/images/product_image/' . $product['logo'],
                                "quantity" => $offerDetail->sellbilldetailquantity,
                                "in_stock" => $stockQuantity > 0,
                            ),
                        );
                    }
                }
            } 
            
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    function items()
    {
        try {

            $billnameid = isset($this->getrequest->billnameid) ? (int) $this->getrequest->billnameid : 3;
            $offerId = isset($this->getrequest->offerId) ? (int) $this->getrequest->offerId : 0;
            $detailId = isset($this->getrequest->id) ? (int) $this->getrequest->id : 0;
            $clientId = isset($this->getrequest->clientId) ? (int) $this->getrequest->clientId : 0;
            $productId = isset($this->getrequest->product_id) ? (int) $this->getrequest->product_id : 0;
            $sizeid = isset($this->getrequest->size_id) ? (int) $this->getrequest->size_id : 0;
            $colorid = isset($this->getrequest->color_id) ? (int) $this->getrequest->color_id : 0;
            $quantity = isset($this->getrequest->quantity) ? (int) $this->getrequest->quantity : 0;
            $price = isset($this->getrequest->price) ? (float) $this->getrequest->price : 0.0;
            $discount = isset($this->getrequest->discount) ? (float) $this->getrequest->discount : 0.0;

             $operation = 'add';
            if($detailId > 0){ //this parameter is sent only in update
                $operation = 'update';
            } 
            
            if ($offerId > 0) {
                $offerData = R::load('sellbilloffer', 'conditions=0 and orderSavedBillId=0 and sellbillid= ?', array($offerId));
            } else if ($clientId > 0) {
                $offerData = R::findOne('sellbilloffer', 'conditions=0 and orderSavedBillId=0 and sellbillclientid= ? order by sellbillid desc limit 1', array($clientId));
                if (isset($offerData)) {
                    $offerId = $offerData->sellbillid;
                }
            } else if ($detailId > 0) {
                $detailrow = R::load('sellbilldetailoffer', $detailId);
                $offerData = R::load('sellbilloffer', $detailrow->sellbillid);
                $offerId = $offerData->sellbillid;
            }

            if ($offerId < 1) { //no offer , add one with almost no data
                $_POST["ordertype"] = 1;
                $_POST['supplier'] = $clientId;
                $_POST['bns'] = uniqid("0");
                $result = $this->add();
                $offerId = $result[0];
                $offerData = R::load('sellbilloffer', $offerId);
                //$offerData = (object) R::getRow('SELECT * FROM sellbilloffer WHERE conditions=0 and orderSavedBillId=0 and sellbillid= ' . $result[0]);
            }


            //now ther is offer , check if there is detail with this data , if so update it
            if($detailId == 0 && $offerId > 0 && $productId > 0){
                $detailId = R::getCell('select sellbilldetailid from sellbilldetailoffer where sellbillid= ? and sellbilldetailproductid= ? and sizeid= ? and colorid= ?', array($offerId, $productId, $sizeid, $colorid));
            }


            
            if ($detailId > 0) {
                $existingDetail = R::load('sellbilldetailoffer', $detailId);
                // Update existing product quantity
                $newQuantity = $quantity; //$existingDetail->sellbilldetailquantity + $quantity;
                $oldDetailTotal = $existingDetail->sellbilldetailtotalprice;
                $newDetailTotal = ($newQuantity * $existingDetail->sellbilldetailprice) - $existingDetail->discountvalue;

                $existingDetail->sellbilldetailquantity = $newQuantity;
                $existingDetail->sellbilldetailtotalprice = $newDetailTotal;
                R::store($existingDetail);


                // Update offer totals
                $newTotal = $offerData->sellbilltotalbill - $oldDetailTotal + $newDetailTotal;
            } else {
                // Create new offer detail record
                $detail = R::dispense('sellbilldetailoffer');
                $detail->sellbillid = $offerId;
                if ($sizeid > 0 && $colorid > 0) {
                    $detail->parcode = R::getCell('select parcode from sizecolorstoredetail where productid=' . $productId . ' and sizeid=' . $sizeid . ' and colorid=' . $colorid);
                } else {
                    $detail->parcode = R::getCell('select parcode from product where productId=' . $productId);
                }
                if (!isset($price) || empty($price)) {
                    $price = R::getCell('select productSellUnitPrice from product where productId=' . $productId);
                }
                $detail->sellbilldetailproductid = $productId;
                $detail->sellbilldetailcatid = (int) R::getCell('select productCatId from product where productId=' . $productId);
                $detail->productunitid = (int) R::getCell('select productunitid from productunit where conditions=0 and productnumber=1 and productid=' . $productId);
                $detail->sizeid = $sizeid;
                $detail->colorid = $colorid;
                $detail->sellbilldetailquantity = $quantity;
                $detail->sellbilldetailprice = $price;
                $detail->discountvalue = $discount;
                $detail->sellbilldetailtotalprice = ($quantity * $price) - $discount;
                $detail->pricetype = $offerData->pricetype;
                $detail->pricetypepro = $offerData->pricetype;
                $detail->storeid = $offerData->sellbillstoreid;
                $detail->otherdetailquantity = 0; //$Programsettingdata->scunitname;


                // Insert the detail
                $detailId = R::store($detail);

                // Calculate new total
                $newTotal = $offerData->sellbilltotalbill + $detail->sellbilldetailtotalprice;
            }

            // Update offer totals
            $offerData->sellbilltotalbill = $newTotal; //اجمالى الفاتورة قبل الخصم
            if ($offerData->sellbilldiscounttype == 1) {
                $discountvalue = $offerData->sellbilldiscount;
            } else {
                $discountvalue = ($newTotal / 100) * $offerData->sellbilldiscount;
            }
            $offerData->sellbillaftertotalbill = $newTotal - $discountvalue; //القيمة بعد الخصم
            $offerData->sellbillfinalbill = $offerData->sellbillaftertotalbill - $offerData->sellbilltotalpayed; //المتبقى
            R::store($offerData);

            // $rdispense = R::dispense('client');
            // $rdispense->clientname = $request['name'];
            // $id = R::store($rdispense);
            // $rdispense->id = $id;
            // إخراج البيانات

            if ($operation == 'add') {
                $response = array(
                    "cart"  => array(
                        "id" => $detailId, //$offerData->sellbillid,
                        "subtotal" => $offerData->sellbilltotalbill,
                        "total_discount" => $offerData->sellbilldiscount,
                        "total" => $offerData->sellbillaftertotalbill, //sellbillfinalbill
                        "items_count" => R::getCell('SELECT COUNT(DISTINCT sellbilldetailproductid) FROM sellbilldetailoffer WHERE sellbillid = ?', [$offerData->sellbillid])
                    )
                );
            } else if ($operation == 'update') {
                $response = array();
            }
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
        } catch (Exception $exception) {
            print_r($exception);
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    function ideltems()
    {
        try {
            $detailId = isset($this->getrequest->id) ? (int) $this->getrequest->id : 0;

            $existingDetail = R::load('sellbilldetailoffer', $detailId);
            $offerData = R::load('sellbilloffer', $existingDetail->sellbillid);

            $oldDetailTotal = $existingDetail->sellbilldetailtotalprice;
            // Update offer totals
            $newTotal = $offerData->sellbilltotalbill - $oldDetailTotal;

            // Update offer totals
            $offerData->sellbilltotalbill = $newTotal; //اجمالى الفاتورة قبل الخصم
            if ($offerData->sellbilldiscounttype == 1) {
                $discountvalue = $offerData->sellbilldiscount;
            } else {
                $discountvalue = ($newTotal / 100) * $offerData->sellbilldiscount;
            }
            $offerData->sellbillaftertotalbill = $newTotal - $discountvalue; //القيمة بعد الخصم
            $offerData->sellbillfinalbill = $offerData->sellbillaftertotalbill - $offerData->sellbilltotalpayed; //المتبقى
            R::store($offerData);



            R::trash('sellbilldetailoffer', $detailId);

            R::exec('DELETE sellbilloffer
                    FROM sellbilloffer
                    LEFT JOIN sellbilldetailoffer ON sellbilloffer.sellbillid = sellbilldetailoffer.sellbillid
                    WHERE sellbilldetailoffer.sellbillid IS NULL');
            $response = array();
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
        } catch (Exception $exception) {
            print_r($exception);
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    function clear()
    {
        try {
            $clientId = isset($this->getrequest->id) ? (int) $this->getrequest->id : 0;

            $offerData = R::findOne('sellbilloffer', 'conditions=0 and orderSavedBillId=0 and sellbillclientid= ? order by sellbillid desc limit 1', array($clientId));

            R::exec('delete from sellbilldetailoffer where sellbillid = ?', [$offerData->sellbillid]);
            R::trash('sellbilloffer', $offerData->sellbillid);
            $response = array();
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
        } catch (Exception $exception) {
            print_r($exception);
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    function add()
    {
        if (!isset($_POST['bns']) || empty($_POST['bns'])) {
            $_POST['bns'] = uniqid("0");
        }

        apiHandler::liveBackupComment("-- bill add start - with serial " . $_POST['bns']);
        // Start transaction
        //$mytransactions = new Transaction();
        R::begin();
        $storeDetailIds = $sizeColrDetailIds = [];
        try {

            $ordertype = (int) $_POST["ordertype"]; //0 bill , 1 offfer
            $offerId = (int) $_POST["offerId"]; //0 bill , 1 offfer
            $tempSaveBillId = (int) $_POST["tempSaveBillId"]; //bill  with autosave
            $billnameId = $_POST['billnameid'];
            $saveid = (int) $_POST['saveid'];
            if (!isset($_POST['saveid']) || empty($saveid)) {
                $saveid = $_SESSION['saveid'];
                if (!isset($_POST['saveid']) || empty($saveid)) {
                    $saveid = 1;
                }
            }

            $settingClient = (int) $_POST['settingclient'];
            $settingStore = (int) $_POST['settingstore'];

            $settingSeller = (int) $_POST['settingseller'];
            $settingDate = (int) $_POST['settingdate'];
            $settingQuantityCondition = $_POST['settingquantitycondition'];

            $tempClientName = $_POST['tempclientName'];

            $sellbillclientId = $_POST['supplier'];

            $sellbilltotaldeptBefor = $_POST['hidden_debt'];
            $sellbilltotaldeptAfter = $_POST['clientdebtafter'];
            $tax = (float) $_POST["tax"];
            $taxVal = (float) $_POST["taxVal"];

            $currencyId = (int) $_POST["currencyId"];
            $cFactor = (float) $_POST["cFactor"];

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

            $Costcenterid = (int) $_POST["Costcenter"];
            $billReservation = (int) $_POST["billReservation"];
            $billReservationDate = '';
            $_POST["billReservationDate"];

            $collectionType = (int) $_POST["collectionType"];
            $collectionDate = ''; //$_POST["collectionDate"];

            $isTaxBill = $_POST["isTaxBill"];
            $taxBillNumber = $_POST["taxBillNumber"];

            $knownwayId = (int) $_POST["knownwayId"];
            $travelDriverId = (int) $_POST["travelDriverId"];
            $travelBusId = (int) $_POST["travelBusId"];
            $travelPathId = (int) $_POST['travelPathId'];
            $travelTripId = (int) $_POST['travelTripId'];
            $travelTripTypeId = (int) $_POST['travelTripTypeId'];
            $travelTripDateId = (int) $_POST['travelTripDateId'];
            $sellToSupplier = (int) $_POST['sellToSupplier'];
            $whatShippingCost = (int) $_POST['whatShippingCost'];


            $clientName = R::getCell('SELECT clientname FROM client WHERE clientid = ' . $sellbillclientId);
            if (empty($tempClientName)) {
                $tempClientName = $_POST['tempclientName'] = $clientName;
            }

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

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

            //Store
            if ($settingStore == 0) {
                $sellbillstoreId = $_POST['storeid'];
            } else {
                $sellbillstoreId = $_POST['storeid'];
            }
            if (!isset($sellbillstoreId) || empty($sellbillstoreId)) {
                $sellbillstoreId = 1;
            }

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

            $comment = ''; //$_POST['comment'];

            $sellbillSerial = $_POST['bns'];
            $sellbillno = $_POST['sellbillno'];
            //$priceType = $_POST['hiddenpricetype'];
            $priceType = (int) $_POST['pricetype'];
            $tagids = $_POST['tagids'];

            $sellbilltotalBill = 0; //$_POST['sellbilltotalbill']; //اجمالى الفاتورة قبل الخصم
            $sellbillDiscountType = isset($_POST['distype']) ? $_POST['distype'] : 1; //نوع الخصم
            $visa = (float) $_POST['genpayvisa'];
            $visaAccount = (int) $_POST['visaAccount'];
            if (empty($visaAccount)) {
                $visa = 0;
            }
            $isBankAccountTransfer = (int) $_POST['isBankAccountTransfer'];
            $extraDiscountPer = (float) $_POST['extraDiscountPer'];
            $extraDiscountVal = (float) $_POST['extraDiscountVal'];
            $taxOfDiscountPer = (float) $_POST['taxOfDiscountPercentage'];
            $taxOfDiscountVal = (float) $_POST['taxOfDiscountVal'];

            $sellbillDiscount = (float) $_POST['gendis']; //قيمة الخصم
            $sellbillAftertotalBill = (float) $_POST['sellbillaftertotalbill']; //القيمة بعد الخصم
            $sellbilltotalPayed = (float) $_POST['genpay']; //المدفوع
            if ($sellbillAftertotalBill > 0) {
                $sellbillFinalbill = $sellbillAftertotalBill - $sellbilltotalPayed - $visa; //المتبقى
            } else {
                //return is more
                $sellbillFinalbill = $sellbillAftertotalBill + $sellbilltotalPayed + $visa; //المتبقى
            }

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

            /* -- reverse store operations on stores for offer  ----------------- */
            if ($offerId > 0) {
                $oldOrdertype = $ordertype;
                $ordertype = 1;
                storeHelper::reverseOfferStoreMovement($offerId);
                $ordertype = $oldOrdertype;
            }

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

            if ($ordertype == 0) { //bill only not offer
                $clientdata = getClientDataFromClientInUseSP($sellbillclientId);
                //$clientdata = $myClientRecord->load($sellbillclientId);
            }

            $sellbilltotaldeptBefor = 0; //$clientdata->clientdebt; //$_POST['hidden_debt'];
            $gen4totalinput = $sellbillAftertotalBill - $sellbilltotalPayed - $visa; //$_POST["gen4totalinput"];
            if ($currencyId > 1) {
                $gen4totalinput = $gen4totalinput / $cFactor;
            }
            $totalprodiscount = (float) $_POST['totalProDis']; //خصومات المنتج
            $manage_ex = (float) $_POST['manage_ex'];
            $med_hallmark = (float) $_POST['med_hallmark'];
            $pay_rec_no = (float) $_POST['pay_rec_no'];
            $pay_rec_val = (float) $_POST['pay_rec_val'];
            $decisionNo = (float) $_POST['decisionNo'];
            $decisionValue = (float) $_POST['decisionValue'];
            ##curr conversion
            $billCurrInsertId = 0;
            //$saveData = $mySaveEx->loadForUpdateEx($_SESSION['saveid']);
            $saveData = (object) R::getRow('SELECT save.* ,currency.conversionFactor
                FROM save
                left join currency on currency.id = save.currencyId
                WHERE saveid = ?', [$_SESSION['saveid']]);
            $saveConversionFactor = $saveData->conversionFactor;
            $sellbilldiscountC = $sellbillDiscount;
            $sellbilltotalbillC = $sellbilltotalBill;
            $sellbillaftertotalbillC = $sellbillAftertotalBill;
            $sellbilltotalpayedC = $sellbilltotalPayed;
            $sellbillfinalbillC = $sellbillFinalbill;
            $sellbildirectpaymentC = $sellbildirectPayment;
            $taxValC = $taxVal;
            $deliveryC = $sellbilldelivery;
            $totalafterdeliveryC = $totalaafterdelivery;
            $cashPayedC = $sellbilltotalPayed;
            $visaPayedC = $visa;
            $extraDiscountValC = $extraDiscountVal;
            $sellbilldiscountC = $sellbillDiscount;
            $totalprodiscountC = $totalprodiscount;
            if ($currencyId > 1) {
                if ($sellbillDiscountType != "2")
                    $sellbillDiscount = $sellbillDiscount / $cFactor;
                $sellbilltotalBill = $sellbilltotalBill / $cFactor;
                $sellbillAftertotalBill = $sellbillAftertotalBill / $cFactor;
                $sellbilltotalPayed = $sellbilltotalPayed / $cFactor;
                $sellbillFinalbill = $sellbillFinalbill / $cFactor;
                $sellbildirectPayment = 1;
                $taxVal = $taxVal / $cFactor;
                $sellbilldelivery = $sellbilldelivery / $cFactor;
                $totalaafterdelivery = $totalaafterdelivery / $cFactor;
                $cashPayed = $sellbilltotalPayed / $cFactor;
                $visa = $visa / $cFactor;
                $extraDiscountVal = $extraDiscountVal / $cFactor;
                $taxOfDiscountVal = $taxOfDiscountVal / $cFactor;
                $totalprodiscount = $totalprodiscount / $cFactor;
                $manage_ex = $manage_ex / $cFactor;
                $med_hallmark = $med_hallmark / $cFactor;
                $pay_rec_no = $pay_rec_no / $cFactor;
                $pay_rec_val = $pay_rec_val / $cFactor;
            }
            ###################################################
            if ($sellbillclientId == 1) {
                $sellbilltotaldeptAfter = $sellbilltotaldeptBefor + $gen4totalinput; //$_POST['clientdebtafter'];
            } else {

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

            $sellbilldelivery = (float) $_POST['delivery']; //قيمه الشحن / التوصيل
            $totalaafterdelivery = (float) $_POST['valdeliveryhidden']; //الاجمالي العام بعد التوصيل
            ##get $billTotalBeforeDiscount
            $billTotalBeforeDiscount = $sellbilltotalBill;
            ##get $billDiscountVal
            $billDiscountVal = $sellbillDiscount;
            if ($sellbillDiscountType == "2") {
                $billDiscountVal = ($sellbillDiscount / 100) * $billTotalBeforeDiscount;
                $billDiscountVal = round($billDiscountVal, $noOfDecimalPlaces);
            }
            ########################################################################
            //////////////////////////////////////////////////////////////////////////
            $sellbillItr = (int) $_POST['hidden_itr'];
            $returnSellbillItr = (int) $_POST['returnhidden_itr'];

            $productsBeforeValid = 1;
            $saveValuebeforeValid = 1;
            /* ----------------------------- */
            $sellbillId;
            $returnsellbillId;
            $billtype;
            /* ------------------------ */
            if ($ordertype == 1) { //its an offer not bill
                $billtype = 1; //مبيعات

                $mySellbill = R::dispense('sellbilloffer');
                $mySellbill->billnameid = $billnameId;
                $mySellbill->conditions = 0;
                $mySellbill->sellbildirectpayment = $sellbildirectPayment;
                $mySellbill->sellbillaftertotalbill = $sellbillAftertotalBill;
                $mySellbill->sellbillclientid = $sellbillclientId;
                $mySellbill->sellbillclientname = $clientName;
                $mySellbill->sellbilldate = $sellbillDate;
                $mySellbill->sellbilldiscount = $sellbillDiscount;
                $mySellbill->sellbilldiscounttype = $sellbillDiscountType;
                $mySellbill->sellbillfinalbill = $sellbillFinalbill;
                $mySellbill->sellbillsaveid = $saveid;
                $mySellbill->sellbillserial = $sellbillSerial;
                $mySellbill->sellbillstoreid = $sellbillstoreId;
                $mySellbill->sellbillsysdate = date("Y-m-d H:i:s");
                $mySellbill->sellbilltotalbill = $sellbilltotalBill;
                $mySellbill->sellbilltotaldeptafter = $sellbilltotaldeptAfter;
                $mySellbill->sellbilltotaldeptbefor = $sellbilltotaldeptBefor;
                $mySellbill->sellbilltotalpayed = $sellbilltotalPayed + $visa;
                $mySellbill->sellerid = $sellerId;
                $mySellbill->userid = 1; //$_SESSION['userid'];
                $mySellbill->tempclientName = $tempClientName;
                $mySellbill->sellQuantity = $sellQuantity;
                $mySellbill->tax = $tax;
                $mySellbill->carnumber = $sellbillcarnumber;
                $mySellbill->cartype = $sellbillcartype;
                $mySellbill->carchase = $sellbillcarchase;
                $mySellbill->carmotor = $sellbillcarmotor;
                $mySellbill->costcenterid = $Costcenterid;
                $mySellbill->dailyentryid = 0;
                $mySellbill->comment = $comment;
                $mySellbill->delivery = $sellbilldelivery;
                $mySellbill->totalafterdelivery = $totalaafterdelivery;
                $mySellbill->billReservation = $billReservation;
                $mySellbill->billReservationDate = $billReservationDate;
                $mySellbill->cashPayed = $sellbilltotalPayed;
                $mySellbill->visaPayed = $visa;
                $mySellbill->visaAccountId = $visaAccount;
                $mySellbill->isBankAccountTransfer = $isBankAccountTransfer;
                $mySellbill->extraDiscountPer = $extraDiscountPer;
                $mySellbill->extraDiscountVal = $extraDiscountVal;
                $mySellbill->taxOfDiscountPer = $taxOfDiscountPer;
                $mySellbill->taxOfDiscountVal = $taxOfDiscountVal;
                $mySellbill->collectionType = $collectionType;
                $mySellbill->collectionDate = $collectionDate;
                $mySellbill->webApiId = (int) $_POST['webApiId'];
                $mySellbill->taxBillNumber = 0;
                $mySellbill->qrerpid = '';
                $mySellbill->qrerpids = '';
                $mySellbill->obgyBillType = (int) $_POST['obgyBillType'];
                $mySellbill->billoperationid = (int) $_POST['billoperationid'];
                $mySellbill->datestarting = ''; //$_POST['datestarting'];
                $mySellbill->pricetype = $priceType;
                $mySellbill->totalprodiscount = $totalprodiscount;
                $mySellbill->manage_ex = $manage_ex;
                $mySellbill->med_hallmark = $med_hallmark;
                $mySellbill->pay_rec_no = $pay_rec_no;
                $mySellbill->pay_rec_val = $pay_rec_val;
                $mySellbill->decisionNo = $decisionNo;
                $mySellbill->decisionValue = $decisionValue;
                if ($isTaxBill == 1 && $taxBillNumber > 0) {
                    //get fresh $taxBillNumber
                    $taxBillNumber =  (int) R::getCell('SELECT taxBillNumber FROM  sellbill WHERE taxBillNumber > 0 order by sellbillid desc limit 1') + 1;
                    $mySellbill->taxBillNumber = $taxBillNumber;
                }
                //by eng sherif as i get sellbillaftertotalbill = 0 when disount = 0
                //i am stoping it as it is working and $mySellbill->sellbillaftertotalbill has many other parameters more than tax only
                //                    if ($sellbillDiscount == 0) {
                //                        $mySellbill->sellbillaftertotalbill = $mySellbill->sellbilltotalbill + ($mySellbill->sellbilltotalbill * ($tax / 100));
                //                    }
                $mySellbill->deletedsellid = 0;
                $mySellbill->controlname = 'sellbillController.php?do=addsellBill';
                $mySellbill->obygyVisitId = 0;
                $mySellbill->costcenterid = 0;
                $mySellbill->comment = $comment;
                $mySellbill->conditions = 0;
                $mySellbill->sellbillsysdate = date("Y-m-d H:i:s");
                $mySellbill->userid = 1; //$_SESSION['userid'];
                $mySellbill->delbyuserid = 0;
                $mySellbill->lastReviewType = 0;
                $mySellbill->billReservation = $billReservation;
                $mySellbill->billReservationDate = $billReservationDate;
                $mySellbill->clientaddress = ''; //$_POST['clientaddress'];
                $sellbillId = R::store($mySellbill);

                $detailsArr = array();
                //insert Sell Data into Sellbilldetail tbl
                $sellbillItr = $_POST['hidden_itr'];
                $h = 1;
                for ($h = 1; $h <= $sellbillItr; $h++) {
                    ## if input are encoded in json put it again in post
                    if (isset($_POST["obj" . $h])) {
                        foreach (json_decode(str_replace("'", '"', $_POST["obj" . $h]), true) as $key => $value) {
                            $_POST[$key . $h] = $value;
                        }
                    }
                    $parcode = $_POST['parcode' . $h . ''];
                    $parcodeType = $_POST['parcodeType' . $h . ''];
                    $productserailId = $_POST['productserailid' . $h . ''];
                    $productId = $_POST['product' . $h . ''];
                    $sizeId = 0;
                    $colorId = 0;
                    $sizeColorStoreDetailId = 0;
                    if (strpos($productId, "hasSizeColor") !== false) {
                        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                        $productId = $productIdComplex[0];
                        $sizeId = $productIdComplex[1];
                        $colorId = $productIdComplex[2];
                        $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $sellbillstoreId, $sizeId, $colorId);
                    }
                    $productunitId = $_POST['productunit' . $h . ''];
                    $quantity = $_POST['pronum' . $h . ''];
                    $price = $_POST['proprice' . $h . ''];
                    $catdis = $_POST['catdis' . $h . ''];
                    $discountValue = $_POST['prodis' . $h . ''];
                    $totalPrice = $_POST['hidden_prototal' . $h . ''];
                    $comment = $_POST['comment' . $h . ''];
                    $prstorid = $_POST['prstorid' . $h . ''];
                    $discounttype = $_POST['discounttype' . $h . ''];
                    $scunitname = $_POST['scunitname' . $h . ''];
                    $pricetypepro = $_POST['pricetypepro' . $h . ''];

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

                        //print_r('in if prstorid'.$prstorid.'<br>');
                        $sellbillstoreId = $prstorid;
                    } else {
                        $sellbillstoreId = $_POST['storeid'];
                        //print_r('in  else sellbillstoreId'.$sellbillstoreId.'<br>');
                    }
                    if ($productunitId == "") {
                        $productunitId = 0;
                    }
                    //print_r('the final'.$sellbillstoreId.'<br>');
                    if (isset($productId) && $productId != '-1' && $productId != "") {
                        $productData = R::load('product', $productId);

                        $mySellbilldetail = R::dispense('sellbilldetail');
                        // $mySellbilldetail->buyprice = $productData->productBuyPrice;
                        $mySellbilldetail->buyprice = $productData->productBuyPrice;

                        $mySellbilldetail->discountvalue = $discountValue;
                        $mySellbilldetail->note = $comment;
                        $mySellbilldetail->parcode = $parcode;
                        $mySellbilldetail->pricetype = $priceType;
                        $mySellbilldetail->productunitid = $productunitId;
                        $mySellbilldetail->sellbilldetailcatid = $productData->productCatId;
                        $mySellbilldetail->sellbilldetaildate = date("Y-m-d H:i:s");
                        $mySellbilldetail->sellbilldetailprice = $price;
                        $mySellbilldetail->sellbilldetailproductid = $productId;
                        $mySellbilldetail->sellbilldetailquantity = $quantity;
                        $mySellbilldetail->sellbilldetailtotalprice = $totalPrice;
                        $mySellbilldetail->sellbillid = $sellbillId;
                        $mySellbilldetail->buydiscount = $productData->buydiscount;
                        $mySellbilldetail->buydiscounttype = $productData->discounttype;
                        $mySellbilldetail->storeid = $sellbillstoreId;
                        $mySellbilldetail->discounttype = $discounttype;
                        $mySellbilldetail->otherdetailquantity = $scunitname;
                        $mySellbilldetail->sizeid = $sizeId;
                        $mySellbilldetail->colorid = $colorId;
                        $mySellbilldetail->pricetypepro = $pricetypepro;
                        $mySellbilldetail->categorydiscount = $catdis;
                        $mySellbilldetail->scunitqty = 0;
                        $mySellbilldetail->onlineOrderId = 0;
                        R::store($mySellbilldetail);

                        array_push($detailsArr, $mySellbilldetail);


                        $taxesitr = $_POST['taxesitr_' . $h . ''];
                        $e = 1;

                        for ($e = 1; $e <= $taxesitr; $e++) {
                            if (!$_POST['type_' . $h . '_' . $e]) {
                                continue;
                            }

                            $sellbilldetailtax = R::dispense('sellbilldetailtax');
                            $sellbilldetailtax->sellbilldetailid = $detailId;
                            $sellbilldetailtax->is_offer = 1; //mean to use sellbilldetailid in sellbilldetailoffer table
                            $sellbilldetailtax->conditions = 0;
                            $sellbilldetailtax->type = $_POST['type_' . $h . '_' . $e];
                            $sellbilldetailtax->subtype = $_POST['subtype_' . $h . '_' . $e];
                            $sellbilldetailtax->rate = $_POST['rate_' . $h . '_' . $e];
                            $sellbilldetailtax->amount = $_POST['amount_' . $h . '_' . $e];
                            R::store($sellbilldetailtax);
                        }

                        $billnameData = R::findOne('billname', 'where billnameid = ' . $billnameId);
                        if ($billnameData->storeeffect == 1) {
                            if ($productData->isService == 0 && $Programsettingdata->preparingStore != $sellbillstoreId) { //if product && stores are not same
                                $productnumber = (float) $_POST['proNum' . $h];
                                if ($productnumber <= 0) {
                                    $productunitData = (object) R::getRow('SELECT productunit.*, unit.unitName,product.overAllAveragePrice
                                        FROM productunit JOIN unit
                                        ON productunit.unitid = unit.unitId
                                        join product on product.productId = productunit.productid
                                        where productunit.productid = ' . $productId . '
                                        and productunit.productunitid = ' . $productunitId . '
                                        and unit.conditions = 0
                                        and productunit.conditions = 0');
                                    $productnumber = $productunitData->productnumber;
                                }
                                $finalquantity = $quantity * $productnumber;


                                /* -- decrease from stroe --------------------------- */
                                //get store productquantity before change
                                $storedetailData = storeHelper::getStoreDetails($sellbillstoreId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

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

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

                                    //update productquantity in storedetail
                                    $productquantityAfter =  storeHelper::decreaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                    //insert in storereport
                                    storeHelper::insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityAfter, 1, $sellbillId, "حجز كميات لامر بيع", "sellbillController.php?do=showoffers", date("Y-m-d H:i:s"), $sizeId, $colorId);
                                } else {
                                    $specialQuantityAfter = $finalquantity * -1;

                                    //insert in storedetail tbl
                                    storeHelper::insertStoredetailupdate($sellbillstoreId, $productId, $specialQuantityAfter, date("Y-m-d H:i:s"), "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);

                                    //insert in storereport
                                    storeHelper::insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $specialQuantityAfter, 1, $sellbillId, "حجز كميات لامر بيع", "sellbillController.php?do=showoffers", date("Y-m-d H:i:s"), $sizeId, $colorId);
                                }

                                // /* -- increase from stroe --------------------------- */
                                // //get storeto productquantity before change
                                // $sellbillstoreId = $Programsettingdata->preparingStore;
                                // $storedetailData = getStoredetailData($sellbillstoreId, $productId, $sizeColorStoreDetailId, $sizeId, $colorId);
                                // $allStoredetailData = $storedetailData[0];
                                // $storedetailId = $storedetailData[1];
                                // $productquantityBefore = $storedetailData[2];
                                // if (count($allStoredetailData) > 0) {
                                //     //update productquantity in storedetail
                                //     $productquantityToAfter = increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                //     //insert in storereport
                                //     insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, $productquantityBefore, $productquantityToAfter, 0, $sellbillId, "حجز كميات لامر بيع", "sellbillController.php?do=showoffers", $sellbillDate, $sizeId, $colorId);
                                // } else {
                                //     //insert in storedetail tbl
                                //     insertStoredetailupdate($sellbillstoreId, $productId, $finalquantity, $sellbillDate, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                //     //insert in storereport
                                //     insertStorereportupdate($productId, $sellbillstoreId, $finalquantity, 0, $finalquantity, 0, $sellbillId, "حجز كميات لامر بيع", "sellbillController.php?do=showoffers", $sellbillDate, $sizeId, $colorId);
                                // }
                            }
                        }
                    }
                }

                //doOfferDailyEntry($sellbillId, $mySellbill, $detailsArr);
            }

            //$mytransactions->commit();
            R::commit(); // Commit transaction

            ##buyTheSellBill
            if ($sellbillId > 0 && $ordertype == 0) {
                buyTheSellBill($sellbillId, 0);
            }
        } catch (Exception $ex) {
            //$mytransactions->rollback();
            R::rollback(); // Rollback if anything goes wrong
            $sellbillclientId = $_POST['supplier'];
            client::markClientAsNOTInUse($sellbillclientId);
        }
        apiHandler::liveBackupComment("-- bill add end - with serial " . $_POST['bns'] . " and sellbillId = $sellbillId and returnsellbillId = $returnsellbillId");
        storeHelper::markStoreDetailNotInUse($storeDetailIds, $sizeColrDetailIds);
        return array(
            $sellbillId,
            $returnsellbillId,
            $productsBeforeValid,
            $saveValuebeforeValid,
            $billtype,
            $ordertype,
            $ex
        );
    }

    public function reverseOfferStoreMovement($offerId)
    {

        /* -- reverse store operations on stores ------------------------ */
        $storeMovesData = R::getAll('select * from storereport where storereportmodelid =' . $offerId . ' and tablename="sellbillController.php?do=showoffers"');
        foreach ($storeMovesData as $move) {
            $storeid = $move['storeid'];
            $productId = $move['productid'];
            $sizeId = $move['sizeid'];
            $colorId = $move['colorid'];
            $billDiscountVal = $detailId = $billTotalBeforeDiscount = $totalPrice = 0;

            $sizeColorStoreDetailId = 0;
            if ($move['sizeid'] > 0 && $move['colorid'] > 0) {
                $sizeColorStoreDetailId = R::getCell("SELECT sizecolorstoredetail.id
                            FROM sizecolorstoredetail
                            WHERE productid = $productId and storeid = $storeid and sizeid = $sizeId and colorid = $colorId ");
            }
            $storedetailData = storeHelper::getStoreDetails($storeid, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);
            $allStoredetailData = $storedetailData[0];
            $storedetailId = $storedetailData[1];
            $productquantityBefore = $storedetailData[2];
            $finalquantity = $move['productquantity'];
            if ($move['storereporttype'] == 1) { //it was decrease,so now increase
                increaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 1, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
            } else if ($move['storereporttype'] == 0) { //it was increase,so now decrease
                decreaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity, "sellbilldetailid", $detailId, $productId, "sellbilldetail", $totalPrice, $billDiscountVal, $billTotalBeforeDiscount, 0, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
            }
            R::exec('DELETE FROM storereport where storereportid=' . $move['storereportid']);
        }
        $dailyentryid = R::getCell('select dailyentryid from sellbilloffer where sellbillid=' . $offerId);
        //قيود اليومية
        foreach (explode(',', $dailyentryid) as $entryid) {
            reverseEntryWithItsID($entryid, 1);
        }
    }

    public function __destruct()
    {
        parent::__destruct();
    }
}
require_once("_master/fireApi.php");
