<?php
// --- Setup ---
header('Content-Type: application/json');
require 'db_connect.php'; // Your database connection file

$response = [
    'status' => 'error',
    'message' => 'An unknown error occurred.'
];

// --- Validate Input ---
if (!isset($_POST['id']) || empty($_POST['id'])) {
    $response['message'] = 'Missing required field: id.';
    echo json_encode($response);
    exit;
}

$id = (int)$_POST['id'];

// --- Validate Database Connection ---
if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    $response['message'] = 'Server Error: Database connection failed.';
    echo json_encode($response);
    exit;
}

// --- Prepare and Execute Query ---
$sql = "DELETE FROM coupons WHERE id = ?";
$stmt = $conn->prepare($sql);

if ($stmt) {
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        if ($stmt->affected_rows > 0) {
            $response['status'] = 'success';
            $response['message'] = 'Coupon deleted successfully.';
        } else {
            $response['message'] = 'Coupon not found or already deleted.';
        }
    } else {
        $response['message'] = 'Database Error: Could not delete coupon.';
    }
    $stmt->close();
} else {
    http_response_code(500);
    $response['message'] = 'Server Error: Could not prepare the database statement.';
}

$conn->close();

// --- Send Final JSON Response ---
echo json_encode($response);
?>