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

    //  $devicecode ='1289';
    // $imeino = '99caf25cb19a70cb';
    // $paradayclosearray='{"JSonObject":[{"autonum":"1","closedate":"1778005800000","devicecode":"99caf25cb19a70cb","createddate":"1778005800000","syncflag":"0","clientcode":"","branchcode":"6"},{"autonum":"2","closedate":"1778005800000","devicecode":"99caf25cb19a70cb","createddate":"1778005800000","syncflag":"0","clientcode":"","branchcode":"6"}]}';

  

   

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

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

    

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

     
    try{

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

       $sql="INSERT into tblsyncdetails (imeino,syncdate,synctype,devicecode) values 
    ($1,now(),'Day 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 Day Close','Insert'];
        $res = pg_execute($con,"query",$data);
          // get masker id
        while ($row = pg_fetch_row($res)) {
          $last_id=$row[0]; 
        }  
         $j=0; 
        
        foreach ($dayclosedetails as $val) {
              $j++;
               $rowcntqryval="rowcntqry".$j;  
               //Get unique count 
                $rowcntqry="SELECT coalesce(count(*),0) as count from tbldayclose 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){
                 $daycloseval = "insertdaycloseval".$j;
                 $sessioncloseval1 = "insertsalesclose1".$j;
                   if($val['clientcode'] == '' || $val['clientcode'] == 'null' || $val['clientcode']== null){
                  $val['clientcode'] = 0;
                 }
                //Insert Close sales 
                $varqueryinsertdenomination = "INSERT INTO  tbldayclose (autonum,closedate, devicecode, createddate, syncflag, syncdate, makerid,clientcode,branchcode) values ((select coalesce(max(autonum),0)+1 from tblsessionclose),$1,$2,$3,$4,$5,$6,$7,$8) ";
                $result1 = pg_prepare($con,$daycloseval,$varqueryinsertdenomination);

                $data = [$val['closedate'],$val['devicecode'],$val['createddate'],$val['syncflag'],$getdatetime ,$last_id,$val['clientcode'],$val['branchcode']]; 

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

                $varquerydeleteval1="varquerydelete1".$j;
                //Delete close sales
                $deletereceipt = 'DELETE from tbldayclose 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)) {  
               
               $daycloseval1 = "insertdaycloseval1".$j;
               $sessioncloseval1 = "insertsalesclose1".$j;
                   if($val['clientcode'] == '' || $val['clientcode'] == 'null' || $val['clientcode']== null){
                  $val['clientcode'] = 0;
                 }
                 $varqueryinsertdenomination = "INSERT INTO  tbldayclose (autonum,closedate, devicecode, createddate, syncflag, syncdate, makerid,clientcode,branchcode) values ((select coalesce(max(autonum),0)+1 from tblsessionclose),$1,$2,$3,$4,$5,$6,$7,$8) ";
                $result1 = pg_prepare($con,$daycloseval1,$varqueryinsertdenomination);

                $data = [$val['closedate'],$val['devicecode'],$val['createddate'],$val['syncflag'],$getdatetime ,$last_id,$val['clientcode'],$val['branchcode']]; 
                  $resval = pg_execute($con,$daycloseval1,$data);
      
                
                if (!empty($resval)) {   
                  array_push($response["CashTransactionDetails"], $val['closedate']);
                }
              }
             }
			 
			 /*$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['closedate'],$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();
}
?>