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

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

// Check if the sale_id is provided
if (!isset($_POST['sale_id'])) {
    die("Error: sale_id is required.");
}

// Get the order ID from the POST request
$saleId = $conn->real_escape_string($_POST['sale_id']);

// Begin a transaction
$conn->begin_transaction();

try {
    // Fetch sale data
    $stmt = $conn->prepare("SELECT product_id, quantity, category, trans_id, subtotal FROM sales WHERE sale_id = ?");
    $stmt->bind_param("i", $saleId);
    $stmt->execute();
    $result = $stmt->get_result();
    $saleData = $result->fetch_assoc();
    $stmt->close();

    if (!$saleData) {
        throw new Exception("No sales found for the provided sale_id.");
    }

    $product_id = $saleData['product_id'];
    $category = $saleData['category'];
    $trans_id = $saleData['trans_id'];
    $quantity = $saleData['quantity'];
    $subtotal = $saleData['subtotal'];

    // Update inventory if the category is Beverages
   
        $stmt = $conn->prepare("UPDATE beverages SET quantity = quantity + ? WHERE beverage_id = ?");
        $stmt->bind_param("ii", $quantity, $product_id);
        $stmt->execute();
        $stmt->close();
 
    // Update the transaction_receipts table
    $stmt = $conn->prepare("UPDATE transaction_receipts SET total = total - ? WHERE trans_id = ?");
    $stmt->bind_param("di", $subtotal, $trans_id);
    $stmt->execute();
    $stmt->close();

    // Delete the sale record
    $stmt = $conn->prepare("DELETE FROM sales WHERE sale_id = ?");
    $stmt->bind_param("i", $saleId);
    $stmt->execute();
    $stmt->close();

    // Commit the transaction
    $conn->commit();

    echo "Sale deleted successfully!";
} catch (Exception $e) {
    // Rollback the transaction in case of error
    $conn->rollback();
    die("Error: " . $e->getMessage());
}

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