<?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']);
$paratransactionarray = $_POST['stocktransaction'];
// $paratrackingarray=$_POST['stocktracking'];

date_default_timezone_set('Asia/Kolkata');
$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 = '';
$tracking_id = '';

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

$getcount = '';

try {
  if (count($stocktransactiondetails) > 0) {
    $response["stocktransactiondetails"] = array();

    $query = 'INSERT into tbluserlog(userid, originator, createdtime, "Action") values ($1,$2,now(),$3) RETURNING autonum';
    $result1 = pg_prepare($con,"query",$query);
    $data = [$devicecode,'Insert Wastage Transaction','Insert'];
    $res = pg_execute($con,"query",$data);
    // get maker id
    while ($row = pg_fetch_row($res)) {
      $last_id=$row[0]; 
    }  

    $distinctWastage = [];
    foreach ($stocktransactiondetails as $val) {

        $transactionDate = str_replace('-', '_', $val['transactiondate']);

        $key = $transactionDate.'_'.$val['transactionno'].'_'.$val['devicecode'].'_'.$val['branchcode'];
        // echo $key."\n";

        if (!isset($distinctWastage[$key])) {
          $distinctWastage[$key] = [
              'transactiondate' => $val['transactiondate'],
              'transactionno'   => $val['transactionno'],
              'devicecode' => $val['devicecode'],
              'branchcode' => $val['branchcode'],
          ];
        }

      // Re-index if needed
      // $distinctWastage = array_values($distinctWastage);
    }


    $j = 0;
    foreach ($distinctWastage as $key => $wastage) {
      $j++;
      $rowcntqryval = "rowcntqry" . $j;
      //Get unique count 
      $rowcntqry = "SELECT coalesce(count(*),0) as count from tblwastage 
                    where transactionno=$1 and devicecode=$2 and branchcode=$3 and date(transactiondate) = date($4)";
      $resultmax = pg_prepare($con, $rowcntqryval, $rowcntqry);
      $data = [$wastage['transactionno'], $wastage['devicecode'], $wastage['branchcode'], $wastage['transactiondate']];
      $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) {
        $varqueryupdateval = "varquerydelete1" . $j;
        $deletereceipt = 'DELETE from tblwastage where transactionno=$1 and devicecode=$2 and branchcode=$3 and date(transactiondate) = date($4)';
        $result1 = pg_prepare($con, $varqueryupdateval, $deletereceipt);
        $data = [$wastage['transactionno'], $wastage['devicecode'], $wastage['branchcode'], $wastage['transactiondate']];
        $deleteresult = pg_execute($con, $varqueryupdateval, $data);
        // echo " deleted". "\n";
      }
      $index = 0;
      foreach ($stocktransactiondetails as $val) {
        $index++;
        if ($wastage['transactiondate']==$val['transactiondate'] && $wastage['transactionno']==$val['transactionno'] && 
            $wastage['devicecode']==$val['devicecode'] && $wastage['branchcode']==$val['branchcode']) {
              $stocktransaction = "insertwastage" . $index;

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

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

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

              //Insert stock transaction
              $varqueryinsert = "INSERT INTO  tblwastage (transactionno, transactiondate, branchcode, itemcode, qty, remark, suppliername, createddate, syncdate, makerid, devicecode, syncflag, cancelflag, cancelremarks, itemgroupcode, itemtype) 
                                              values ($1,$2,$3,$4,$5,$6,$7,$8,now(),$9,$10,$11,$12,$13,$14,$15) ";
              $result1 = pg_prepare($con, $stocktransaction, $varqueryinsert);
      
              $data = [$val['transactionno'], $val['transactiondate'], $val['branchcode'], $val['itemcode'], $val['qty'], $val['remark'], $val['suppliername'], $val['createddate'], $last_id, $val['devicecode'], 1, $val['cancelflag'], $cancelremarks, $itemgroupcode, $itemtype ];
      
              $resval = pg_execute($con, $stocktransaction, $data);
      
              if (!empty($resval)) {
                array_push($response["stocktransactiondetails"], $val['transactionno']);
              }
        }
      }

      // if ($getcount == 0) {
      //   $stocktransaction = "insertwastage" . $j;

      //   //Insert stock transaction
      //   $varqueryinsert = "INSERT INTO  tblwastage (transactionno, transactiondate, branchcode, itemcode, qty, remark, suppliername, createddate, syncdate, makerid, devicecode, syncflag, cancelflag) 
      //                                   values ($1,$2,$3,$4,$5,$6,$7,$8,now(),$9,$10,$11,$12) ";
      //   $result1 = pg_prepare($con, $stocktransaction, $varqueryinsert);

      //   $data = [$val['transactionno'], $val['transactiondate'], $val['branchcode'], $val['itemcode'], $val['qty'], $val['remark'], $val['suppliername'], $val['createddate'], $last_id, $val['devicecode'], 1, $val['cancelflag']];

      //   $resval = pg_execute($con, $stocktransaction, $data);

      //   if (!empty($resval)) {
      //     array_push($response["stocktransactiondetails"], $val['transactionno']);
      //   }
      // } else {  

      //   $varqueryupdateval = "varqueryupdate" . $j;

      //   //Delete stock transaction
      //   $updateinward = "UPDATE tblwastage set qty=$1, remark=$2, suppliername=$3, cancelflag=$4 
      //                     where transactionno=$5 and devicecode=$6 and branchcode=$7 and date(transactiondate)=date($8) and itemcode=$9";    
      //   $result1 = pg_prepare($con, $varqueryupdateval, $updateinward);
      //   $data = [$val['qty'], $val['remark'], $val['suppliername'], $val['cancelflag'],
      //             $val['transactionno'], $val['devicecode'], $val['branchcode'], $val['transactiondate'], $val['itemcode']];
      //   $deleteresult = pg_execute($con, $varqueryupdateval, $data);

      //   if (!empty($deleteresult)) {
      //     array_push($response["stocktransactiondetails"], $val['transactionno']);
      //   }
      // }
    }
  }

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