<?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['code']) || empty(trim($_POST['code']))) {
    $response['message'] = 'Please enter a coupon code.';
    echo json_encode($response);
    exit;
}

$couponCode = trim($_POST['code']);

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

// --- Prepare and Execute Query ---
// Use a prepared statement to prevent SQL injection
$sql = "SELECT discount_amount, is_active FROM coupons WHERE code = ? LIMIT 1";
$stmt = $conn->prepare($sql);

if ($stmt) {
    $stmt->bind_param("s", $couponCode);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $coupon = $result->fetch_assoc();

        if ($coupon['is_active'] == 1) {
            // --- Success ---
            $response['status'] = 'success';
            $response['message'] = 'Coupon applied successfully!';
            $response['discount'] = (float)$coupon['discount_amount'];
        } else {
            // --- Coupon is Inactive ---
            $response['message'] = 'This coupon is no longer active.';
        }
    } else {
        // --- Coupon Not Found ---
        $response['message'] = 'Invalid coupon code.';
    }

    $stmt->close();
} else {
    // --- Database Statement Error ---
    http_response_code(500);
    $response['message'] = 'Server Error: Could not prepare the database statement.';
}

$conn->close();

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

?>