<?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['stocktransfer'];
// $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, '.', '');

$response1["TransactionDetails"] = array();
$last_id = '';
$tracking_id = '';

// $devicecode = 1279;
// $imeino = '9dff810ab0655aae';
// $paratransactionarray = '{"JSonObject":[{"transferno":20,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"108","itemcode":441,"qty":25,"createddate":"2025-12-12 10:19:00","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":20,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"108","itemcode":442,"qty":69,"createddate":"2025-12-12 10:19:00","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":20,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"108","itemcode":443,"qty":22,"createddate":"2025-12-12 10:19:00","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":20,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"108","itemcode":444,"qty":30,"createddate":"2025-12-12 10:19:00","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":20,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"108","itemcode":446,"qty":14,"createddate":"2025-12-12 10:19:00","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":20,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"108","itemcode":1,"qty":88,"createddate":"2025-12-12 10:19:00","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":20,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"108","itemcode":23,"qty":33,"createddate":"2025-12-12 10:19:00","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":20,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"108","itemcode":24,"qty":14,"createddate":"2025-12-12 10:19:00","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":20,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"108","itemcode":25,"qty":77,"createddate":"2025-12-12 10:19:00","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":21,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"29","itemcode":23,"qty":36,"createddate":"2025-12-12 10:18:20","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":21,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"29","itemcode":24,"qty":9,"createddate":"2025-12-12 10:18:20","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":21,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"29","itemcode":25,"qty":5,"createddate":"2025-12-12 10:18:20","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":21,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"29","itemcode":26,"qty":11,"createddate":"2025-12-12 10:18:20","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":21,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"29","itemcode":1,"qty":2,"createddate":"2025-12-12 10:18:20","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":21,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"29","itemcode":3,"qty":64,"createddate":"2025-12-12 10:18:20","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":21,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"29","itemcode":4,"qty":31,"createddate":"2025-12-12 10:18:20","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":21,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"29","itemcode":6,"qty":97,"createddate":"2025-12-12 10:18:20","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":21,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"29","itemcode":17,"qty":82,"createddate":"2025-12-12 10:18:20","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":21,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"29","itemcode":18,"qty":20,"createddate":"2025-12-12 10:18:20","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":21,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"29","itemcode":13,"qty":54,"createddate":"2025-12-12 10:18:20","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":21,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"29","itemcode":15,"qty":65,"createddate":"2025-12-12 10:18:20","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":21,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"29","itemcode":36,"qty":98,"createddate":"2025-12-12 10:18:20","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":21,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"29","itemcode":37,"qty":12,"createddate":"2025-12-12 10:18:20","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":21,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"29","itemcode":38,"qty":31,"createddate":"2025-12-12 10:18:20","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":22,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"57","itemcode":13,"qty":6,"createddate":"2025-12-12 10:17:15","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":22,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"57","itemcode":15,"qty":8,"createddate":"2025-12-12 10:17:15","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":22,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"57","itemcode":36,"qty":2,"createddate":"2025-12-12 10:17:15","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":22,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"57","itemcode":441,"qty":81,"createddate":"2025-12-12 10:17:15","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":22,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"57","itemcode":442,"qty":33,"createddate":"2025-12-12 10:17:15","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":22,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"57","itemcode":443,"qty":30,"createddate":"2025-12-12 10:17:15","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":22,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"57","itemcode":444,"qty":20,"createddate":"2025-12-12 10:17:15","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":23,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"17","itemcode":444,"qty":11,"createddate":"2025-12-12 10:17:43","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":23,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"17","itemcode":443,"qty":8,"createddate":"2025-12-12 10:17:43","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":23,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"17","itemcode":442,"qty":6,"createddate":"2025-12-12 10:17:43","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":23,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"17","itemcode":441,"qty":2,"createddate":"2025-12-12 10:17:43","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":23,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"17","itemcode":4,"qty":9,"createddate":"2025-12-12 10:17:43","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":23,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"17","itemcode":3,"qty":6,"createddate":"2025-12-12 10:17:43","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":23,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"17","itemcode":6,"qty":2,"createddate":"2025-12-12 10:17:43","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":24,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"30","itemcode":441,"qty":23,"createddate":"2025-12-12 10:18:50","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":25,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"44","itemcode":1,"qty":55,"createddate":"2025-12-12 10:19:16","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":26,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"15","itemcode":23,"qty":66,"createddate":"2025-12-12 10:20:00","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":26,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"15","itemcode":1,"qty":55,"createddate":"2025-12-12 10:20:00","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":28,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"103","itemcode":23,"qty":55,"createddate":"2025-12-12 10:27:03","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":28,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"103","itemcode":24,"qty":99,"createddate":"2025-12-12 10:27:03","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":28,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"103","itemcode":25,"qty":11,"createddate":"2025-12-12 10:27:03","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":28,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"103","itemcode":1,"qty":3,"createddate":"2025-12-12 10:27:03","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":29,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"75","itemcode":1,"qty":75,"createddate":"2025-12-12 10:27:58","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":29,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"75","itemcode":23,"qty":36,"createddate":"2025-12-12 10:27:58","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":29,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"75","itemcode":24,"qty":14,"createddate":"2025-12-12 10:27:58","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0},{"transferno":29,"transferdate":"12-12-2025","sourcecode":"73","destinationcode":"75","itemcode":25,"qty":28,"createddate":"2025-12-12 10:27:58","devicecode":"9dff810ab0655aae","syncflag":"0","cancelflag":0}]}';

