<?php
include "../../includes/db.php";
include "../../includes/auth.php";

$isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
if ($isAjax) {
    header("Content-Type: application/json");
}

if (isset($_POST['id'])) {
    $id = (int)$_POST['id'];
    // Also delete associated features
    $conn->query("DELETE FROM service_features WHERE service_id=$id");
    $conn->query("DELETE FROM services WHERE id=$id");
    if ($conn->affected_rows > 0) {
        if ($isAjax) {
            echo json_encode(['status' => 'success']);
        } else {
            header("Location: services.php?deleted=1");
        }
    } else {
        if ($isAjax) {
            echo json_encode(['status' => 'error', 'message' => 'Service not found or already deleted.']);
        } else {
            header("Location: services.php?deleted=0");
        }
    }
} else {
    if ($isAjax) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Missing id.']);
    } else {
        header("Location: services.php?deleted=0");
    }
}
