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

    //  $devicecode = "403";
    //  $imeino ="5cdf0a149eb3a641";

    //  $paratransactionarray='{"JSonObject":[{"transfercode":1,"transferdate":"08-08-2022","itemcode":1,"transfertype":"Inward","inqty":10,"outqty":0,"remark":"","createddate":"2022-08-08 18:36:15","suppliername":"Aruna","branchcode":25,"devicecode":"9c9aed003ae48de8","syncflag":0,"cancelflag":0},
    //  {"transfercode":1,"transferdate":"08-08-2022","itemcode":2,"transfertype":"Inward","inqty":20,"outqty":0,"remark":"","createddate":"2022-08-08 18:36:15","suppliername":"Aruna","branchcode":25,"devicecode":"9c9aed003ae48de8","syncflag":0,"cancelflag":0},
    //  {"transfercode":1,"transferdate":"08-08-2022","itemcode":23,"transfertype":"Inward","inqty":30,"outqty":0,"remark":"","createddate":"2022-08-08 18:36:15","suppliername":"Aruna","branchcode":25,"devicecode":"9c9aed003ae48de8","syncflag":0,"cancelflag":0},
    //  {"transfercode":1,"transferdate":"08-08-2022","itemcode":24,"transfertype":"Inward","inqty":40,"outqty":0,"remark":"","createddate":"2022-08-08 18:36:15","suppliername":"Aruna","branchcode":25,"devicecode":"9c9aed003ae48de8","syncflag":0,"cancelflag":0},
    //  {"transfercode":1,"transferdate":"08-08-2022","itemcode":4,"transfertype":"Inward","inqty":20,"outqty":0,"remark":"","createddate":"2022-08-08 18:36:15","suppliername":"Aruna","branchcode":25,"devicecode":"9c9aed003ae48de8","syncflag":0,"cancelflag":0}]}';

    //  $paratrackingarray='{"JSonObject":[{"transfercode":1,"transferdate":"30-07-2022","itemcode":39,"transfertype":"Inward","inqty":10,"outqty":0,"remark":"Stock","createddate":"2022-07-30 14:48:17","process":"Insert","branchcode":"6","syncflag":"0","devicecode":5,"suppliername":"Prabha"},{"transfercode":1,"transferdate":"30-07-2022","itemcode":40,"transfertype":"Inward","inqty":20,"outqty":0,"remark":"Stock","createddate":"2022-07-30 14:48:17","process":"Insert","branchcode":"6","syncflag":"0","devicecode":5,"suppliername":"Prabha"},{"transfercode":1,"transferdate":"30-07-2022","itemcode":57,"transfertype":"Inward","inqty":10,"outqty":0,"remark":"Stock","createddate":"2022-07-30 14:48:17","process":"Insert","branchcode":"6","syncflag":"0","devicecode":5,"suppliername":"Prabha"},{"transfercode":1,"transferdate":"30-07-2022","itemcode":39,"transfertype":"Inward","inqty":10,"outqty":0,"remark":"Stock","createddate":"2022-07-30 14:48:17","process":"Delete","branchcode":"6","syncflag":"0","devicecode":5,"suppliername":"Prabha"},{"transfercode":1,"transferdate":"30-07-2022","itemcode":40,"transfertype":"Inward","inqty":20,"outqty":0,"remark":"Stock","createddate":"2022-07-30 14:48:17","process":"Delete","branchcode":"6","syncflag":"0","devicecode":5,"suppliername":"Prabha"},{"transfercode":1,"transferdate":"30-07-2022","itemcode":57,"transfertype":"Inward","inqty":10,"outqty":0,"remark":"Stock","createddate":"2022-07-30 14:48:17","process":"Delete","branchcode":"6","syncflag":"0","devicecode":5,"suppliername":"Prabha"},{"transfercode":1,"transferdate":"30-07-2022","itemcode":57,"transfertype":"Inward","inqty":5,"outqty":0,"remark":"Stock","createddate":"2022-07-30 14:48:45","process":"Insert","branchcode":"6","syncflag":"0","devicecode":5,"suppliername":"Eswari"},{"transfercode":1,"transferdate":"30-07-2022","itemcode":58,"transfertype":"Inward","inqty":7,"outqty":0,"remark":"Stock","createddate":"2022-07-30 14:48:45","process":"Insert","branchcode":"6","syncflag":"0","devicecode":5,"suppliername":"Eswari"}]}';


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


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

     $getcount='';
  
   try{
     if(count($stocktransactiondetails) > 0){
      $response["stocktransactiondetails"] = array();
  
 
        $sql="INSERT into tblsyncdetails (imeino,syncdate,synctype,devicecode) values 
     ($1,now(),'Stock Transaction',$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 Stock Transaction','Insert'];
         $res = pg_execute($con,"query",$data);
           // get masker id
         while ($row = pg_fetch_row($res)) {
           $last_id=$row[0]; 
         }  
          $j=0; 
         foreach ($stocktransactiondetails as $val) {
               $j++;
                $rowcntqryval="rowcntqry".$j;  
                //Get unique count 
                 $rowcntqry="SELECT coalesce(count(*),0) as count from tblstocktransaction where   transfercode=$1 and devicecode=$2 and branchcode=$3 and transferdate = $4 and itemcode =$5";
                 $resultmax =  pg_prepare($con,$rowcntqryval,$rowcntqry);
                 $data = [$val['transfercode'],$val['devicecode'],$val['branchcode'],$val['transferdate'],$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 = "insertstocktransaction".$j;
 
                 //Insert stock transaction
                 $varqueryinsertdenomination = "INSERT INTO  tblstocktransaction (transfercode, transferdate, branchcode, itemcode, transfertype,inqty,outqty,remark,suppliername,createddate, syncdate, makerid,devicecode,syncflag,cancelflag) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,now(),$11,$12,$13,$14) ";
                 $result1 = pg_prepare($con,$stocktransaction,$varqueryinsertdenomination);
 
                 $data = [$val['transfercode'],$val['transferdate'],$val['branchcode'],$val['itemcode'],$val['transfertype'],$val['inqty'],$val['outqty'],$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['transfercode']);
                  }
              }else{
                 $varquerydeleteval1="varquerydelete1".$j;
 
                 //Delete stock transaction
                 $deletereceipt = 'DELETE from tblstocktransaction where transfercode=$1 and devicecode=$2 and branchcode=$3 and transferdate=$4';
                 $result1 = pg_prepare($con,$varquerydeleteval1,$deletereceipt);
                 $data = [$val['transfercode'],$val['devicecode'],$val['branchcode'],$val['transferdate']];
                 $deleteresult = pg_execute($con,$varquerydeleteval1,$data);
 
                
                if (!empty($deleteresult)) {  
                
                  $stocktransaction1 = "insertstocktransaction1".$j;
                    $varqueryinsertdenomination =  "INSERT INTO  tblstocktransaction (transfercode, transferdate, branchcode, itemcode, transfertype,inqty,outqty,remark,suppliername,createddate, syncdate, makerid,devicecode,syncflag,cancelflag) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,now(),$11,$12,$13,$14) ";
                   $result1 = pg_prepare($con,$stocktransaction1,$varqueryinsertdenomination);
 
                   $data = [$val['transfercode'],$val['transferdate'],$val['branchcode'],$val['itemcode'],$val['transfertype'],$val['inqty'],$val['outqty'],$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['transfercode']);
                 }
               }
              }
      }   
 }

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

    $sql="INSERT into tblsyncdetails (imeino,syncdate,synctype,devicecode) values 
 ($1,now(),'Stock Tracking',$2 )";  
 $resultmax=  pg_prepare($con,"con",$sql);
