/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Poslogreport the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Poslogreport::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
   public function actionPosSaveBill()
    {
        $postedData = $this->getPostedData();
        $order = new Order;
        $payment = new Payment;
        $rtn = false;
        $trans = Yii::app()->db->beginTransaction();
        try{
            $currentmode = (empty($postedData['currentmode'])?0:$postedData['currentmode']);
            $oldorderid = (empty($postedData['oldorderid'])?0:$postedData['oldorderid']);
            
            $closedstsid = $this->getStatusIdFromName(Helper::CONST_CLOSED);
            $ordersts = $closedstsid;
            $noerror = true;
            $oldorder = null;
            if($currentmode != 0 && $oldorderid == 0)
            {
                $noerror = false;
            }
            else if($currentmode == 1 || $currentmode == 3)
            {
                $oldorder = Order::model()->findByPk($oldorderid);
                if(empty($oldorder))
                {
                    $noerror=false;
                }
                else
                {
                    if($currentmode == 1)
                    {
                        $refundoldstsid = $this->getStatusIdFromName(Helper::CONST_REFUNDOLD);
                        $oldorder->status = $refundoldstsid;

                        $refundnewstsid = $this->getStatusIdFromName(Helper::CONST_REFUNDNEW);
                        $ordersts = $refundnewstsid;
                    }else
                    {
                        $canceloldstsid = $this->getStatusIdFromName(Helper::CONST_CANCELOLD);
                        $oldorder->status = $canceloldstsid;

                        $cancelnewstsid = $this->getStatusIdFromName(Helper::CONST_CANCELNEW);
                        $ordersts = $cancelnewstsid;
                    }
                }
            }
            else if($currentmode == 2)
            {
                $oldorder = Order::model()->findByPk($oldorderid);
                if(empty($oldorder))
                {
                    $noerror=false;
                }
                else
                {
                    $refundoldstsid = $this->getStatusIdFromName(Helper::CONST_EXCHANGEOLD);
                    $oldorder->status = $refundoldstsid;

                    $refundnewstsid = $this->getStatusIdFromName(Helper::CONST_EXCHANGENEW);
                    $ordersts = $refundnewstsid;  
                }
            }
            if(!$noerror)
            {
                $RetCode = Helper::CONST_Error;
                $message = Helper::CONST_OldBillNotFound_Message;
                $data = array();
                $this->returnJsonResponse($RetCode, $data, $message);
            }
            $order->status = $ordersts;
            $order->addnlinfo = $oldorderid;
            $customer_id = $postedData['customer_id'];
            $payment_modecheck = (empty($postedData['payment_modecheck'])?-1:$postedData['payment_modecheck']);
            if($payment_modecheck == '-1')
            {
                $payment_mode = $postedData['payment_mode'];
            }
            else
            {
                $payment_mode = Helper::CONST_OnAccount;
            }            
            $exchange = $postedData['exchange'];
            $roundoff = (empty($postedData['roundoff'])?0:$postedData['roundoff']);            
            $lineItems = $postedData['lineItems'];
            
            $order->type = Helper::CONST_Order;
            $order->customer_id = $customer_id;
            $order->created_id = Yii::app()->user->person->id;
            $order->modified_id = Yii::app()->user->person->id;
            $order->createdemp_id = Yii::app()->user->person->id;
            $order->modifiedemp_id = Yii::app()->user->person->id;                        
            $isconvert = $this->IsConversion($order);
            $extId = ($this->getEnableautoordrid()?($isconvert?null:$order->qoi_id):($isconvert?$order->new_id:$order->qoi_id));
            $isautogenerated = false;
            $curtype = $order->type;
            $isnew = empty($order->id);
            $gnrtdId = $this->getOrderAutoId($curtype, $isnew, $extId, $isautogenerated, $isconvert);
            if($isautogenerated)
            {
                $order->qoi_id = $gnrtdId;                
            }
            $order->name = $order->qoi_id;            
            $totalBilltax = 0;
            $totalBillcost = 0;
            $totalBillamount = 0;
            $orderproducts = array();
            $temporders = array();
            foreach($lineItems as $lineitem)
            {
                $orderproduct = new Orderproduct;
                $temppurchasedetails=new Poslogreport;
                $qnty = $lineitem['quantity'];            
                $temppurchasedetails->sold_out = $qnty;
                $temporders[] = $temppurchasedetails;
                $prdprice = $lineitem['unit_sp'];
                $lineitemdisc = $lineitem['disc'];
                $prdid = $lineitem['productprice'][0]['product_id'];
                $prdprcid = $lineitem['productprice'][0]['id'];
                $prdcost = $lineitem['productprice'][0]['unit_cp'];
                $prdtax = $lineitem['productprice'][0]['tax'];
                $skucode = $lineitem['productprice'][0]['sku'];
                $temppurchasedetails->barcode = $skucode;
                
                $lineitemcost =  $qnty * $prdcost;                                
                $lineitemamount = $qnty * $prdprice;
                $lineitemtax = $qnty * $prdtax;
                $lineitemamount += $lineitemtax - $lineitemdisc;
                
                $orderproduct->product_id = $prdid;
                $orderproduct->productprice_id = $prdprcid;
                $orderproduct->cost = $lineitemcost;
                $orderproduct->tax = $lineitemtax;
                
                $orderproduct->quantity = $qnty;
                $orderproduct->unit_sp = $prdprice;                
                $orderproduct->amount = $lineitemamount;
                $orderproduct->disc = $lineitemdisc;
                if($lineitemamount > 0)
                {
                    $orderproduct->discper = round(($lineitemdisc/$lineitemamount * 100),2);
                }
                else
                {
                   $orderproduct->discper = 0; 
                }
                
                $orderproducts[] = $orderproduct;
                
                $totalBilltax += $lineitemtax;
                $totalBillcost += $lineitemcost;
                $totalBillamount += $lineitemamount;
            }
            $billdiscount = $postedData['billdiscount'];
            if($currentmode == '1' || $currentmode == '3')
            {
                $billdiscount = $billdiscount * -1;
            }
            if($currentmode == '1' || $currentmode == '2' || $currentmode == '3')
            {
                $roundoff = $roundoff * -1;
            }
            $totalBillamount  = $totalBillamount - $billdiscount + $roundoff;
            if($currentmode == 2 && $totalBillamount <= 0)
            {
                $order->exchange = -$totalBillamount;//should add the amount in the name 'getback old bill discount'
                $totalBillamount = 0;
            }
            else if($currentmode != 1 && $currentmode != 2 
                    && $currentmode != 3 && $totalBillamount <= 0)
            {
                $RetCode = Helper::CONST_Error;
                $message = Helper::CONST_InvalidBillAmount_Message;
                $data = array();
                $this->returnJsonResponse($RetCode, $data, $message);
            }            
            $order->disc = $billdiscount;
            $order->roundoff = $roundoff;            
            $order->tax = $totalBilltax;
            $order->cost = $totalBillcost;
            $order->amount = $totalBillamount;
            if(strtolower($payment_mode) === strtolower(Helper::CONST_OnAccount))
            {
                $order->paid = 0;
            }
            else
            {
               $order->paid =  $order->amount;
            }
            
            $tenderedamount = $postedData['tenderedamount'];
            $balancereturned = $postedData['balancereturned'];
            $paymentdetails = $postedData['paymentdetails'];
            switch($currentmode)
            {
                case 1:
                    $paymentdetails = $paymentdetails . ':Refund:';
                    break;
                case 2:
                    $paymentdetails = $paymentdetails . ':Exchange:';
                    break;
                case 3:
                    $paymentdetails = $paymentdetails . ':Cancel:';
                    break;
                default:
                    break;
            }
            $payment->person_id = Yii::app()->user->person->id;
            $payment->amount = $totalBillamount;
            $payment->party_id = $customer_id;
            $payment->type = $payment_mode;
            $payment->tendered = $tenderedamount;
            $payment->balreturned = $balancereturned;
            $payment->details = $paymentdetails;
            $payment->direction = Helper::CONST_Inwards;
            
            $rtn = true;
            if(!empty($oldorder))
            {
                $rtn = $oldorder->save();
            }
            if($rtn)
            {
                $this->setOrderConfigs($order);
                $rtn = $order->save();
                if($rtn)
                {
                    $rtn = $this->updateOrderAutoId($order->qoi_id);
                    if($rtn)
                    {
                        foreach($orderproducts as $orderproduct)
                        {
                            $orderproduct->order_id = $order->id;
                            $orderproduct->order_type = $order->type;     
                            $rtn = $orderproduct->save();
                            if(!$rtn) break;
                        }
                        if($rtn)
                        {
                            $payment->order_id = $order->id;
                            $rtn = $payment->save();
                        }
                    }
                
                    $poslogs = new Poslogreport;
                        foreach($temporders as $temppurchasedetails)
                        {   
                             $quantities = $temppurchasedetails->sold_out;                            
                             $barcode = $temppurchasedetails->barcode;
                             
                             $rowsql = "select id from subproductprices where sku='$barcode'";
                             $result = Yii::app()->db->createCommand( $rowsql )->queryScalar();                  
                             $product = Subproductprice::model()->findByPk($result);
                             
                             $stockupdate = "update `subproductprices` set `initial_stock`=`initial_stock`-'$quantities' where `id`='$result'";
                             Yii::app()->db->createCommand($stockupdate)->execute(); 
                             
                             $rowsqlquery = "select `sno` from `poslogreport` where `barcode`='$barcode' and `log_status`=0";
                             $resultset = Yii::app()->db->createCommand( $rowsqlquery )->queryScalar();
                             
                             $rowsqlquery1 = "select `stock` from `subproductprices` where `sku`='$barcode'";
                             $stockresult = Yii::app()->db->createCommand( $rowsqlquery1)->queryScalar();
                             
                             if($resultset=="")
                             {
                              $insertrowsql = "insert into `poslogreport`(`date`,`barcode`,`previous_stock`,`current_stock`) values(CURDATE(),'$barcode','$stockresult','$stockresult')";
                              $result = Yii::app()->db->createCommand( $insertrowsql )->execute(); 
                             }
                
                             $rowsqlupdate = "select sno from poslogreport where barcode='$barcode' and `log_status`=0";
                             $resultupdate = Yii::app()->db->createCommand( $rowsqlupdate )->queryScalar();                  
                             $productupdate = Poslogreport::model()->findByPk($resultupdate);
                             
                             $rtn = !empty($productupdate);
                             if($rtn)
                              {
                                 if($quantities>0)
                                 {
                                 $productupdate->current_stock -= $quantities;
                                 $rtn = $productupdate->save();
                                 }
                                 else 
                                 {
                                  $cancelstockupdate = "update `poslogreport` set `rtn_product_quantity`=-$quantities where `sno`='$resultupdate'";
                                  Yii::app()->db->createCommand($cancelstockupdate)->execute();
                                 }
                               }
                        }                                        
                }
            }
        }catch(Exception $e){
            $rtn = false;
        }
        if($rtn)
        {     
//            $curr_date=Yii::app()->Date->now();
            $trans->commit();
            $RetCode = Helper::CONST_Error_None;
            $message = 'Saved Bill No.:.' .$order->qoi_id;
            $data = array(); 
           $this->printSavedbill($postedData,$order->qoi_id);
        }else
        {
            $trans->rollback();
            $RetCode = Helper::CONST_Error;
            $message = $cancelstockupdate;
            $data = array();
        }
        $this->returnJsonResponse($RetCode, $data, $message);        
    }