<?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']) || !isset($_POST['code']) || !isset($_POST['discount']) || !isset($_POST['is_active'])) {
    $response['message'] = 'Missing required fields (id, code, discount, is_active).';
    echo json_encode($response);
    exit;
}

$id = (int)$_POST['id'];
$code = trim($_POST['code']);
$discount = (float)$_POST['discount'];
$isActive = (int)$_POST['is_active'];

if ($id <= 0 || empty($code) || $discount <= 0) {
    $response['message'] = 'Invalid data provided.';
    echo json_encode($response);
    exit;
}

// --- 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 = "UPDATE coupons SET code = ?, discount_amount = ?, is_active = ? WHERE id = ?";
$stmt = $conn->prepare($sql);

if ($stmt) {
    $stmt->bind_param("sdii", $code, $discount, $isActive, $id);
    if ($stmt->execute()) {
        if ($stmt->affected_rows > 0) {
            $response['status'] = 'success';
            $response['message'] = 'Coupon updated successfully.';
        } else {
            $response['message'] = 'No changes were made or coupon not found.';
        }
    } else {
        $response['message'] = 'Database Error: Could not update 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);
?>