$data = [$imeino,$devicecode ];
$result = pg_execute($con,"con",$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,"query1",$query);
     $data = [$devicecode,'Insert Stock Tracking','Insert'];
     $res = pg_execute($con,"query1",$data);

       // get masker id
     while ($row = pg_fetch_row($res)) {
       $tracking_id=$row[0]; 
     }  
      $j=0; 

     foreach ($stocktrackingdetails as $val) {
           $j++;
            $rowcntqryval="rowcntqry2".$j;  
            //Get unique count 
             $rowcntqry="SELECT coalesce(count(*),0) as count from tblstocktracking where   transfercode=$1 and devicecode=$2 and branchcode=$3 and transferdate=$4 and itemcode=$5 and process=$6 and createddate=$7";
             $resultmax =  pg_prepare($con,$rowcntqryval,$rowcntqry);
           
             $data = [$val['transfercode'],$val['devicecode'],$val['branchcode'],$val['transferdate'],$val['itemcode'],$val['process'],$val['createddate']];
             $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){
              $stocktracking = "insertstocktracking".$j;
             //Insert stock transaction
             $varqueryinsertdenomination = "INSERT INTO  tblstocktracking (transfercode, transferdate, branchcode, itemcode, transfertype,newqty,oldqty,remark,suppliername,createddate, syncdate, makerid,devicecode,syncflag,process) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,now(),$11,$12,$13,$14) ";
             $result1 = pg_prepare($con,$stocktracking,$varqueryinsertdenomination);

             $data = [$val['transfercode'],$val['transferdate'],$val['branchcode'],$val['itemcode'],$val['transfertype'],$val['newqty'],$val['oldqty'],$val['remark'],$val['suppliername'],$val['createddate'],$tracking_id,$val['devicecode'],1,$val['process']]; 

             $resval = pg_execute($con,$stocktracking,$data);

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

       //     $varquerydeleteval1="varquerydelete1".$j;

       //     //Delete stock transaction
       //     $deletereceipt = 'DELETE from tblstocktracking where transfercode=$1 and devicecode=$2 and branchcode=$3 and transferdate=$4 ';
       //     $result1 = pg_prepare($con,$varquerydeleteval1,$deletereceipt);
       //     $data = [$val['transfercode'],$val['devicecode'],$val['branchcode'],$val['transferdate']];
       //     $deleteresult = pg_execute($con,$varquerydeleteval1,$data);

          
       //    if (!empty($deleteresult)) {  
          
       //      $stocktracking1 = "insertstocktracking1".$j;
       //        $varqueryinsertdenomination =  "INSERT INTO  tblstocktracking (transfercode, transferdate, branchcode, itemcode, transfertype,inqty,outqty,remark,suppliername,createddate, syncdate, makerid,devicecode,syncflag,process) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15) ";
       //       $result1 = pg_prepare($con,$stocktracking1,$varqueryinsertdenomination);

       //       $data = [$val['transfercode'],$val['transferdate'],$val['branchcode'],$val['itemcode'],$val['transfertype'],$val['inqty'],$val['outqty'],$val['remark'],$val['suppliername'],$val['createddate'],$getdatetime ,$tracking_id,$val['devicecode'],$val['syncflag'],$val['process']]; 

       //       $resval = pg_execute($con,$stocktracking1,$data);
 
           
       //     if (!empty($resval)) {   
       //       array_push($response["stocktrackingdetails"], $val['transfercode']);
       //     }
       //   }
       //  }
  }
      
}


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