<?php
$response = array();
require_once __DIR__ . '/catchexception.php';
// include db connect class
require_once __DIR__ . '/db_config.php';
// connecting to db 
   // check for post data   
    $devicecode = urldecode($_POST['paradevicecode']);
    $imeino = urldecode($_POST['paraimeino']);
    $salesarray=$_POST['salesarray'];  
     

    $response1["TransactionDetails"]=array();
    $last_id ='';


    /*$devicecode ='1';
    $imeino = 'f4f8ffbef470be87';
    $salesarray = '{"JSonObject":[{"transactionno":"12","voucherno":"11","devicecode":"4","branchcode":"1","transactiondate":"1611340200000","grandtotal":"580","noofitems":"2","salestime":"10:25 PM","createddate":"1611420911170","syncflag":"0","statuscode":"1","cancelflag":"1"}]}';

 */

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

  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["SalesStockTransactionDetails"] =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,'Cancel Sales','Cancel'];
      $res = pg_execute($con,"query",$data);
        // get masker id
      while ($row = pg_fetch_row($res)) {
        $last_id=$row[0]; 
      }  
      $j=0;
      $i=0;
      $p=0;
    foreach ($salestransactiondetails as $val) {
      $j++;
       $rowcntqryval="rowcntqry".$j;
      //Get unique count 
        $rowcntqry="SELECT  coalesce(count(*),0) as count from tblsales where  transactionno=$1 and voucherno=$2 and devicecode =$3 and branchcode =$4 and transactiondate=$5 ;";
        $resultmax=  pg_prepare($con,$rowcntqryval,$rowcntqry);
        $data = [$val['transactionno'],$val['voucherno'],$val['devicecode'],$val['branchcode'],$val['transactiondate'] ];
        $res = pg_execute($con,$rowcntqryval,$data);
        if (!empty($res)) {
            if (pg_num_rows($res) > 0) {   
              while ($row = pg_fetch_assoc($res)) {
                  $getcount= $row["count"] ;
              }
            }
        } 
        if( $getcount > 0){ 
           $updateqryval="updatesalesqry".$j;
          //Update sales transactions data
          $varqueryupdate = "UPDATE tblsales set cancelflag=$1, updateddate=$2 where transactionno=$3 and voucherno=$4 and devicecode =$5 and branchcode =$6 and transactiondate=$7   ";
            $result1 = pg_prepare($con,$updateqryval,$varqueryupdate);
            $data = ['1',$getdatetime ,$val['transactionno'],$val['voucherno'],$val['devicecode'],$val['branchcode'],$val['transactiondate'] ];
            $resval = pg_execute($con,$updateqryval,$data);
            if (!empty($resval)) {
              array_push($response["SalesTransactionDetails"], $val['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();
}
?>