<?php
$response = array();
require_once __DIR__ . '/catchexception.php';
// include db connect class
require_once __DIR__ . '/db_config.php'; 

    $devicecode = urldecode($_POST['paradevicecode']);
    $imeino = urldecode($_POST['paraimeino']);
    $paracashclosearray=$_POST['paracashclosearray'];

    //  $devicecode ='1289';
    // $imeino = '99caf25cb19a70cb';
    // $paracashclosearray='{"JSonObject":[{"autonum":"2","closedate":"1778005800000","devicecode":"99caf25cb19a70cb","createddate":"1778005800000","syncflag":"0","clientcode":"","branchcode":"6", "cashinhand":"1000", "credit":"2000", "onlineupi":"500", "onlineorder":"300", "complimentary":"100", "transactionno":"12345", "card":"4000"}]}';

  

   

  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, '.', '');

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

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

    

     $getcount='';
     $getscheduledate='';

     
    try{

  if(count($cashclosedetails) > 0){
    $getsalescount='';
     $response["CashTransactionDetails"] = array();
    
       $getschedulecount='';       

       $sql="INSERT into tblsyncdetails (imeino,syncdate,synctype,devicecode) values 
    ($1,now(),'Cash Close',$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 Cash Close','Insert'];
        $res = pg_execute($con,"query",$data);
          // get masker id
        while ($row = pg_fetch_row($res)) {
          $last_id=$row[0]; 
        }  
         $j=0; 
        
        foreach ($cashclosedetails as $val) {
              $j++;
               $rowcntqryval="rowcntqry".$j;  
               //Get unique count 
                $rowcntqry="SELECT coalesce(count(*),0) as count from tblcashclose where devicecode=$1 and branchcode=$2 and closedate=$3;";
                $resultmax =  pg_prepare($con,$rowcntqryval,$rowcntqry);

                $data = [$val['devicecode'],$val['branchcode'],$val['closedate']];
                $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){
                 $cashcloseval = "insertcashcloseval".$j;
                 $sessioncloseval1 = "insertsalesclose1".$j;
                   if($val['clientcode'] == '' || $val['clientcode'] == 'null' || $val['clientcode']== null){
                  $val['clientcode'] = 0;
                 }
                //Insert Close sales 
                $varqueryinsertdenomination = "INSERT INTO  tblcashclose (autonum,transactionno, devicecode, branchcode, closedate, createddate, syncflag, clientcode, cashinhand, 
                credit, onlineupi, onlineorder, complimentary, syncdate, makerid, refautonum, card) values ((select coalesce(max(autonum),0)+1 from tblcashclose),$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15, $16) ";
                $result1 = pg_prepare($con,$cashcloseval,$varqueryinsertdenomination);

                $data = [$val['transactionno'], $val['devicecode'] ,$val['branchcode'] , $val['closedate'],$val['createddate'],$val['syncflag'],$val['clientcode'],$val['cashinhand'], $val['credit'], $val['onlineupi'], $val['onlineorder'], $val['complimentary'],$getdatetime ,$last_id, $val['autonum'], $val['card']]; 

                $resval = pg_execute($con,$cashcloseval,$data);
   
                if (!empty($resval)) {   
                   array_push($response["CashTransactionDetails"], $val['closedate']);
                 }
             }else{

                $varquerydeleteval1="varquerydelete1".$j;
                //Delete close sales
                $deletereceipt = 'DELETE from tblcashclose where devicecode=$1 and branchcode=$2 and closedate=$3 ';
                $result1 = pg_prepare($con,$varquerydeleteval1,$deletereceipt);
                $data = [$val['devicecode'],$val['branchcode'],$val['closedate']];
                $deleteresult = pg_execute($con,$varquerydeleteval1,$data);

               
               if (!empty($deleteresult)) {  
               
               $cashcloseval1 = "insertcashcloseval1".$j;
               $sessioncloseval1 = "insertsalesclose1".$j;
                   if($val['clientcode'] == '' || $val['clientcode'] == 'null' || $val['clientcode']== null){
                  $val['clientcode'] = 0;
                 }
                 $varqueryinsertdenomination = "INSERT INTO  tblcashclose (autonum,transactionno, devicecode, branchcode, closedate, createddate, syncflag, clientcode, cashinhand, 
                credit, onlineupi, onlineorder, complimentary, syncdate, makerid, refautonum, card) values ((select coalesce(max(autonum),0)+1 from tblcashclose),$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15, $16) ";
                $result1 = pg_prepare($con,$cashcloseval1,$varqueryinsertdenomination);

                $data = [$val['transactionno'], $val['devicecode'] ,$val['branchcode'] , $val['closedate'],$val['createddate'],$val['syncflag'],$val['clientcode'],$val['cashinhand'], $val['credit'], $val['onlineupi'], $val['onlineorder'], $val['complimentary'],$getdatetime ,$last_id, $val['autonum'], $val['card']]; 
                $resval = pg_execute($con,$cashcloseval1,$data);
      
                
                if (!empty($resval)) {   
                  array_push($response["CashTransactionDetails"], $val['closedate']);
                }
              }
             }
     
         
    }
  }
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();
}
?>