$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 Stock Transfer','Insert'];
    $res = pg_execute($con,"query",$data);
    // get maker id
    while ($row = pg_fetch_row($res)) {
      $last_id=$row[0]; 
    }  

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

        $stocktransferDate = str_replace('-', '_', $val['transferdate']);

        $key = $stocktransferDate.'_'.$val['transferno'].'_'.$val['devicecode'].'_'.$val['sourcecode'].'_'.$val['destinationcode'];
        // echo $key."\n";

        if (!isset($distinctStocktransfer[$key])) {
          $distinctStocktransfer[$key] = [
              'transferdate' => $val['transferdate'],
              'transferno'   => $val['transferno'],
              'devicecode' => $val['devicecode'],
              'sourcecode' => $val['sourcecode'],
              'destinationcode' => $val['destinationcode'],
          ];
        }

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


    $j=0;
    foreach ($distinctStocktransfer as $key => $stocktransfer) {
      $j++;

      $rowcntqryval = "rowcntqry" . $j;
      //Get unique count 
      $rowcntqry = "SELECT coalesce(count(*),0) as count from tblstocktransfer 
                    where stocktransferno=$1 and devicecode=$2 and sourcecode=$3 and destinationcode=$4 and date(stocktransferdate) = date($5)";
      $resultmax = pg_prepare($con, $rowcntqryval, $rowcntqry);
      $data = [$stocktransfer['transferno'], $stocktransfer['devicecode'], $stocktransfer['sourcecode'], $stocktransfer['destinationcode'], $stocktransfer['transferdate']];
      $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 tblstocktransfer where stocktransferno=$1 and devicecode=$2 and sourcecode=$3 and destinationcode=$4 and date(stocktransferdate) = date($5)';
        $result1 = pg_prepare($con, $varqueryupdateval, $deletereceipt);
        $data = [$stocktransfer['transferno'], $stocktransfer['devicecode'], $stocktransfer['sourcecode'], $stocktransfer['destinationcode'], $stocktransfer['transferdate']];
        $deleteresult = pg_execute($con, $varqueryupdateval, $data);
        // echo " deleted". "\n";
      }

      $index = 0;
      foreach ($stocktransactiondetails as $val) {
        $index++;
        if ($stocktransfer['transferdate']==$val['transferdate'] && $stocktransfer['transferno']==$val['transferno'] && 
            $stocktransfer['devicecode']==$val['devicecode'] && $stocktransfer['sourcecode']==$val['sourcecode'] && $stocktransfer['destinationcode']==$val['destinationcode']) {
              $stocktransaction = "insertstocktransfer" . $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  tblstocktransfer (stocktransferno, stocktransferdate, sourcecode, destinationcode, itemcode, qty, createddate, syncdate, makerid, devicecode, syncflag, cancelflag, origin, cancelremarks, itemgroupcode, itemtype) 
                                              values ($1,$2,$3,$4,$5,$6,$7,now(),$8,$9,$10,$11,$12,$13,$14,$15) ";
              $result1 = pg_prepare($con, $stocktransaction, $varqueryinsert);
      
              $data = [$val['transferno'], $val['transferdate'], $val['sourcecode'], $val['destinationcode'], $val['itemcode'], $val['qty'], $val['createddate'], $last_id, $val['devicecode'], 1, $val['cancelflag'], 'Mobile', $cancelremarks, $itemgroupcode, $itemtype];
      
              $resval = pg_execute($con, $stocktransaction, $data);
      
              if (!empty($resval)) {
                array_push($response["stocktransactiondetails"], $val['transferno']);
              } 
        }
      }
      
    }
    // $j = 0;
    // foreach ($stocktransactiondetails as $val) {
    //   $j++;
      

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

    //     //Insert stock transaction
    //     $varqueryinsert = "INSERT INTO  tblstocktransfer (stocktransferno, stocktransferdate, sourcecode, destinationcode, itemcode, qty, createddate, syncdate, makerid, devicecode, syncflag, cancelflag, origin) 
    //                                     values ($1,$2,$3,$4,$5,$6,$7,now(),$8,$9,$10,$11,$12) ";
    //     $result1 = pg_prepare($con, $stocktransaction, $varqueryinsert);

    //     $data = [$val['transferno'], $val['transferdate'], $val['sourcecode'], $val['destinationcode'], $val['itemcode'], $val['qty'], $val['createddate'], $last_id, $val['devicecode'], 1, $val['cancelflag'], 'Mobile'];

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

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

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

    //     //Delete stock transaction
    //     $updateinward = "UPDATE tblstocktransfer set qty=$1, cancelflag=$2 
    //                       where stocktransferno=$3 and devicecode=$4 and sourcecode=$5 and destinationcode=$6 and date(stocktransferdate) = date($7) and itemcode =$8";
    //     $result1 = pg_prepare($con, $varqueryupdateval, $updateinward);
    //     $data = [$val['qty'], $val['cancelflag'], $val['transferno'], $val['devicecode'], $val['sourcecode'], $val['destinationcode'], $val['transferdate'],$val['itemcode']];
    //     $deleteresult = pg_execute($con, $varqueryupdateval, $data);

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

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