<?php
require('config.php'); // Include your database connection file

// Get and sanitize the posted product ID
$productID = mysqli_real_escape_string($connect, $_POST['product']);
$response = array();

// Check if the product ID is provided
if (!empty($productID)) {
    // Start a transaction
    $connect->begin_transaction();

    try {
        // 1. Delete from creditsPayments table
        $deleteCreditsPayments = "DELETE cp FROM creditsPayments cp
                                  JOIN credits c ON cp.creditID = c.id
                                  JOIN transactions t ON c.transID = t.id
                                  WHERE t.productCode = '$productID'";
        $connect->query($deleteCreditsPayments);

        // 2. Delete from credits table
        $deleteCredits = "DELETE c FROM credits c
                          JOIN transactions t ON c.transID = t.id
                          WHERE t.productCode = '$productID'";
        $connect->query($deleteCredits);

        // 3. Delete from transactions table
        $deleteTransactions = "DELETE FROM transactions WHERE productCode = '$productID'";
        $connect->query($deleteTransactions);

        // 4. Delete from stock table
        $deleteStock = "DELETE FROM stock WHERE productID = '$productID'";
        $connect->query($deleteStock);

        // 5. Delete from products table
        $deleteProduct = "DELETE FROM products WHERE id = '$productID'";
        $connect->query($deleteProduct);

        // Check if the product was deleted successfully
        if ($connect->affected_rows > 0) {
            // Commit the transaction
            $connect->commit();
            $response = array(
                "error" => false,
                "message" => "Product and related records deleted successfully"
            );
        } else {
            // Rollback the transaction if no product was deleted
            $connect->rollback();
            $response = array(
                "error" => true,
                "message" => "No product found with the provided product ID"
            );
        }
    } catch (Exception $e) {
        // Rollback the transaction in case of any error
        $connect->rollback();
        $response = array(
            "error" => true,
            "message" => "Error deleting product and related records: " . $e->getMessage()
        );
    }
} else {
    // Missing product ID in the request
    $response = array(
        "error" => true,
        "message" => "Product ID is required"
    );
}

// Output the result as JSON
echo json_encode($response);

// Close the database connection
$connect->close();
?>
