<?php
// admin/delete-product.php (Fallback if JavaScript fails)
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($id <= 0) {
    $_SESSION['error_msg'] = 'Invalid product ID';
    header('Location: products.php');
    exit;
}

// Get product
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$id]);
$product = $stmt->fetch();

if (!$product) {
    $_SESSION['error_msg'] = 'Product not found';
    header('Location: products.php');
    exit;
}

try {
    // Delete product images
    if ($product['image']) {
        $image_path = __DIR__ . '/../assets/images/products/' . $product['image'];
        if (file_exists($image_path)) {
            unlink($image_path);
        }
    }
    
    // Delete gallery images
    if ($product['gallery_images']) {
        $gallery_images = explode(',', $product['gallery_images']);
        foreach ($gallery_images as $gallery_img) {
            if (!empty($gallery_img)) {
                $gallery_path = __DIR__ . '/../assets/images/products/' . $gallery_img;
                if (file_exists($gallery_path)) {
                    unlink($gallery_path);
                }
            }
        }
    }
    
    // Delete product attributes
    $stmt = $pdo->prepare("DELETE FROM product_attributes WHERE product_id = ?");
    $stmt->execute([$id]);
    
    // Delete product
    $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
    $stmt->execute([$id]);
    
    $_SESSION['success_msg'] = 'Product "' . $product['name'] . '" deleted successfully!';
    header('Location: products.php');
    exit;
    
} catch (Exception $e) {
    $_SESSION['error_msg'] = 'Error deleting product: ' . $e->getMessage();
    header('Location: products.php');
    exit;
}
?>