<?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']; */
 
  $devicecode = 57;
  $imeino = 'f4f8ffbef470be87';
  $salesarray='{"JSonObject":[{"transactionno":"1","voucherno":"1","devicecode":"f4f8ffbef470be87","branchcode":"1","transactiondate":"1611599400000","grandtotal":"1370","noofitems":"4","salestime":"11:18 am","createddate":"1611640132320","syncflag":"0","statuscode":"1","cancelflag":"0"}]}';

  $salesitemarray='{"JSonObject":[{"autonum":"1","transactionno":"1","voucherno":"1","devicecode":"f4f8ffbef470be87","branchcode":"1","itemcode":"1","qty":"3","price":50,"amount":150,"createddate":1611640130196,"updateddate":0,"syncflag":0},{"autonum":"2","transactionno":"1","voucherno":"1","devicecode":"f4f8ffbef470be87","branchcode":"1","itemcode":"4","qty":"3","price":100,"amount":300,"createddate":1611640130770,"updateddate":0,"syncflag":0},{"autonum":"3","transactionno":"1","voucherno":"1","devicecode":"f4f8ffbef470be87","branchcode":"1","itemcode":"2","qty":"2","price":60,"amount":120,"createddate":1611640131457,"updateddate":0,"syncflag":0},{"autonum":"4","transactionno":"1","voucherno":"1","devicecode":"f4f8ffbef470be87","branchcode":"1","itemcode":"3","qty":"1","price":800,"amount":800,"createddate":1611640132320,"updateddate":0,"syncflag":0}]}'; 


  // $retailerjson=$_POST['retailerjson'];  
  $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, '.', '');
  $transactionno = 3000;
  $k=0;
  while($k<500){
    $transactionno = $transactionno + $k;
    $k=$k+1;
    echo $transactionno;
    if(count($salestransactiondetails) > 0){
    $getsalescount='';
    $response["SalesTransactionDetails"] = array();
    $response["SalesItemTransactionDetails"] = array(); 
    $SalesItemarrays = array();      
$salesquery="query".$k;  
     //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,$salesquery,$query);
      $data = [$devicecode,'Insert Sales Return','Insert'];
      $res = pg_execute($con,$salesquery,$data);
        // get masker id
      while ($row = pg_fetch_row($res)) {
        $last_id=$row[0]; 
      }  

    $j=0;
    foreach ($salestransactiondetails as $val) {
        $j++;
        $rowcntqryval="rowcntqry".$j.$k.$transactionno;  
         //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 = [$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;
            
            //Insert Sales   
            $varqueryinsert = "INSERT INTO  tblsales (transactionno, voucherno, deviceid, transactiondate, grandtotal, noofitems, salestime, createddate, syncflag, statuscode, syncdate,branchcode,makerid,cancelflag) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14 )  ";
            $result1 = pg_prepare($con,$varqueryinsertval,$varqueryinsert);

            $data = [$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']  ];

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

                $rowitemcntqryval="rowitemcntqry".$i.$k.$transactionno;  
               //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 = [$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.$k.$transactionno;
                    //Insert Sales Return Items
                    $varqueryinsert = "INSERT INTO  tblsalesitemdetails ( transactiondate, transactionno, voucherno, deviceid, branchcode, itemcode, qty, price, amount, createddate, updateddate, syncflag, syncautonum,syncdate)  values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)  ";
                    $result1 = pg_prepare($con,$varqueryinsertitemval,$varqueryinsert);

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

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

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

        
        if (!empty($resultdelete)) { 

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

          
          if (!empty($resultdelete1)) { 
           

             $varqueryinsertval1="varqueryinsert1".$j.$k.$transactionno;
             //Insert Sales   
            $varqueryinsert = "INSERT INTO  tblsales (transactionno, voucherno, deviceid, transactiondate, grandtotal, noofitems, salestime, createddate,syncflag, statuscode, syncdate,branchcode,makerid,cancelflag) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)  ";
            $result1 = pg_prepare($con,$varqueryinsertval1,$varqueryinsert);

            $data = [$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']];
 
            $res1 = pg_execute($con,$varqueryinsertval1,$data); 

            if (!empty($res1)) 
            {
              $i=0;
              foreach ($salesitemtransactiondetails as $vals) {   
                $i++;                    
                 
                  $getitembillcode='';

                  $rowitemcntqryval="rowitemcntqry".$i.$k.$transactionno;  
                 //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 = [$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.$k.$transactionno;
                      //Insert Sales Return Items
                      $varqueryinsert = "INSERT INTO  tblsalesitemdetails (  transactionno, voucherno, deviceid, branchcode, itemcode, qty, price, amount, createddate, updateddate, syncflag, syncautonum,syncdate)  values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)  ";
                      $result1 = pg_prepare($con,$varqueryinsertitemval,$varqueryinsert);

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

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

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

  echo json_encode($response1);

 mch_db_release($con);

?>