<?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']);
  $devicecode = '1289';
  $imeino = '99caf25cb19a70cb';
  $salesarray='{"JSonObject": [
    {
        "transactionno": "196370",
        "voucherno": "117",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "transactiondate": "1778005800000",
        "grandtotal": "260",
        "noofitems": "3",
        "salestime": "04:55 PM",
        "createddate": "1778066674651",
        "syncflag": "1",
        "statuscode": "1",
        "cancelflag": "0",
        "modeofpayment": "3",
        "mobileno": "",
        "customername": " ",
        "cashamount": "0",
        "creditamount": "0",
        "onlineamount": "260",
        "onlineorders": "",
        "cgstamount": "6.19",
        "sgstamount": "6.19",
        "sessionid": "1",
        "netamount": "260",
        "discper": "0",
        "discamount": "0",
        "subtotal": "247.62",
        "takername": "default",
        "onlineorderamount": "0",
        "creditcustomercode": "0",
        "creditcustomeramount": "0"
    },
    {
        "transactionno": "196371",
        "voucherno": "118",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "transactiondate": "1778005800000",
        "grandtotal": "60",
        "noofitems": "1",
        "salestime": "04:55 PM",
        "createddate": "1778066747721",
        "syncflag": "1",
        "statuscode": "1",
        "cancelflag": "0",
        "modeofpayment": "1",
        "mobileno": "",
        "customername": " ",
        "cashamount": "60",
        "creditamount": "0",
        "onlineamount": "0",
        "onlineorders": "",
        "cgstamount": "1.43",
        "sgstamount": "1.43",
        "sessionid": "1",
        "netamount": "60",
        "discper": "0",
        "discamount": "0",
        "subtotal": "57.14",
        "takername": "default",
        "onlineorderamount": "0",
        "creditcustomercode": "0",
        "creditcustomeramount": "0"
    },
    {
        "transactionno": "196372",
        "voucherno": "119",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "transactiondate": "1778005800000",
        "grandtotal": "50",
        "noofitems": "2",
        "salestime": "04:58 PM",
        "createddate": "1778066889239",
        "syncflag": "1",
        "statuscode": "1",
        "cancelflag": "0",
        "modeofpayment": "1",
        "mobileno": "",
        "customername": " ",
        "cashamount": "50",
        "creditamount": "0",
        "onlineamount": "0",
        "onlineorders": "",
        "cgstamount": "1.19",
        "sgstamount": "1.19",
        "sessionid": "1",
        "netamount": "50",
        "discper": "0",
        "discamount": "0",
        "subtotal": "47.62",
        "takername": "default",
        "onlineorderamount": "0",
        "creditcustomercode": "0",
        "creditcustomeramount": "0"
    },
    {
        "transactionno": "196373",
        "voucherno": "120",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "transactiondate": "1778005800000",
        "grandtotal": "75",
        "noofitems": "2",
        "salestime": "04:59 PM",
        "createddate": "1778066983126",
        "syncflag": "1",
        "statuscode": "1",
        "cancelflag": "0",
        "modeofpayment": "3",
        "mobileno": "",
        "customername": " ",
        "cashamount": "0",
        "creditamount": "0",
        "onlineamount": "75",
        "onlineorders": "",
        "cgstamount": "1.79",
        "sgstamount": "1.79",
        "sessionid": "1",
        "netamount": "75",
        "discper": "0",
        "discamount": "0",
        "subtotal": "71.42",
        "takername": "default",
        "onlineorderamount": "0",
        "creditcustomercode": "0",
        "creditcustomeramount": "0"
    },
    {
        "transactionno": "196374",
        "voucherno": "121",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "transactiondate": "1778005800000",
        "grandtotal": "100",
        "noofitems": "1",
        "salestime": "05:00 PM",
        "createddate": "1778067010311",
        "syncflag": "1",
        "statuscode": "1",
        "cancelflag": "0",
        "modeofpayment": "1",
        "mobileno": "",
        "customername": " ",
        "cashamount": "100",
        "creditamount": "0",
        "onlineamount": "0",
        "onlineorders": "",
        "cgstamount": "2.38",
        "sgstamount": "2.38",
        "sessionid": "1",
        "netamount": "100",
        "discper": "0",
        "discamount": "0",
        "subtotal": "95.24",
        "takername": "default",
        "onlineorderamount": "0",
        "creditcustomercode": "0",
        "creditcustomeramount": "0"
    },
    {
        "transactionno": "196375",
        "voucherno": "122",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "transactiondate": "1778005800000",
        "grandtotal": "145",
        "noofitems": "4",
        "salestime": "05:02 PM",
        "createddate": "1778067123702",
        "syncflag": "1",
        "statuscode": "1",
        "cancelflag": "0",
        "modeofpayment": "3",
        "mobileno": "",
        "customername": " ",
        "cashamount": "0",
        "creditamount": "0",
        "onlineamount": "145",
        "onlineorders": "",
        "cgstamount": "3.45",
        "sgstamount": "3.45",
        "sessionid": "1",
        "netamount": "145",
        "discper": "0",
        "discamount": "0",
        "subtotal": "138.09",
        "takername": "default",
        "onlineorderamount": "0",
        "creditcustomercode": "0",
        "creditcustomeramount": "0"
    },
    {
        "transactionno": "196376",
        "voucherno": "123",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "transactiondate": "1778005800000",
        "grandtotal": "120",
        "noofitems": "1",
        "salestime": "05:02 PM",
        "createddate": "1778067157611",
        "syncflag": "1",
        "statuscode": "1",
        "cancelflag": "0",
        "modeofpayment": "3",
        "mobileno": "",
        "customername": " ",
        "cashamount": "0",
        "creditamount": "0",
        "onlineamount": "120",
        "onlineorders": "",
        "cgstamount": "2.86",
        "sgstamount": "2.86",
        "sessionid": "1",
        "netamount": "120",
        "discper": "0",
        "discamount": "0",
        "subtotal": "114.29",
        "takername": "default",
        "onlineorderamount": "0",
        "creditcustomercode": "0",
        "creditcustomeramount": "0"
    },
    {
        "transactionno": "196377",
        "voucherno": "124",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "transactiondate": "1778005800000",
        "grandtotal": "55",
        "noofitems": "2",
        "salestime": "05:03 PM",
        "createddate": "1778067185420",
        "syncflag": "1",
        "statuscode": "1",
        "cancelflag": "0",
        "modeofpayment": "3",
        "mobileno": "",
        "customername": " ",
        "cashamount": "0",
        "creditamount": "0",
        "onlineamount": "55",
        "onlineorders": "",
        "cgstamount": "1.31",
        "sgstamount": "1.31",
        "sessionid": "1",
        "netamount": "55",
        "discper": "0",
        "discamount": "0",
        "subtotal": "52.38",
        "takername": "default",
        "onlineorderamount": "0",
        "creditcustomercode": "0",
        "creditcustomeramount": "0"
    },
    {
        "transactionno": "196378",
        "voucherno": "125",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "transactiondate": "1778005800000",
        "grandtotal": "40",
        "noofitems": "1",
        "salestime": "05:03 PM",
        "createddate": "1778067228779",
        "syncflag": "1",
        "statuscode": "1",
        "cancelflag": "0",
        "modeofpayment": "3",
        "mobileno": "",
        "customername": " ",
        "cashamount": "0",
        "creditamount": "0",
        "onlineamount": "40",
        "onlineorders": "",
        "cgstamount": "0.95",
        "sgstamount": "0.95",
        "sessionid": "1",
        "netamount": "40",
        "discper": "0",
        "discamount": "0",
        "subtotal": "38.1",
        "takername": "default",
        "onlineorderamount": "0",
        "creditcustomercode": "0",
        "creditcustomeramount": "0"
    }
]}';
  $salesitemarray='{"JSonObject": [
    {
        "autonum": "337445",
        "transactionno": "196370",
        "voucherno": "117",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "1",
        "qty": "2",
        "price": 60,
        "amount": 120,
        "createddate": 1778066674651,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 57.14,
        "basicamount": 114.29
    },
    {
        "autonum": "337446",
        "transactionno": "196370",
        "voucherno": "117",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "316",
        "qty": "2",
        "price": 55,
        "amount": 110,
        "createddate": 1778066678526,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 52.38,
        "basicamount": 104.76
    },
    {
        "autonum": "337447",
        "transactionno": "196370",
        "voucherno": "117",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "383",
        "qty": "1",
        "price": 30,
        "amount": 30,
        "createddate": 1778066708327,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 28.57,
        "basicamount": 28.57
    },
    {
        "autonum": "337448",
        "transactionno": "196371",
        "voucherno": "118",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "1",
        "qty": "1",
        "price": 60,
        "amount": 60,
        "createddate": 1778066747721,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 57.14,
        "basicamount": 57.14
    },
    {
        "autonum": "337449",
        "transactionno": "196372",
        "voucherno": "119",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "51",
        "qty": "1",
        "price": 30,
        "amount": 30,
        "createddate": 1778066889239,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 28.57,
        "basicamount": 28.57
    },
    {
        "autonum": "337450",
        "transactionno": "196372",
        "voucherno": "119",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "1962",
        "qty": "1",
        "price": 20,
        "amount": 20,
        "createddate": 1778066900019,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 19.05,
        "basicamount": 19.05
    },
    {
        "autonum": "337451",
        "transactionno": "196373",
        "voucherno": "120",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "1367",
        "qty": "1",
        "price": 10,
        "amount": 10,
        "createddate": 1778066983126,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 9.52,
        "basicamount": 9.52
    },
    {
        "autonum": "337452",
        "transactionno": "196373",
        "voucherno": "120",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "1939",
        "qty": "1",
        "price": 65,
        "amount": 65,
        "createddate": 1778066990549,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 61.9,
        "basicamount": 61.9
    },
    {
        "autonum": "337453",
        "transactionno": "196374",
        "voucherno": "121",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "1955",
        "qty": "2",
        "price": 50,
        "amount": 100,
        "createddate": 1778067010311,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 47.62,
        "basicamount": 95.24
    },
    {
        "autonum": "337454",
        "transactionno": "196375",
        "voucherno": "122",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "52",
        "qty": "2",
        "price": 40,
        "amount": 80,
        "createddate": 1778067123702,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 38.1,
        "basicamount": 76.19
    },
    {
        "autonum": "337455",
        "transactionno": "196375",
        "voucherno": "122",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "51",
        "qty": "1",
        "price": 30,
        "amount": 30,
        "createddate": 1778067131849,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 28.57,
        "basicamount": 28.57
    },
    {
        "autonum": "337456",
        "transactionno": "196375",
        "voucherno": "122",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "536",
        "qty": "1",
        "price": 10,
        "amount": 10,
        "createddate": 1778067137391,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 9.52,
        "basicamount": 9.52
    },
    {
        "autonum": "337457",
        "transactionno": "196375",
        "voucherno": "122",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "1960",
        "qty": "1",
        "price": 25,
        "amount": 25,
        "createddate": 1778067149860,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 23.81,
        "basicamount": 23.81
    },
    {
        "autonum": "337458",
        "transactionno": "196376",
        "voucherno": "123",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "1",
        "qty": "2",
        "price": 60,
        "amount": 120,
        "createddate": 1778067157611,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 57.14,
        "basicamount": 114.29
    },
    {
        "autonum": "337459",
        "transactionno": "196377",
        "voucherno": "124",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "51",
        "qty": "1",
        "price": 30,
        "amount": 30,
        "createddate": 1778067185420,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 28.57,
        "basicamount": 28.57
    },
    {
        "autonum": "337460",
        "transactionno": "196377",
        "voucherno": "124",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "1960",
        "qty": "1",
        "price": 25,
        "amount": 25,
        "createddate": 1778067203535,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 23.81,
        "basicamount": 23.81
    },
    {
        "autonum": "337461",
        "transactionno": "196378",
        "voucherno": "125",
        "devicecode": "99caf25cb19a70cb",
        "branchcode": "124",
        "itemcode": "52",
        "qty": "1",
        "price": 40,
        "amount": 40,
        "createddate": 1778067228779,
        "updateddate": 0,
        "syncflag": 1,
        "basicrate": 38.1,
        "basicamount": 38.1
    }
]}';
  $salescount = '9';
  $billdate = '1778005800000';

  $dbsalescount=0;
  //$success=array();
  //$failure=array();
  $response["salescount"] = array();
   
  $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();      
    $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','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'];
			}
      // $modeofpayment = 1;
      $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,takername, onlineorderamount,creditcustomercode,creditcustomeramount, taxamount, taxname, exchangerate) 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,$29,$30,$31,$32, $33, $34, $35)  ";
            $result1 = pg_prepare($con,$varqueryinsertval,$varqueryinsert);
            $netamt = $val['grandtotal'];
            $discper = 0;
            $discamount = 0;
            $basicamount = 0;
            $cgstamount =0;
            $sgstamount =0;
            $taxamount =0;
            $taxname ='';
            $exchangerate =0;
            $takername = "";
            if(array_key_exists("takername",$val)) {
              if($val['takername'] != null && $val['takername'] != ""){
                $takername = $val['takername'];
              }
            }
            if(array_key_exists("netamount",$val)) {
              if($val['netamount'] != null && $val['netamount'] != 0 ){
                $netamt = $val['netamount'];
              }
            }
            if(array_key_exists("discper",$val)) {
              if($val['discper'] != null && $val['discper'] != 0 ){
                $discper = $val['discper'];
              }
            }
             if(array_key_exists("discamount",$val)) {
              if($val['discamount'] != null && $val['discamount'] != 0 ){
                $discamount = $val['discamount'];
              }
            }
            if(array_key_exists("subtotal",$val)) {
              if($val['subtotal'] != null && $val['subtotal'] != 0 ){
                $basicamount = $val['subtotal'];
              }
            }
            if(array_key_exists("cgstamount",$val)) {
              if($val['cgstamount'] != null && $val['cgstamount'] != 0 ){
                $sgstamount = $val['cgstamount'];
              }
            }
            if(array_key_exists("sgstamount",$val)) {
              if($val['sgstamount'] != null && $val['sgstamount'] != 0 ){
                $cgstamount = $val['sgstamount'];
              }
            }
            $onlineorderamount = 0;
            if(array_key_exists("onlineorderamount",$val)) {
              if($val['onlineorderamount'] != null && $val['onlineorderamount'] != 0 ){
                $onlineorderamount = $val['onlineorderamount'];
              }
            }
			
			$creditcustomercode = 0;
            if(array_key_exists("creditcustomercode",$val)) {
              if($val['creditcustomercode'] != null && $val['creditcustomercode'] != 0 ){
                $creditcustomercode = $val['creditcustomercode'];
              }
            }
			
			$creditcustomeramount = 0;
            if(array_key_exists("creditcustomeramount",$val)) {
              if($val['creditcustomeramount'] != null && $val['creditcustomeramount'] != 0 ){
                $creditcustomeramount = $val['creditcustomeramount'];
              }
            }

            if(array_key_exists("taxamount",$val)) {
              if($val['taxamount'] != null && $val['taxamount'] != 0 ){
                $taxamount = $val['taxamount'];
              }
            }

            if(array_key_exists("taxname",$val)) {
              if($val['taxname'] != null && $val['taxname'] != ""){
                $taxname = $val['taxname'];
              }
            }

            if(array_key_exists("exchangerate",$val)) {
              if($val['exchangerate'] != null && $val['exchangerate'] != 0 ){
                $exchangerate = $val['exchangerate'];
              }
            }

            $val['cancelflag']=0;
            $val['statuscode']=1;
            $val['syncflag']=1;
            $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,$discper,$discamount,$cgstamount,$sgstamount,$basicamount, $takername, $onlineorderamount, $creditcustomercode, $creditcustomeramount, $taxamount, $taxname, $exchangerate]; 
            $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;
                      $basicrate =0;
                      $basicamount =0;
                      if(array_key_exists("basicrate",$vals)) {
                        if($vals['basicrate'] != null && $vals['basicrate'] != 0 ){
                          $basicrate = $vals['basicrate'];
                        }
                      }
                      if(array_key_exists("basicamount",$vals)) {
                        if($vals['basicamount'] != null && $vals['basicamount'] != 0 ){
                          $basicamount = $vals['basicamount'];
                        }
                      }
                    //Insert Sales 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,$basicrate,$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,takername,onlineorderamount,creditcustomercode,creditcustomeramount, taxamount, taxname, exchangerate) 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,$29,$30,$31,$32, $33, $34, $35)  ";
            $result1 = pg_prepare($con,$varqueryinsertval1,$varqueryinsert);
           
            $netamt = $val['grandtotal'];
            $discper = 0;
            $discamount = 0;
            $basicamount = 0;
            $cgstamount =0;
            $sgstamount =0;
            $taxamount =0;
            $taxname ='';
            $exchangerate =0;
            $takername = "";
            if(array_key_exists("takername",$val)) {
              if($val['takername'] != null && $val['takername'] != ""){
                $takername = $val['takername'];
              }
            }
            if(array_key_exists("netamount",$val)) {
              if($val['netamount'] != null && $val['netamount'] != 0 ){
                $netamt = $val['netamount'];
              }
            }
            if(array_key_exists("discper",$val)) {
              if($val['discper'] != null && $val['discper'] != 0 ){
                $discper = $val['discper'];
              }
            }
             if(array_key_exists("discamount",$val)) {
              if($val['discamount'] != null && $val['discamount'] != 0 ){
                $discamount = $val['discamount'];
              }
            }
            if(array_key_exists("subtotal",$val)) {
              if($val['subtotal'] != null && $val['subtotal'] != 0 ){
                $basicamount = $val['subtotal'];
              }
            }
            if(array_key_exists("cgstamount",$val)) {
              if($val['cgstamount'] != null && $val['cgstamount'] != 0 ){
                $sgstamount = $val['cgstamount'];
              }
            }
            if(array_key_exists("sgstamount",$val)) {
              if($val['sgstamount'] != null && $val['sgstamount'] != 0 ){
                $cgstamount = $val['sgstamount'];
              }
            }
            $onlineorderamount = 0;
            if(array_key_exists("onlineorderamount",$val)) {
              if($val['onlineorderamount'] != null && $val['onlineorderamount'] != 0 ){
                $onlineorderamount = $val['onlineorderamount'];
              }
            }
			
			$creditcustomercode = 0;
            if(array_key_exists("creditcustomercode",$val)) {
              if($val['creditcustomercode'] != null && $val['creditcustomercode'] != 0 ){
                $creditcustomercode = $val['creditcustomercode'];
              }
            }
			
			$creditcustomeramount = 0;
            if(array_key_exists("creditcustomeramount",$val)) {
              if($val['creditcustomeramount'] != null && $val['creditcustomeramount'] != 0 ){
                $creditcustomeramount = $val['creditcustomeramount'];
              }
            }

             if(array_key_exists("taxamount",$val)) {
              if($val['taxamount'] != null && $val['taxamount'] != 0 ){
                $taxamount = $val['taxamount'];
              }
            }

            if(array_key_exists("taxname",$val)) {
              if($val['taxname'] != null && $val['taxname'] != ""){
                $taxname = $val['taxname'];
              }
            }

            if(array_key_exists("exchangerate",$val)) {
              if($val['exchangerate'] != null && $val['exchangerate'] != 0 ){
                $exchangerate = $val['exchangerate'];
              }
            }
            $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,$discper,$discamount,$cgstamount,$sgstamount,$basicamount,$takername,$onlineorderamount,$creditcustomercode, $creditcustomeramount, $taxamount, $taxname, $exchangerate];
           
             $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;

                      $basicrate =0;
                      $basicamount =0;
                      if(array_key_exists("basicrate",$vals)) {
                        if($vals['basicrate'] != null && $vals['basicrate'] != 0 ){
                          $basicrate = $vals['basicrate'];
                        }
                      }
                      if(array_key_exists("basicamount",$vals)) {
                        if($vals['basicamount'] != null && $vals['basicamount'] != 0 ){
                          $basicamount = $vals['basicamount'];
                        }
                      }
                      //Insert Sales 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,$basicrate,$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);

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