<?php 
// array for JSON response
$response = array();
 
require_once __DIR__ . '/catchexception.php'; 
// include db connect class
require_once __DIR__ . '/db_config.php';
  
  $paraimeino = urldecode($_POST['paraimeino']);  
  $billdate = urldecode($_POST['parabilldate']);
  //   $paraimeino ='aa306fe80a7dceac';
  // $billdate='1782066600000';
try{
if ($paraimeino !=""   ) { 
  $paravancodeqry="SELECT branch_devicemapcode  from tblbranchdevicemapping as a where  deviceid=$1";
  $resultmax=  pg_prepare($con,"vancodequery",$paravancodeqry);
  $data = [$paraimeino];
  $res = pg_execute($con,"vancodequery",$data);
  if (!empty($res)) {
      if (pg_num_rows($res) > 0) {   
        while ($row = pg_fetch_assoc($res)) {
            $paradevicecode= $row["branch_devicemapcode"] ;
          }
      }
  }

  $parabranchcode=0;
  $parabranchcodeqry="SELECT branchcode from tblbranchdevicemapping as a where  deviceid=$1";
  $resultmax=  pg_prepare($con,"branchcodequery",$parabranchcodeqry);
  $data = [$paraimeino];
  $res = pg_execute($con,"branchcodequery",$data);
  if (!empty($res)) {
      if (pg_num_rows($res) > 0) {   
        while ($row = pg_fetch_assoc($res)) {
            $parabranchcode= $row["branchcode"] ;
          }
      }
  }

  $sales_sessionid=-1;
  $sessionidsql="SELECT cast(coalesce(max(sessionid),'0') as integer) as sessionid from tblsales where deviceid=$1 and transactiondate=$2;";
  $resultmax=  pg_prepare($con,"sessionidsql",$sessionidsql);
  $data = [$paraimeino,$billdate];
  $res = pg_execute($con,"sessionidsql",$data);
  if (!empty($res)) {
    if (pg_num_rows($res) > 0) {   
      while ($row = pg_fetch_assoc($res)) {
          $sales_sessionid= $row["sessionid"] ;
        }
    }
  }

  $getCount=-1;
  $getCountsql="SELECT count(*) as count from tblsessionclose
    where devicecode=$1 and sessionclosedate=$2 and cast(sessionid as integer)=$3;";
  $resultmax=  pg_prepare($con,"getCountsql",$getCountsql);
  $data = [$paraimeino,$billdate,$sales_sessionid];
  $res = pg_execute($con,"getCountsql",$data);
  if (!empty($res)) {
    if (pg_num_rows($res) > 0) {   
      while ($row = pg_fetch_assoc($res)) {
          $getCount= $row["count"] ;
        }
    }
  }

  $getDayCount=-1;
  $getDayCountsql="SELECT count(*) from tbldayclose where devicecode=$1 and 
        closedate=$2 and branchcode=$3;";
  $resultmax=  pg_prepare($con,"getDayCountsql",$getDayCountsql);
  $data = [$paraimeino,$billdate,$parabranchcode];
  $res = pg_execute($con,"getDayCountsql",$data);
  if (!empty($res)) {
    if (pg_num_rows($res) > 0) {   
      while ($row = pg_fetch_assoc($res)) {
          $getDayCount= $row["count"] ;
        }
    }
  }

  if($sales_sessionid == 0){
    $sales_sessionid = $sales_sessionid+1;
  }
  $valsessionid=-1;
  if($getCount==0){
    $valsessionid = $sales_sessionid;
  }
  if($getCount > 0){
    $valsessionid = $sales_sessionid+1; 
  }
  if($getDayCount == 1){
    $valsessionid = 1;
  }

 $previousdaysales_sessionid=-1;
  $previousdaysales_sessionidsql="SELECT cast(coalesce(max(sessionid),'0') as integer) as sessionid from tblsales where deviceid=$1 and branchcode=$2;";
  $resultmax=  pg_prepare($con,"previousdaysales_sessionidsql",$previousdaysales_sessionidsql);
  $data = [$paraimeino,$parabranchcode];
  $res = pg_execute($con,"previousdaysales_sessionidsql",$data);
  if (!empty($res)) {
    if (pg_num_rows($res) > 0) {   
      while ($row = pg_fetch_assoc($res)) {
          $previousdaysales_sessionid= $row["sessionid"] ;
        }
    }
  }

 
  $sql="SELECT '1' as code,'sales' as process , COALESCE(MAX(transactionno),0)+1 as transactionno, COALESCE(MAX(COALESCE(sequenceno, voucherno::integer)),0) as voucherno, coalesce((select transactiondate from tblsales where deviceid=$1 and transactiondate=$2 order by createddate desc limit 1),0) as closedate,0 as salescount from tblsales where deviceid=$1 and transactiondate=$2 
  union all

  SELECT '333' as code,'dayclose' as process , 0 as transactionno,
  coalesce((select branchcode from tbldayclose where devicecode=$1 order by createddate desc limit 1),0) as voucherno,
  coalesce((select closedate from tbldayclose where devicecode=$1 order by createddate desc limit 1),0) as closedate,0 as salescount

  union all 
  -- This is section is mandatory for stock inward
  SELECT '21225' as code, 'stock_inward' as process, 0 as transactionno, COALESCE(MAX(inwardno),0)+1 as voucherno, 0 as closedate,0 as salescount from tblstockinward where devicecode=$1 --and date(inwarddate) = to_timestamp($2 / 1000)::date
  
  union all 
  -- This is section is mandatory for wastage
  SELECT '31225' as code, 'wastage' as process, 0 as transactionno, COALESCE(MAX(transactionno),0)+1 as voucherno, 0 as closedate,0 as salescount from tblwastage where devicecode=$1 --and date(transactiondate) = to_timestamp($2 / 1000)::date;

  union all 
  -- This is section is mandatory for stock transfer
  SELECT '111225' as code, 'stock_transfer' as process, 0 as transactionno, COALESCE(MAX(stocktransferno),0)+1 as voucherno, 0 as closedate,0 as salescount from tblstocktransfer where devicecode=$1
  ";

    $resultmax=  pg_prepare($con,"sql",$sql);
    $data = [$paraimeino,$billdate];
    $res = pg_execute($con,"sql",$data);
  

  //$resultmax=  pg_prepare($con,"sql",$sql);
  //$data = [$paraimeino,$billdate];
  //$res = pg_execute($con,"sql",$data);
   // $result = mysqli_query($con,$sql);      
    
    if (!empty($res)) {
        // check for empty result
        if (pg_num_rows($res) > 0) {

      // user node
            $response["Value"] = array(); 
 
            while ($row = pg_fetch_assoc($res)) { 
                  
              $report = array();


            $report["code"] = $row["code"];
            $report["process"] = $row["process"];
            $report["transactionno"] = $row["transactionno"];
            $report["voucherno"] = $row["voucherno"];    
            $report["closedate"] = $row["closedate"];   
            $report["salescount"] = $row["salescount"];
            
              // push single product into final response array
              array_push($response["Value"], $report);
            }
            if($valsessionid >=0){
              $report["code"] = 222;
            $report["process"] = 'current_session';
            $report["transactionno"] = 0; // session close count 1 means closed 0 means not closed
            $report["voucherno"] = $valsessionid; // last session id
            $report["closedate"] = 0;
            $report["salescount"] = 0; 
            // push single product into final response array
              array_push($response["Value"], $report);
            }
            // success
            $response["success"] = 1;
 
            // echoing JSON response
            echo  json_encode($response,JSON_UNESCAPED_UNICODE);


        } else {
            // no user found
            $response["success"] = 0;
            $response["message"] = "No Report found";
 
            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no user found
        $response["success"] = 0;
        $response["message"] = "No found";
 
        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
     echo  json_encode($response,JSON_UNESCAPED_UNICODE);
  }
    mch_db_release($con);
  }
  //catch exception
  catch(Exception $e) {
  mch_db_release($con);
  echo 'Message: ' .$e->getMessage();
  }
?>
