<?php
include_once 'shikanisha.kts.php';

$response = [];

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['originalSaleId'])) {
    $saleId = $_POST['originalSaleId'];
    $originalQuantity = $_POST['originalQuantity'];
    $originalSubtotal = $_POST['originalSubtotal'];
    $editedQuantity = $_POST['quantity'];
    $editedSubtotal = $_POST['subtotal'];

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

    try {
        // Fetch the product_id, category, and trans_id for rollback purposes
        $stmt = $conn->prepare("SELECT product_id, category, trans_id FROM sales WHERE sale_id = ?");
        $stmt->bind_param("i", $saleId);
        $stmt->execute();
        $result = $stmt->get_result();
        $saleData = $result->fetch_assoc();
        $product_id = $saleData['product_id'];
        $category = $saleData['cat'];
        $trans_id = $saleData['trans_id'];
        $stmt->close();

        // If the category is Beverages, update inventory
        if ($category === 'Beverages') {
            $stmt = $conn->prepare("UPDATE beverages SET quantity = quantity + ? - ? WHERE beverage_id = ?");
            $stmt->bind_param("ddi", $originalQuantity, $editedQuantity, $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("ddi", $originalSubtotal, $editedSubtotal, $trans_id);
        $stmt->execute();
        $stmt->close();

        // Update the sales table with the new edited quantity and subtotal
        $stmt = $conn->prepare("UPDATE sales SET quantity = ?, subtotal = ? WHERE sale_id = ?");
        $stmt->bind_param("ddi", $editedQuantity, $editedSubtotal, $saleId);
        $stmt->execute();
        $stmt->close();

        // Commit the transaction
        $conn->commit();
        $response['status'] = 'success';
        $response['message'] = 'Sale updated successfully';
    } catch (mysqli_sql_exception $e) {
        // If there is an error, rollback the transaction
        $conn->rollback();
        $response['status'] = 'error';
        $response['message'] = 'Failed to update sale: ' . $e->getMessage();
    }

    echo json_encode($response);
} else {
    echo json_encode(['error' => 'Invalid request']);
}
?>
