<?php
// admin/delete-product-ajax.php
error_reporting(E_ALL);
ini_set('display_errors', 0);

// Set content type to JSON
header('Content-Type: application/json');

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Include config
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

// Check if admin
if (!isAdmin()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Get ID
$id = isset($_POST['id']) ? intval($_POST['id']) : 0;

if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid ID']);
    exit;
}

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

    if (!$product) {
        echo json_encode(['success' => false, 'message' => 'Product not found']);
        exit;
    }

    // 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 first
    $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]);

    echo json_encode([
        'success' => true,
        'message' => 'Product deleted successfully',
        'name' => $product['name']
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>