<?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'];

// $devicecode = 1279;
// $imeino = '9dff810ab0655aae';
// $paratransactionarray = '{"JSonObject":[{"inwardno":44,"inwarddate":"26-12-2025","itemcode":26,"qty":25,"price":365,"remark":"","createddate":"2025-12-26 19:07:52","suppliername":"g","branchcode":"73","devicecode":"9dff810ab0655aae","syncflag":0,"cancelflag":0,"itemgroupcode":"1","itemtype":"Menu Item"},{"inwardno":44,"inwarddate":"26-12-2025","itemcode":25,"qty":7,"price":360,"remark":"","createddate":"2025-12-26 19:07:52","suppliername":"g","branchcode":"73","devicecode":"9dff810ab0655aae","syncflag":0,"cancelflag":0,"itemgroupcode":"1","itemtype":"Menu Item"},{"inwardno":44,"inwarddate":"26-12-2025","itemcode":24,"qty":4,"price":25,"remark":"","createddate":"2025-12-26 19:07:52","suppliername":"g","branchcode":"73","devicecode":"9dff810ab0655aae","syncflag":0,"cancelflag":0,"itemgroupcode":"1","itemtype":"Menu Item"},{"inwardno":44,"inwarddate":"26-12-2025","itemcode":23,"qty":3,"price":30,"remark":"","createddate":"2025-12-26 19:07:52","suppliername":"g","branchcode":"73","devicecode":"9dff810ab0655aae","syncflag":0,"cancelflag":0,"itemgroupcode":"1","itemtype":"Menu Item"},{"inwardno":44,"inwarddate":"26-12-2025","itemcode":1,"qty":5,"price":60,"remark":"","createddate":"2025-12-26 19:07:52","suppliername":"g","branchcode":"73","devicecode":"9dff810ab0655aae","syncflag":0,"cancelflag":0,"itemgroupcode":"1","itemtype":"Menu Item"},{"inwardno":45,"inwarddate":"26-12-2025","itemcode":34,"qty":69,"price":650,"remark":"","createddate":"2025-12-26 19:09:56","suppliername":"qw","branchcode":"73","devicecode":"9dff810ab0655aae","syncflag":0,"cancelflag":0,"itemgroupcode":"4","itemtype":"Menu Item"},{"inwardno":45,"inwarddate":"26-12-2025","itemcode":32,"qty":64,"price":69,"remark":"","createddate":"2025-12-26 19:09:56","suppliername":"qw","branchcode":"73","devicecode":"9dff810ab0655aae","syncflag":0,"cancelflag":0,"itemgroupcode":"4","itemtype":"Menu Item"},{"inwardno":45,"inwarddate":"26-12-2025","itemcode":31,"qty":31,"price":324,"remark":"","createddate":"2025-12-26 19:09:56","suppliername":"qw","branchcode":"73","devicecode":"9dff810ab0655aae","syncflag":0,"cancelflag":0,"itemgroupcode":"4","itemtype":"Menu Item"},{"inwardno":45,"inwarddate":"26-12-2025","itemcode":8,"qty":69,"price":55,"remark":"","createddate":"2025-12-26 19:09:56","suppliername":"qw","branchcode":"73","devicecode":"9dff810ab0655aae","syncflag":0,"cancelflag":0,"itemgroupcode":"4","itemtype":"Menu Item"}]}';

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

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

        $inwardDate = str_replace('-', '_', $val['inwarddate']);

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

        if (!isset($distinctInwards[$key])) {
          $distinctInwards[$key] = [
              'inwarddate' => $val['inwarddate'],
              'inwardno'   => $val['inwardno'],
              'devicecode' => $val['devicecode'],
              'branchcode' => $val['branchcode'],
          ];
        }

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


    $j=0;
    foreach ($distinctInwards as $key => $inward) {
      $j++;
      $rowcntqryval = "rowcntqry" . $j;
      
      //Get unique count 
      $rowcntqry = "SELECT coalesce(count(*),0) as count from tblstockinward 
                    where inwardno=$1 and devicecode=$2 and branchcode=$3 and date(inwarddate) = date($4)";
      $resultmax = pg_prepare($con, $rowcntqryval, $rowcntqry);
      $data = [$inward['inwardno'], $inward['devicecode'], $inward['branchcode'], $inward['inwarddate']];
      $res = pg_execute($con, $rowcntqryval, $data);

      if (!empty($res)) {
        if (pg_num_rows($res) > 0) {
          while ($row = pg_fetch_assoc($res)) {
            $getcount = $row["count"];
          }
        }
      }

      // echo "inward count : ".$getcount. "\n";

      if ($getcount > 0) {
        $varqueryupdateval = "varquerydelete1" . $j;
        $deletereceipt = 'DELETE from tblstockinward where inwardno=$1 and devicecode=$2 and branchcode=$3 and inwarddate=$4';
        $result1 = pg_prepare($con, $varqueryupdateval, $deletereceipt);
        $data = [$inward['inwardno'], $inward['devicecode'], $inward['branchcode'], $inward['inwarddate']];
        $deleteresult = pg_execute($con, $varqueryupdateval, $data);
        // echo " deleted". "\n";
      }

      $index = 0;
      foreach ($stocktransactiondetails as $val) {
        $index++;
        if ($inward['inwarddate']==$val['inwarddate'] && $inward['inwardno']==$val['inwardno'] && 
            $inward['devicecode']==$val['devicecode'] && $inward['branchcode']==$val['branchcode']) {
              
              $stocktransaction = "insertstockinward" . $index;

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

        
      }
      

    }


    // $j = 0;
    // foreach ($stocktransactiondetails as $val) {
    //   $j++;
    //   $rowcntqryval = "rowcntqry" . $j;
    //   //Get unique count 
    //   $rowcntqry = "SELECT coalesce(count(*),0) as count from tblstockinward 
    //                 where inwardno=$1 and devicecode=$2 and branchcode=$3 and date(inwarddate) = date($4) and itemcode =$5";
    //   $resultmax = pg_prepare($con, $rowcntqryval, $rowcntqry);
    //   $data = [$val['inwardno'], $val['devicecode'], $val['branchcode'], $val['inwarddate'], $val['itemcode']];
    //   $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) {
    //   //   $stocktransaction = "insertstockinward" . $j;

    //   //   $itemgroupcode = 0;
    //   //   if(array_key_exists("itemgroupcode",$val)) {
    //   //     if($val['itemgroupcode'] != null && $val['itemgroupcode'] != 0 ){
    //   //       $itemgroupcode = $val['itemgroupcode'];
    //   //     }
    //   //   }
    //   //   //Insert stock transaction
    //   //   $varqueryinsert = "INSERT INTO  tblstockinward (inwardno, inwarddate, branchcode, itemcode, qty, price, remark, suppliername, createddate, syncdate, makerid, devicecode, syncflag, cancelflag, itemgroupcode, itemtype) 
    //   //                                   values ($1,$2,$3,$4,$5,$6,$7,$8,$9,now(),$10,$11,$12,$13,$14,$15) ";
    //   //   $result1 = pg_prepare($con, $stocktransaction, $varqueryinsert);

    //   //   $data = [$val['inwardno'], $val['inwarddate'], $val['branchcode'], $val['itemcode'], $val['qty'], $val['price'], $val['remark'], $val['suppliername'], $val['createddate'], $last_id, $val['devicecode'], 1, $val['cancelflag'], $itemgroupcode, $val['itemtype']];

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

    //   //   if (!empty($resval)) {
    //   //     array_push($response["stocktransactiondetails"], $val['inwardno']);
    //   //   }
    //   // } else {
    //   //   // $varqueryupdateval = "varquerydelete1" . $j;

    //   //   // //Delete stock transaction
    //   //   // $deletereceipt = 'DELETE from tblstockinward where inwardno=$1 and devicecode=$2 and branchcode=$3 and inwarddate=$4';
    //   //   // $result1 = pg_prepare($con, $varqueryupdateval, $deletereceipt);
    //   //   // $data = [$val['inwardno'], $val['devicecode'], $val['branchcode'], $val['inwarddate']];
    //   //   // $deleteresult = pg_execute($con, $varqueryupdateval, $data);


    //   //   // if (!empty($deleteresult)) {

    //   //   //   $stocktransaction1 = "insertstockinward" . $j;
    //   //   //   $varqueryinsert = "INSERT INTO  tblstockinward (inwardno, inwarddate, branchcode, itemcode, qty, price, remark, suppliername, createddate, syncdate, makerid, devicecode, syncflag, cancelflag) 
    //   //   //                                 values ($1,$2,$3,$4,$5,$6,$7,$8,$9,now(),$10,$11,$12,$13) ";
    //   //   //   $result1 = pg_prepare($con, $stocktransaction1, $varqueryinsert);

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

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


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

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

    //   //   //Delete stock transaction
    //   //   $updateinward = "UPDATE tblstockinward set qty=$1, price=$2, remark=$3, suppliername=$4, cancelflag=$5, itemgroupcode=$6, itemtype=$7, createddate=$8
    //   //                     where inwardno=$9 and devicecode=$10 and branchcode=$11 and date(inwarddate)=date($12) and itemcode=$13";    
    //   //   $result1 = pg_prepare($con, $varqueryupdateval, $updateinward);
    //   //   $data = [$val['qty'], $val['price'], $val['remark'], $val['suppliername'], $val['cancelflag'], $val['itemgroupcode'], $val['itemtype'], $val['createddate'],
    //   //             $val['inwardno'], $val['devicecode'], $val['branchcode'], $val['inwarddate'], $val['itemcode']];
    //   //   $deleteresult = pg_execute($con, $varqueryupdateval, $data);

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

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