<?php
include '../includes/config.php';

if (isset($_GET['del'])) {
    $id = intval($_GET['del']);
    
    // Preserve current page & search
    $page   = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $search = isset($_GET['search']) ? urlencode($_GET['search']) : '';

    try {
        $conn->beginTransaction();

        $sqlDeleteVariations = "DELETE FROM variations WHERE product_id = :id";
        $queryVariations = $conn->prepare($sqlDeleteVariations);
        $queryVariations->bindParam(':id', $id, PDO::PARAM_INT);
        $queryVariations->execute();

        $sqlDeleteProducts = "DELETE FROM products WHERE id = :id";
        $queryProducts = $conn->prepare($sqlDeleteProducts);
        $queryProducts->bindParam(':id', $id, PDO::PARAM_INT);
        $queryProducts->execute();

        if ($queryProducts->rowCount() > 0 || $queryVariations->rowCount() > 0) {
            $conn->commit();
            echo "<script>alert('Product and related variations deleted successfully.');</script>";
        } else {
            $conn->rollBack();
            echo "<script>alert('No product or related variations found to delete.');</script>";
        }
    } catch (Exception $e) {
        $conn->rollBack();
        echo "<script>alert('Error occurred: " . htmlspecialchars($e->getMessage()) . "');</script>";
    }

    // Redirect back to same page with search preserved
    echo "<script>window.location.href='../list_products.php?page={$page}&search={$search}';</script>";
}
?>
