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

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

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

    // First, fetch the product_id and quantity from the sales table
    $selectSalesStmt = $conn->prepare("SELECT product_id, quantity FROM sales WHERE trans_id = ?");
    $selectSalesStmt->bind_param("i", $transId);
    $selectSalesStmt->execute();
    $salesResult = $selectSalesStmt->get_result();

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

    // Prepare SQL statements to delete records
    $stmt1 = $conn->prepare("DELETE FROM transaction_receipts WHERE trans_id = ?");
    $stmt2 = $conn->prepare("DELETE FROM payments WHERE trans_id = ?");
    $stmt3 = $conn->prepare("DELETE FROM sales WHERE trans_id = ?");
    
    // Bind parameters
    $stmt1->bind_param("i", $transId);
    $stmt2->bind_param("i", $transId);
    $stmt3->bind_param("i", $transId);
    
    // Execute delete statements
    $deleteSuccess = $stmt1->execute() && $stmt2->execute() && $stmt3->execute();
    
    // Close the statements
    $stmt1->close();
    $stmt2->close();
    $stmt3->close();
    
    if ($deleteSuccess) {
        // If all deletes are successful, commit the transaction
        $conn->commit();
        echo json_encode(['success' => true]);
    } else {
        // If there is an error deleting, rollback and send an error response
        $conn->rollback();
        echo json_encode(['error' => 'Failed to delete transaction.']);
    }
} else {
    echo json_encode(['error' => 'Invalid request']);
}
?>
