<?php
session_start();
if(!isset($_SESSION['aid']))
{
	echo '<script>location.href="../index.php"</script>';
}

include "../connection/config.php";

if(isset($_POST['submit']))
{
    $flag=$_POST['flag'];
    $sid=$_POST['sid'];

    $date=date("Y/m/d");
    $item=$_POST['item'];
    $stockin=$_POST['stockin'];
    // $stockout=$_POST['stockout'];
    // $current_stock=$_POST['current_stock'];
    $dead_stock=$_POST['dead_stock'];
    // $stocktot=$_POST['stocktot'];
    // $relvl       =   $_POST['relvl'];
    $relvl       =   5;
    $remark      =   $_POST['remark'];
    //$edititem=$_POST['cat'];

if($flag==0)
{

  $sql="insert into stock_details(iid,date,stockin,dead_stock,reorder,remark)
        values('$item','$date','$stockin','$dead_stock','$relvl','$remark')";
  $exe=mysqli_query($con,$sql); 

  $getsid=mysqli_query($con,"select * from stock_details where iid='$item' ");
  $fsid=mysqli_fetch_assoc($getsid);
  $ssid=$fsid['sid'];



// Check if iid exists in table
$sql_check = "SELECT * FROM stock WHERE iid = '$item'";
$result = $con->query($sql_check);
if ($result->num_rows > 0) {

  // If iid exists, update data
  
  $update_item_sql=mysqli_query($con,"select * from stock where iid='$item'");
  $update_item_fet=mysqli_fetch_assoc($update_item_sql);

   $ugstock=$update_item_fet['good_stock'];
   $udstock=$update_item_fet['dead_stock'];

   $update_goodstock = $ugstock + $stockin;
   $update_deadstock = $udstock + $dead_stock;

  $updatesql="update stock set good_stock='$update_goodstock',dead_stock='$update_deadstock',reorder='$relvl' where iid='$item'";
  mysqli_query($con,$updatesql);

}
 else 
{
  // If iid does not exist, insert data
  $sql2="insert into stock(sid,iid,good_stock,dead_stock,reorder)
        values('$ssid','$item','$stockin','$dead_stock','$relvl')";
  $exe2=mysqli_query($con,$sql2);
}

  echo '<script>location.href="stock_input.php"</script>';
}

if($flag==2)
{
    // update stock details
    $sqli="update stock_details set iid='$item',stockin='$stockin',dead_stock='$dead_stock',reorder='$relvl',remark='$remark' where sid='$sid'";  
    $exee=mysqli_query($con,$sqli);

   // update stock
      $update_item_sql=mysqli_query($con,"select * from stock where iid='$item'");
      $update_item_fet=mysqli_fetch_assoc($update_item_sql);
  
      $ugstock=$update_item_fet['good_stock']; 
      $udstock=$update_item_fet['dead_stock'];
  
      $update_goodstock = $ugstock + $stockin; 
      $update_deadstock = $udstock + $dead_stock;


    $sqli2="update stock set good_stock='$update_goodstock',dead_stock='$update_deadstock',reorder='$relvl' where iid='$item'";  
    $exee2=mysqli_query($con,$sqli);

    echo '<script>location.href="stock_input.php"</script>';
}
}

?>