<?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 = 250;
  $imeino = '398bcd7a638d12b2';
  $salesarray='{"JSonObject":[{"transactionno":"61","voucherno":"35","devicecode":"398bcd7a638d12b2","branchcode":"2","transactiondate":"1612636200000","grandtotal":"910","noofitems":"3","salestime":"09:35 PM","createddate":"1612713949375","syncflag":"0","statuscode":"1","cancelflag":"0"},{"transactionno":"62","voucherno":"36","devicecode":"398bcd7a638d12b2","branchcode":"2","transactiondate":"1612636200000","grandtotal":"910","noofitems":"3","salestime":"09:36 PM","createddate":"1612713964056","syncflag":"0","statuscode":"1","cancelflag":"0"},{"transactionno":"63","voucherno":"1","devicecode":"398bcd7a638d12b2","branchcode":"2","transactiondate":"1612722600000","grandtotal":"170","noofitems":"2","salestime":"04:10 PM","createddate":"1612780798197","syncflag":"0","statuscode":"1","cancelflag":"0"},{"transactionno":"64","voucherno":"1","devicecode":"398bcd7a638d12b2","branchcode":"2","transactiondate":"1612981800000","grandtotal":"110","noofitems":"2","salestime":"10:25 AM","createddate":"1613019277983","syncflag":"0","statuscode":"1","cancelflag":"0"},{"transactionno":"65","voucherno":"2","devicecode":"398bcd7a638d12b2","branchcode":"2","transactiondate":"1612981800000","grandtotal":"94","noofitems":"2","salestime":"10:27 AM","createddate":"1613019420045","syncflag":"0","statuscode":"1","cancelflag":"0"}]}';

  $salesitemarray='{"JSonObject":[{"autonum":"1","transactionno":"61","voucherno":"35","devicecode":"398bcd7a638d12b2","branchcode":"2","itemcode":"1","qty":"1","price":50,"amount":50,"createddate":1612713946644,"updateddate":0,"syncflag":0},{"autonum":"2","transactionno":"61","voucherno":"35","devicecode":"398bcd7a638d12b2","branchcode":"2","itemcode":"2","qty":"1","price":60,"amount":60,"createddate":1612713947924,"updateddate":0,"syncflag":0},{"autonum":"3","transactionno":"61","voucherno":"35","devicecode":"398bcd7a638d12b2","branchcode":"2","itemcode":"3","qty":"1","price":800,"amount":800,"createddate":1612713949375,"updateddate":0,"syncflag":0},{"autonum":"4","transactionno":"62","voucherno":"36","devicecode":"398bcd7a638d12b2","branchcode":"2","itemcode":"1","qty":"1","price":50,"amount":50,"createddate":1612713962989,"updateddate":0,"syncflag":0},{"autonum":"5","transactionno":"62","voucherno":"36","devicecode":"398bcd7a638d12b2","branchcode":"2","itemcode":"2","qty":"1","price":60,"amount":60,"createddate":1612713963248,"updateddate":0,"syncflag":0},{"autonum":"6","transactionno":"62","voucherno":"36","devicecode":"398bcd7a638d12b2","branchcode":"2","itemcode":"3","qty":"1","price":800,"amount":800,"createddate":1612713964056,"updateddate":0,"syncflag":0},{"autonum":"7","transactionno":"63","voucherno":"1","devicecode":"398bcd7a638d12b2","branchcode":"2","itemcode":"1","qty":"1","price":50,"amount":50,"createddate":1612780797850,"updateddate":0,"syncflag":0},{"autonum":"8","transactionno":"63","voucherno":"1","devicecode":"398bcd7a638d12b2","branchcode":"2","itemcode":"2","qty":"2","price":60,"amount":120,"createddate":1612780798197,"updateddate":0,"syncflag":0},{"autonum":"9","transactionno":"64","voucherno":"1","devicecode":"398bcd7a638d12b2","branchcode":"2","itemcode":"1","qty":"1","price":50,"amount":50,"createddate":1613019277361,"updateddate":0,"syncflag":0},{"autonum":"10","transactionno":"64","voucherno":"1","devicecode":"398bcd7a638d12b2","branchcode":"2","itemcode":"2","qty":"1","price":60,"amount":60,"createddate":1613019277983,"updateddate":0,"syncflag":0},{"autonum":"11","transactionno":"65","voucherno":"2","devicecode":"398bcd7a638d12b2","branchcode":"2","itemcode":"16","qty":"2","price":32,"amount":64,"createddate":1613019418568,"updateddate":0,"syncflag":0},{"autonum":"12","transactionno":"65","voucherno":"2","devicecode":"398bcd7a638d12b2","branchcode":"2","itemcode":"5","qty":"1","price":30,"amount":30,"createddate":1613019420045,"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, '.', '');
   
  try{
  if(count($salestransactiondetails) > 0){
    $getsalescount='';
    $response["SalesTransactionDetails"] = array();
    $response["SalesItemTransactionDetails"] = array(); 
    $SalesItemarrays = array();      

     //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]; 
      }  
    $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;
            echo $val['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,$varqueryinsertval,$varqueryinsert);

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

            $res1 = pg_execute($con,$varqueryinsertval,$data);
         
          if (!empty($res1)) {      
            $i=0;
            foreach ($salesitemtransactiondetails as $vals) {   
              echo $vals['transactionno'];
                $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)  values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)  ";
                    $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 ];

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

echo 'Existing';
echo $val['transactionno'];
         $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)) { 
            echo 'insert';
           echo $val['transactionno'];

             $varqueryinsertval1="varqueryinsert1".$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,$varqueryinsertval1,$varqueryinsert);

            $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']];
 
            $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"] ;
                        }
                      }
                  } 
                  echo $getitembillcode;
   
                  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)  values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)  ";
                      $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 ];

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

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

  echo json_encode($response1);

 mch_db_release($con);
}
//catch exception
catch(Exception $e) {
mch_db_release($con);
echo 'Message: ' .$e->getMessage();
}

?>