<?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']);
    $parasessionarray=$_POST['parasessionarray'];

     /*$devicecode ='249';
    $imeino = 'eba7eac7c658ca44';
    $paracasharray='{"JSonObject":[{"autonum":"1","transactionno":"1","devicecode":"eba7eac7c658ca44","branchcode":"2","totalamount":"0","closedate":"1619116200000","createddate":"1619166396231","syncflag":"0","cashinhand":"150"}]}';*/

  

   

  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 ='';

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

    

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

     
    
try{
  if(count($sessiondetails) > 0){
    $getsalescount='';
     $response["SessionIdDetails"] = array();
     $response["SessionCloseDateDetails"] = array();
    
       $getschedulecount='';       

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

                $data = [$val['sessionid'],$val['devicecode'],$val['branchcode'],$val['sessionclosedate']];
                $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){
                 $sessioncloseval = "insertsalesclose".$j;
                //Insert Close sales 
                 if($val['clientcode'] == '' || $val['clientcode'] == 'null' || $val['clientcode']== null){
                  $val['clientcode'] = 0;
                 }
                $varqueryinsertdenomination = "INSERT INTO  tblsessionclose (sessionid, sessionclosedate, actualcash, handcash, devicecode, createddate, syncflag, syncdate, makerid,clientcode,branchcode) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) ";
                $result1 = pg_prepare($con,$sessioncloseval,$varqueryinsertdenomination);

                $data = [$val['sessionid'],$val['sessionclosedate'],$val['actualcash'],$val['handcash'],$val['devicecode'],$val['createddate'],$val['syncflag'],$getdatetime ,$last_id,$val['clientcode'],$val['branchcode']]; 

                $resval = pg_execute($con,$sessioncloseval,$data);
   
                if (!empty($resval)) {   
                   array_push($response["SessionIdDetails"], $val['sessionid']);
                   array_push($response["SessionCloseDateDetails"], $val['sessionclosedate']);
                 }
             }else{

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

               
               if (!empty($deleteresult)) {  
               
                 $sessioncloseval1 = "insertsalesclose1".$j;
                   if($val['clientcode'] == '' || $val['clientcode'] == 'null' || $val['clientcode']== null){
                  $val['clientcode'] = 0;
                 }
                $varqueryinsertdenomination = "INSERT INTO  tblsessionclose (sessionid, sessionclosedate, actualcash, handcash, devicecode, createddate, syncflag, syncdate, makerid,clientcode,branchcode) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) ";
                $result1 = pg_prepare($con,$sessioncloseval1,$varqueryinsertdenomination);

                $data = [$val['sessionid'],$val['sessionclosedate'],$val['actualcash'],$val['handcash'],$val['devicecode'],$val['createddate'],$val['syncflag'],$getdatetime ,$last_id,$val['clientcode'],$val['branchcode']]; 
                  $resval = pg_execute($con,$sessioncloseval1,$data);
      
                
                if (!empty($resval)) {   
                  array_push($response["SessionIdDetails"], $val['sessionid']);
                  array_push($response["SessionCloseDateDetails"], $val['sessionclosedate']);
                }
              }
             }
			 
			 /*$branchnamevar='';
			 $convertdateformat = "converttodateformat".$j;
                   $convertdateqry = " select to_char(to_timestamp($1/1000.0),'DD/MM/YYYY') as closingdate , branchname from tblbranchmaster where branchcode=$2";
                  $result1 = pg_prepare($con,$convertdateformat,$convertdateqry);
   
                  $data = [$val['sessionclosedate'],$val['branchcode'] ]; 
                  $resvalconvdate = pg_execute($con,$convertdateformat,$data);
				  $resultdate='';
				  if (!empty($resvalconvdate)) {
                    if (pg_num_rows($resvalconvdate) > 0) {   
                      while ($row = pg_fetch_assoc($resvalconvdate)) {
                          $resultdate= $row["closingdate"] ;
						  $branchnamevar=$row["branchname"];
                      }
                    }
                }
				  
			$apiToken = "1710419275:AAETRaljB5U5FD6i-dRZzeXHN97mqfrDpBs";  
    $data1 = [
        'chat_id' => '135183318',
        'text' => '<b>SALES CLOSE - <i>'.$resultdate.'</i></b>,<pre>Branch : <b><i>'.$branchnamevar.'</i></b>,</pre> <pre>Actual Sales Close Value : <b>'.$val['totalamount'].'</b>,</pre><pre>Hand Over Cash value : <b>'.$val['cashinhand'].'</b>.</pre>'
    ];

    $responsetelegram = file_get_contents("https://api.telegram.org/bot".$apiToken."/sendMessage?" . http_build_query($data1)."&parse_mode=HTML" );*/

			 
     }
     
         
}
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();
}
?>