<?php
  $response = array();
  require_once __DIR__ . '/catchexception.php';
  // include db connect class
  require_once __DIR__ . '/db_config.php';
  // connecting to db 
 
  $devicecode = urldecode($_POST['paradevicecode']);
  $imeino = urldecode($_POST['paraimeino']);
  $salesarray=$_POST['salesarray'];
  $salesitemarray=$_POST['salesitem'];
  $salescount = urldecode($_POST['parasalescount']);
  $billdate = urldecode($_POST['parabilldate']);

  $dbsalescount=0;
  //$success=array();
  //$failure=array();
  $response["salescount"] = array();

  //  $devicecode = 122;
  // $imeino = '11602d03b4a5684e';
  // $billdate='1643826600000';
  // $salesarray=''; 

  // $salesitemarray='';  

  // // $salesarray='{}';
  // // $salesitemarray='{}';
  // $salescount = 5; 
   
  $response1["TransactionDetails"]=array();
  $last_id ='';

  

  $salestransactiondetails=str_replace('{"JSonObject":', '', $salesarray);
  $salestransactiondetails=substr_replace($salestransactiondetails, "", -1);
  $salestransactiondetails=json_decode($salestransactiondetails,true);

  $salesitemtransactiondetails=str_replace('{"JSonObject":', '', $salesitemarray);
  $salesitemtransactiondetails=substr_replace($salesitemtransactiondetails, "", -1);
  $salesitemtransactiondetails=json_decode($salesitemtransactiondetails,true);
 

  $getmainbillcode='';
  $getitembillcode='';
  $getstockbillcode='';

  date_default_timezone_set('Australia/Melbourne');
  $date = date('Y-m-d H:i:s', time());  
  $stamp = strtotime($date); // get unix timestamp
  $time_in_ms = $stamp*1000;  
  $getdatetime = number_format($time_in_ms, 0, '.', '');

  
    
   
  if(count($salestransactiondetails) > 0){
    $getsalescount='';
    $response["SalesTransactionDetails"] = array();
    $response["SalesItemTransactionDetails"] = array(); 
  
    $SalesItemarrays = array();      
    $sql="INSERT into tblsyncdetails (imeino,syncdate,synctype,devicecode) values 
    ($1,now(),'Sales',$2 )";  
    $resultmax=  pg_prepare($con,"sql",$sql);
  $data = [$imeino,$devicecode ];
  $result = pg_execute($con,"sql",$data);

     //Insert user log for maintaining logs      
      $query = 'INSERT into tbluserlog(userid, originator, createdtime, "Action") values ($1,$2,now(),$3) RETURNING autonum';
      $result1 = pg_prepare($con,"query",$query);
      $data = [$devicecode,'Insert Sales Return','Insert'];
      $res = pg_execute($con,"query",$data);
        // get masker id
      while ($row = pg_fetch_row($res)) {
        $last_id=$row[0]; 
      }

      /*$salescountquery = "SELECT coalesce(count(*),0) from tblsales where transactiondate=$1 and deviceid=$2";
      $result1 = pg_prepare($con,"salescountquery",$salescountquery);
      $data = [$billdate,$imeino];
      $res = pg_execute($con,"salescountquery",$data);
        // get masker id
      while ($row = pg_fetch_row($res)) {
        array_push($response["salescount"], $row[0]);
      }*/
      

    $j=0;
    foreach ($salestransactiondetails as $val) {
        $j++;
        $rowcntqryval="rowcntqry".$j;  
         //Get unique count 
         /* $rowcntqry='SELECT coalesce(count(*),0) as count from tblsales where   transactionno='.$val['transactionno'].' and devicecode='.$val['devicecode'].' and branchcode='.$val['branchcode'].' and voucherno='.$val['voucherno'].';';*/
          $rowcntqry="SELECT coalesce(count(*),0) as count from tblsales where   transactionno=$1 and deviceid=$2 and branchcode=$3 and voucherno=$4;";
          $resultmax =  pg_prepare($con,$rowcntqryval,$rowcntqry); 
          $data = [$val['transactionno'],$val['devicecode'],$val['branchcode'],$val['voucherno'] ];
          $res = pg_execute($con,$rowcntqryval,$data);
          if (!empty($res)) {
              if (pg_num_rows($res) > 0) {   
                while ($row = pg_fetch_assoc($res)) {
                    $getmainbillcode= $row["count"] ;
                }
              }
          } 
        //  echo $rowcntqry;

      if( $getmainbillcode==0){
            $varqueryinsertval="varqueryinsert".$j;
            
			$modeofpayment = 1;
			if(array_key_exists("modeofpayment",$val)) {
			
				$modeofpayment = $val['modeofpayment'];
			}

      $valsessionid = 0;
      if(array_key_exists("sessionid",$val)) {
        if($val['sessionid'] == 'null' || $val['sessionid'] =='' || $val['sessionid'] == null){
          $valsessionid = 0;
        }
        else{
            $valsessionid = $val['sessionid'];
        }
        
      }
            //Insert Sales   
            $varqueryinsert = "INSERT INTO  tblsales (transactionno, voucherno, deviceid, transactiondate, grandtotal, noofitems, salestime, createddate, syncflag, statuscode, syncdate,branchcode,makerid,cancelflag,modeofpayment,customermobileno,customername,cashamount,creditamount,onlineamount,onlineorders,sessionid,netamount,discper,discamount,cgstamount,sgstamount,basicamount) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28 )  ";
            $result1 = pg_prepare($con,$varqueryinsertval,$varqueryinsert);
            $netamt = $val['grandtotal'];
            if($val['netamount'] != null && $val['netamount'] != 0 ){
              $netamt = $val['netamount'];
            }
            $data = [$val['transactionno'],$val['voucherno'],$val['devicecode'],$val['transactiondate'],$val['grandtotal'],$val['noofitems'],$val['salestime'],$val['createddate'],$val['syncflag'],$val['statuscode'],$getdatetime,$val['branchcode'],$last_id,$val['cancelflag'],$modeofpayment,$val['mobileno'],$val['customername'] ,$val['cashamount'] ,$val['creditamount'] ,$val['onlineamount'] ,$val['onlineorders'],$valsessionid,$netamt,$val['discper'],$val['discamount'],$val['cgstamount'],$val['sgstamount'],$val['subtotal']  ];

            $res1 = pg_execute($con,$varqueryinsertval,$data);
         
          if (!empty($res1)) {      
            $i=0;
            foreach ($salesitemtransactiondetails as $vals) {   
                $i++;                    
              if($vals['transactionno'] ==  $val['transactionno'] && $vals['devicecode'] ==  $val['devicecode']  )
              {
                $getitembillcode='';

                $rowitemcntqryval="rowitemcntqry".$i;  
               //Get unique count 
                $rowitemcntqry="SELECT coalesce(count(*),0) as count from tblsalesitemdetails where transactionno=$1 and deviceid=$2 and branchcode =$3 and itemcode=$4 and syncautonum=$5 ;";
                $resultmax =  pg_prepare($con,$rowitemcntqryval,$rowitemcntqry); 
                $data = [$val['transactionno'],$vals['devicecode'],$val['branchcode'],$vals['itemcode'],$vals['autonum'] ];
                $res = pg_execute($con,$rowitemcntqryval,$data);
                if (!empty($res)) {
                    if (pg_num_rows($res) > 0) {   
                      while ($row = pg_fetch_assoc($res)) {
                          $getitembillcode= $row["count"] ;
                      }
                    }
                } 
 
                if( $getitembillcode==0){

                    $varqueryinsertitemval="varqueryinsertitem".$i;
                    //Insert Sales Return Items
                    $varqueryinsert = "INSERT INTO  tblsalesitemdetails ( transactiondate, transactionno, voucherno, deviceid, branchcode, itemcode, qty, price, amount, createddate, updateddate, syncflag, syncautonum,syncdate,basicrate,basicamount)  values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16)  ";
                    $result1 = pg_prepare($con,$varqueryinsertitemval,$varqueryinsert);

                    $data = [$val['transactiondate'],$vals['transactionno'],$vals['voucherno'],$vals['devicecode'],$vals['branchcode'],$vals['itemcode'],$vals['qty'],$vals['price'],$vals['amount'],$vals['createddate'],$vals['updateddate'],$vals['syncflag'],$vals["autonum"],$getdatetime,$vals["basicrate"],$vals["basicamount"] ];

                    $res2 = pg_execute($con,$varqueryinsertitemval,$data);  
                    if (!empty($res2)) { 
                      array_push($response["SalesTransactionDetails"], $vals['transactionno']
                    );
                      array_push($response["SalesItemTransactionDetails"],$vals['transactionno']);
                    }
                }
              }
            }
          }
        }
      else{

         $varquerydeletesalesitemsval="varquerydeletesalesitems".$j;
        //Delete sales items
        $deletesalesitem = 'DELETE from tblsalesitemdetails where  transactionno=$1 and branchcode=$2 and deviceid=$3 ';
        $result1 = pg_prepare($con,$varquerydeletesalesitemsval,$deletesalesitem);
        $data = [$val['transactionno'],$val['branchcode'],$val['devicecode']];
        $resultdelete = pg_execute($con,$varquerydeletesalesitemsval,$data); 

        
        if (!empty($resultdelete)) { 

          $varquerydeletesalesval="varquerydeletesales".$j;
          //Delete Sales
          $deletesales = 'DELETE from tblsales where  transactionno=$1 and branchcode=$2 and deviceid=$3   ';
          $result1 = pg_prepare($con,$varquerydeletesalesval,$deletesales);
          $data = [$val['transactionno'],$val['branchcode'],$val['devicecode']];
          $resultdelete1 = pg_execute($con,$varquerydeletesalesval,$data);  

          
          if (!empty($resultdelete1)) { 
           
		   $modeofpayment = 1;
			if(array_key_exists("modeofpayment",$val)) {
				
				$modeofpayment = $val['modeofpayment'];
			}

        $valsessionid = 0;
      if(array_key_exists("sessionid",$val)) {
        if($val['sessionid'] == 'null' || $val['sessionid'] =='' || $val['sessionid'] == null){
          $valsessionid = 0;
        }
        else{
            $valsessionid = $val['sessionid'];
        }
        
      } 
       $varqueryinsertval1="varqueryinsertval".$j;
            //Insert Sales   
            $varqueryinsert = "INSERT INTO  tblsales (transactionno, voucherno, deviceid, transactiondate, grandtotal, noofitems, salestime, createddate, syncflag, statuscode, syncdate,branchcode,makerid,cancelflag,modeofpayment,customermobileno,customername,cashamount,creditamount,onlineamount,onlineorders,sessionid,netamount,discper,discamount,cgstamount,sgstamount,basicamount) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28)  ";
            $result1 = pg_prepare($con,$varqueryinsertval1,$varqueryinsert);
            $netamt = $val['grandtotal'];
            if($val['netamount'] != null && $val['netamount'] != 0 ){
              $netamt = $val['netamount'];
            }
            $data = [$val['transactionno'],$val['voucherno'],$val['devicecode'],$val['transactiondate'],$val['grandtotal'],$val['noofitems'],$val['salestime'],$val['createddate'],$val['syncflag'],$val['statuscode'],$getdatetime,$val['branchcode'],$last_id,$val['cancelflag'],$modeofpayment,$val['mobileno'],$val['customername'] ,$val['cashamount'] ,$val['creditamount'] ,$val['onlineamount'] ,$val['onlineorders'],$valsessionid,$netamt,$val['discper'],$val['discamount'],$val['cgstamount'],$val['sgstamount'],$val['subtotal'] ];
 
             $res1 = pg_execute($con,$varqueryinsertval1,$data); 

            if (!empty($res1)) 
            {
              $i=0;
              foreach ($salesitemtransactiondetails as $vals) {   
                $i++;                    
                 if($vals['transactionno'] ==  $val['transactionno'] && $vals['devicecode'] ==  $val['devicecode']  )
                {
                  $getitembillcode='';

                  $rowitemcntqryval="rowitemcntqry".$i;  
                 //Get unique count 
                  $rowitemcntqry="SELECT coalesce(count(*),0) as count from tblsalesitemdetails where transactionno=$1 and deviceid=$2 and branchcode =$3 and itemcode=$4 and syncautonum=$5 ;";
                  $resultmax =  pg_prepare($con,$rowitemcntqryval,$rowitemcntqry); 
                  $data = [$val['transactionno'],$vals['devicecode'],$val['branchcode'],$vals['itemcode'],$vals['autonum'] ];
                  $res = pg_execute($con,$rowitemcntqryval,$data);
                  if (!empty($res)) {
                      if (pg_num_rows($res) > 0) {   
                        while ($row = pg_fetch_assoc($res)) {
                            $getitembillcode= $row["count"] ;
                        }
                      }
                  } 
   
                  if( $getitembillcode==0){

                      $varqueryinsertitemval="varqueryinsertitem".$i;
                      //Insert Sales Return Items
                      $varqueryinsert = "INSERT INTO  tblsalesitemdetails (  transactiondate,transactionno, voucherno, deviceid, branchcode, itemcode, qty, price, amount, createddate, updateddate, syncflag, syncautonum,syncdate,basicrate,basicamount)  values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16)  ";
                      $result1 = pg_prepare($con,$varqueryinsertitemval,$varqueryinsert);

                      $data = [$val['transactiondate'],$vals['transactionno'],$vals['voucherno'],$vals['devicecode'],$vals['branchcode'],$vals['itemcode'],$vals['qty'],$vals['price'],$vals['amount'],$vals['createddate'],$vals['updateddate'],$vals['syncflag'],$vals["autonum"],$getdatetime,$vals["basicrate"],$vals["basicamount"] ];

                      $res2 = pg_execute($con,$varqueryinsertitemval,$data);  
                      if (!empty($res2)) { 
                        array_push($response["SalesTransactionDetails"], $val['transactionno']);
                        array_push($response["SalesItemTransactionDetails"],$vals['transactionno']);
                      }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
 
  if($imeino != ''){
      $salescountquery = "SELECT coalesce(count(*),0) from tblsales where transactiondate=$1 and deviceid=$2";
      $result1 = pg_prepare($con,"salescountquery",$salescountquery);
      $data = [$billdate,$imeino];
      $res = pg_execute($con,"salescountquery",$data);
        // get masker id
      while ($row = pg_fetch_row($res)) {
        
       $dbsalescount=$row[0];

//echo $dbsalescount.",". $salescount;
       
      }
//echo $salescount;
 //echo $dbsalescount;

    }
    
      if($dbsalescount == $salescount){
          //echo 'hi';
          array_push($response["salescount"], 1);
          //echo $response["salescount"] ."gg";
      }else{
          array_push($response["salescount"], 0);
      }
    

  array_push($response1["TransactionDetails"], $response);

  echo json_encode($response1);

 mch_db_release($con);

?>