<?php
// Start or resume the PHP session
session_start();

// Include the database connection file
include_once 'shikanisha.kts.php';

// Get the order ID from the POST request
$trans_id = $_POST['receipt_id'];

// Delete the transaction receipt from the transaction receipts table
$query = "DELETE FROM transaction_receipts WHERE trans_id = $trans_id";
$result = $conn->query($query);

if ($result) {
  // Get the sales items associated with the transaction ID
  $query = "SELECT * FROM sales WHERE trans_id = $trans_id";
  $result = $conn->query($query);

  if ($result->num_rows > 0) {
    // Loop through each sales item
    while ($row = $result->fetch_assoc()) {
      $product_id = $row['product_id'];
      $quantity = $row['quantity'];

      // Update the product quantity in the products table
      $query = "UPDATE beverages SET  = quantity + $quantity WHERE beverages_id = $product_id";
      $result2 = $conn->query($query);

      if (!$result2) {
        // Error occurred, rollback transaction
        $conn->rollback();
        die("Error updating product quantity: " . $conn->error);
      }
    }

    // All updates successful, commit transaction
    $conn->commit();
    echo "Sale deleted successfully!";
  } else {
    // No sales found for the transaction, rollback transaction
    $conn->rollback();
    die("Error: No sales found for transaction!");
  }
} else {
  // Error occurred, rollback transaction
  $conn->rollback();
  die("Error deleting transaction receipt: " . $conn->error);
}

// Close the database connection
mysqli_close($conn);
?>
