<?php
include("connection.php");

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!isset($_GET['id'])) {
    die("Invalid request.");
}

$id = (int)$_GET['id'];

if ($id <= 0) {
    die("Invalid product ID.");
}

// Folder where images are stored
$uploadDir = "./assets/images/products/";

// 1) Fetch product to get image names
$sql  = "SELECT product_main_image, product_images FROM products WHERE id = $id LIMIT 1";
$res  = mysqli_query($con, $sql);

if (!$res || mysqli_num_rows($res) == 0) {
    die("Product not found.");
}

$product = mysqli_fetch_assoc($res);

// 2) Delete main image file
if (!empty($product['product_main_image'])) {
    $mainPath = $uploadDir . $product['product_main_image'];
    if (file_exists($mainPath)) {
        @unlink($mainPath);
    }
}

// 3) Delete gallery images (JSON array)
if (!empty($product['product_images'])) {
    $images = json_decode($product['product_images'], true);
    if (is_array($images)) {
        foreach ($images as $img) {
            $imgPath = $uploadDir . $img;
            if (file_exists($imgPath)) {
                @unlink($imgPath);
            }
        }
    }
}

// 4) Delete database record
$deleteSql = "DELETE FROM products WHERE id = $id";
if (mysqli_query($con, $deleteSql)) {
    header("Location: view_product.php");
    exit();
} else {
    echo "Error deleting product: " . mysqli_error($con);
}
