<?php
/**
 * ADMIN AJAX: Delete Product
 */
header('Content-Type: application/json; charset=utf-8');

try {
    // Initialize
    define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
    require_once BASE_PATH . '/app/config/config.php';
    
    // Start session
    if (session_status() === PHP_SESSION_NONE) {
        session_name(SESSION_NAME);
        session_start();
    }
    
    // Must be POST
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'message' => 'Invalid request']);
        exit;
    }
    
    // Must be admin
    if (!isAdminLoggedIn()) {
        echo json_encode(['success' => false, 'message' => 'অ্যাডমিন লগইন প্রয়োজন']);
        exit;
    }
    
    // Load service
    require_once APP_PATH . '/services/product_service.php';
    
    // Get product ID (jQuery sends as productId from data-product-id)
    $productId = (int)($_POST['productId'] ?? $_POST['product_id'] ?? 0);
    
    if ($productId < 1) {
        echo json_encode(['success' => false, 'message' => 'অবৈধ পণ্য']);
        exit;
    }
    
    // Check if product has orders
    $stmt = Database::getInstance()->prepare("SELECT COUNT(*) FROM order_items WHERE product_id = ?");
    $stmt->execute([$productId]);
    $hasOrders = $stmt->fetchColumn();
    
    $forceDelete = !empty($_POST['force']) || !empty($_POST['forceDelete']);
    
    if ($hasOrders && !$forceDelete) {
        echo json_encode([
            'success' => false, 
            'message' => 'এই পণ্যের অর্ডার আছে, মুছে ফেলা যাবে না।',
            'has_orders' => true,
            'order_count' => $hasOrders
        ]);
        exit;
    }
    
    // If force delete, disable foreign key checks temporarily
    if ($hasOrders && $forceDelete) {
        Database::getInstance()->exec("SET FOREIGN_KEY_CHECKS = 0");
    }
    
    // Delete product
    $deleted = ProductService::delete($productId);
    
    // Re-enable foreign key checks
    if ($hasOrders && $forceDelete) {
        Database::getInstance()->exec("SET FOREIGN_KEY_CHECKS = 1");
    }
    
    if ($deleted) {
        echo json_encode(['success' => true, 'message' => 'পণ্য সফলভাবে মুছে ফেলা হয়েছে']);
    } else {
        echo json_encode(['success' => false, 'message' => 'পণ্য মুছতে সমস্যা হয়েছে']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'ত্রুটি: ' . $e->getMessage()]);
}
