<?php
session_start();
include_once 'shikanisha.kts.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  
  if (isset($_POST['tostore'])) {
    
    $query2 = "insert into tostore (product_id, quantity, sdate) values (?, ?, ?)";
    $stmt = mysqli_prepare($conn, $query2);
    
    if ($stmt) {
      
      mysqli_stmt_bind_param($stmt, "iis", $id, $quantity, $date);
     
      foreach ($_SESSION['shop'] as $key => $value) {
        
        $quantity = $value['qty'];
        $id = $value['id'];
        $date=date('Y-m-d');
        mysqli_stmt_execute($stmt);
        
      }

      $query3 = "update products set store_quantity = store_quantity + ? where product_id = ?";
      $stmt3 = mysqli_prepare($conn, $query3);
      
      if ($stmt3) {
        
        foreach ($_SESSION['shop'] as $key => $value) {
          
          $quantity = $value['qty'];
          $id = $value['id'];
          mysqli_stmt_bind_param($stmt3, "ii", $quantity, $id);
          mysqli_stmt_execute($stmt3);
          
          // Check for errors
          if (mysqli_stmt_error($stmt3)) {
            echo "Error: " . mysqli_stmt_error($stmt3);
          }
          
        }
        
        $query4 = "update products set shop_quantity = shop_quantity - ? where product_id = ?";
        $stmt4 = mysqli_prepare($conn, $query4);
        
        if ($stmt4) {
          
          foreach ($_SESSION['shop'] as $key => $value) {
            
            $quantity = $value['qty'];
            $id = $value['id'];
            mysqli_stmt_bind_param($stmt4, "ii", $quantity, $id);
            mysqli_stmt_execute($stmt4);
            
            // Check for errors
            if (mysqli_stmt_error($stmt4)) {
              echo "Error: " . mysqli_stmt_error($stmt4);
            }
            
          }
          unset ($_SESSION['shop']);
          echo "<script>alert('Items sent to store successfully'); window.location.href='../shop.php';</script>";
    
        } else {
          echo "Error: " . mysqli_error($conn);
        }
        
      } else {
        echo "Error: " . mysqli_error($conn);
      }     
      
    } else {
      echo "Error: " . mysqli_error($conn);
    }
    
  }
  
}

?>
