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

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['sale_id'])) {
    $saleId = $conn->real_escape_string($_POST['sale_id']);

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

    // Fetch the necessary details from the sales table
    $fetchSaleStmt = $conn->prepare("SELECT product_id, quantity, trans_id, subtotal FROM sales WHERE sale_id = ?");
    $fetchSaleStmt->bind_param("i", $saleId);
    $fetchSaleStmt->execute();
    $result = $fetchSaleStmt->get_result();
    $saleData = $result->fetch_assoc();
    $fetchSaleStmt->close();

    // Check if sale data was retrieved
    if (!$saleData) {
        $conn->rollback();
        echo json_encode(['error' => 'Sale item not found.']);
        exit();
    }

    // Update the products table
    $updateProductsStmt = $conn->prepare("UPDATE products SET shop_quantity = shop_quantity + ? WHERE product_id = ?");
    $updateProductsStmt->bind_param("di", $saleData['quantity'], $saleData['product_id']);
    if (!$updateProductsStmt->execute()) {
        // If there is an error updating, rollback and send an error response
        $conn->rollback();
        echo json_encode(['error' => 'Failed to update product quantity.']);
        $updateProductsStmt->close();
        exit();
    }
    $updateProductsStmt->close();

    // Update the transaction_receipts table
    $updateReceiptsStmt = $conn->prepare("UPDATE transaction_receipts SET total = total - ? WHERE trans_id = ?");
    $updateReceiptsStmt->bind_param("di", $saleData['subtotal'], $saleData['trans_id']);
    if (!$updateReceiptsStmt->execute()) {
        // If there is an error updating, rollback and send an error response
        $conn->rollback();
        echo json_encode(['error' => 'Failed to update transaction total.']);
        $updateReceiptsStmt->close();
        exit();
    }
    $updateReceiptsStmt->close();

    // Delete the sale item
    $deleteSaleStmt = $conn->prepare("DELETE FROM sales WHERE sale_id = ?");
    $deleteSaleStmt->bind_param("i", $saleId);
    if (!$deleteSaleStmt->execute()) {
        // If there is an error deleting, rollback and send an error response
        $conn->rollback();
        echo json_encode(['error' => 'Failed to delete sale item.']);
        $deleteSaleStmt->close();
        exit();
    }
    $deleteSaleStmt->close();

    // If all operations were successful, commit the transaction
    $conn->commit();
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['error' => 'Invalid request']);
}
?>
