<?php
include_once 'shikanisha.kts.php';
session_start();

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['trans_id'])) {
    $transId = $conn->real_escape_string($_POST['trans_id']);
    $date = date('Y-m-d H:i:s');
    $disposedBy = $_SESSION['user'];

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

    // First, get the shift_id and transaction total amount
    $shiftQuery = $conn->prepare("
        SELECT shift_id, total 
        FROM transaction_receipts 
        WHERE trans_id = ?
    ");
    if (!$shiftQuery) {
        error_log("Failed to prepare shift query: " . $conn->error);
        $conn->rollback();
        echo json_encode(['error' => 'Failed to prepare shift query: ' . $conn->error]);
        exit();
    }

    $shiftQuery->bind_param("i", $transId);
    if (!$shiftQuery->execute()) {
        error_log("Failed to execute shift query: " . $conn->error);
        $conn->rollback();
        echo json_encode(['error' => 'Failed to execute shift query: ' . $conn->error]);
        $shiftQuery->close();
        exit();
    }
    $shiftResult = $shiftQuery->get_result();
    $shiftData = $shiftResult->fetch_assoc();
    $shiftQuery->close();

    $shiftId = $shiftData['shift_id'] ?? null;
    $transactionTotal = $shiftData['total'] ?? 0;

    // Fetch product_id, category, quantity, and product_name from the sales table
    $selectSalesStmt = $conn->prepare("SELECT product_id, category, quantity, product_name FROM sales WHERE trans_id = ?");
    if (!$selectSalesStmt) {
        error_log("Failed to prepare select statement: " . $conn->error);
        $conn->rollback();
        echo json_encode(['error' => 'Failed to prepare select statement: ' . $conn->error]);
        exit();
    }

    $selectSalesStmt->bind_param("i", $transId);
    if (!$selectSalesStmt->execute()) {
        error_log("Failed to execute select statement: " . $conn->error);
        $conn->rollback();
        echo json_encode(['error' => 'Failed to execute select statement: ' . $conn->error]);
        $selectSalesStmt->close();
        exit();
    }
    $salesResult = $selectSalesStmt->get_result();

    $updatedProducts = [];
    if ($salesResult->num_rows > 0) {
        while ($sale = $salesResult->fetch_assoc()) {
            $qty = round($sale['quantity']);
            $productId = $sale['product_id'];
            $category = $sale['category'];

            // Handle 'Beverages' category
            if ($category === 'Beverage' || $category === 'Beverages') {
                if ($qty > 0) {
                    $updateProductStmt = $conn->prepare("UPDATE beverages SET quantity = quantity + ? WHERE beverage_id = ?");
                    $updateProductStmt->bind_param("ii", $qty, $productId);
                    if (!$updateProductStmt->execute()) {
                        error_log("Failed to update beverage quantity. Error: " . $conn->error);
                        $conn->rollback();
                        echo json_encode(['error' => 'Failed to update beverage quantity']);
                        exit();
                    }
                    $updatedProducts[] = [
                        'product_name' => $sale['product_name'],
                        'quantity_updated' => $qty,
                        'category' => $category
                    ];
                    $updateProductStmt->close();
                }
            }
            // Handle 'Food' category
            elseif ($category === 'Food') {
                if ($qty > 0) {
                    $disposeStmt = $conn->prepare("INSERT INTO dispose (disposed_by, date) VALUES (?, ?)");
                    $disposeStmt->bind_param("ss", $disposedBy, $date);
                    if (!$disposeStmt->execute()) {
                        error_log("Failed to execute insert statement for dispose table: " . $conn->error);
                        $conn->rollback();
                        echo json_encode(['error' => 'Failed to insert into dispose table']);
                        exit();
                    }
                    $disposeId = $disposeStmt->insert_id;
                    $disposeStmt->close();

                    $disposedItemsStmt = $conn->prepare("INSERT INTO disposed_items (product_name, quantity, dispose_id, dispose_date, product_id, category) VALUES (?, ?, ?, ?, ?, ?)");
                    $disposedItemsStmt->bind_param("siisis", $sale['product_name'], $qty, $disposeId, $date, $productId, $category);
                    if (!$disposedItemsStmt->execute()) {
                        error_log("Failed to insert into disposed_items table: " . $conn->error);
                        $conn->rollback();
                        echo json_encode(['error' => 'Failed to insert into disposed_items table']);
                        exit();
                    }
                    $updatedProducts[] = [
                        'product_name' => $sale['product_name'],
                        'quantity_updated' => $qty,
                        'category' => $category
                    ];
                    $disposedItemsStmt->close();
                }
            }
        }
    }
    $selectSalesStmt->close();

    if (!empty($updatedProducts)) {
        // Prepare delete statements
        $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 = ?");

        // Check if delete statements are prepared successfully
        if (!$stmt1 || !$stmt2 || !$stmt3) {
            $conn->rollback();
            echo json_encode(['error' => 'Failed to prepare delete statements: ' . $conn->error]);
            exit();
        }

        // Bind parameters for deletion
        $stmt1->bind_param("i", $transId); 
        $stmt2->bind_param("i", $transId);
        $stmt3->bind_param("i", $transId);

        // Execute delete statements and check success
        $deleteSuccess = $stmt1->execute() && $stmt2->execute() && $stmt3->execute();

        // Close delete statements
        $stmt1->close();
        $stmt2->close();
        $stmt3->close();

        // Update shift totals if this transaction was part of a shift
        if ($shiftId) {
            $updateShiftStmt = $conn->prepare("UPDATE shifts SET total_orders = total_orders - ?, total_debt = total_debt - ? WHERE shift_id = ?");
            if (!$updateShiftStmt) {
                $conn->rollback();
                echo json_encode(['error' => 'Failed to prepare shift update statement: ' . $conn->error]);
                exit();
            }
            $updateShiftStmt->bind_param("dii", $transactionTotal, $transactionTotal, $shiftId);
            if (!$updateShiftStmt->execute()) {
                $conn->rollback();
                echo json_encode(['error' => 'Failed to update shift totals: ' . $conn->error]);
                exit();
            }
            $updateShiftStmt->close();
        }

        if ($deleteSuccess) {
            // Commit transaction on success
            $conn->commit();
            echo json_encode(['success' => true, 'message' => 'Transaction successfully deleted and quantities updated.']);
        } else {
            // Rollback on delete failure
            $conn->rollback();
            echo json_encode(['error' => 'Failed to delete transaction records.']);
        }
    } else {
        // If no products were updated, rollback transaction
        $conn->rollback();
        echo json_encode(['error' => 'No products updated']);
    }
} else {
    echo json_encode(['error' => 'Invalid request']);
}
?>