<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['POST']);
hw_require_auth();

try {
    $pdo = hw_db();
    
    $data = json_decode(file_get_contents('php://input'), true);
    $product_id = (int)($data['product_id'] ?? 0);
    
    if (!$product_id) {
        hw_json(['success' => false, 'message' => 'Invalid product ID'], 400);
        exit;
    }
    
    // Get product to delete image if exists
    $stmt = $pdo->prepare("SELECT image_url FROM products WHERE id = ?");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$product) {
        hw_json(['success' => false, 'message' => 'Product not found'], 404);
        exit;
    }
    
    // Delete image file if exists
    if ($product['image_url']) {
        $image_path = __DIR__ . '/../../' . ltrim($product['image_url'], '/');
        if (file_exists($image_path)) {
            @unlink($image_path);
        }
    }
    
    // Delete product
    $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
    $stmt->execute([$product_id]);
    
    // Also delete related order items
    $stmt = $pdo->prepare("DELETE FROM order_items WHERE product_id = ?");
    $stmt->execute([$product_id]);
    
    hw_json(['success' => true, 'message' => 'Product deleted successfully']);
    
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}
