<?php
/**
 * ============================================================================
 * ajax/delete-product.php
 * Delete product
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once '../config/config.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    jsonError('Unauthorized', 401);
}

if (!isPost()) {
    jsonError('Invalid request method');
}

$productId = (int)($_POST['product_id'] ?? 0);
$userId = getUserId();

if ($productId <= 0) {
    jsonError('Invalid product ID');
}

$database = new Database();
$db = $database->getConnection();

// Check if user owns the product
$sql = "SELECT seller_id, images FROM products WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$productId]);
$product = $stmt->fetch();

if (!$product) {
    jsonError('Product not found');
}

if ($product['seller_id'] != $userId && getUserType() !== 'admin') {
    jsonError('Unauthorized to delete this product');
}

// Delete product images
if (!empty($product['images'])) {
    $images = json_decode($product['images'], true);
    foreach ($images as $image) {
        deleteFile($image);
    }
}

// Delete product
$sql = "DELETE FROM products WHERE id = ?";
$stmt = $db->prepare($sql);

if ($stmt->execute([$productId])) {
    logActivity($userId, 'delete_product', "Deleted product ID: $productId");
    jsonSuccess('Product deleted successfully');
} else {
    jsonError('Failed to delete product');
}
?>
