<?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 and trans_id for rollback purposes
        $stmt = $conn->prepare("SELECT product_id, 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'];
        $trans_id = $saleData['trans_id'];
        $stmt->close();

        // Update the products table with the original quantity
        $stmt = $conn->prepare("UPDATE products SET shop_quantity = shop_quantity + ? - ? WHERE product_id = ?");
        $stmt->bind_param("ddi", $originalQuantity, $editedQuantity, $product_id);
        $stmt->execute();
        $stmt->close();

        // Update the transaction_receipts table subtracting the original subtotal
        $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']);
}
?>
