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

$response = [];

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

// --- Prepare and Execute Query ---
$sql = "SELECT id, code, discount_amount, is_active FROM coupons ORDER BY id DESC";
$stmt = $conn->prepare($sql);

if ($stmt) {
    $stmt->execute();
    $result = $stmt->get_result();

    $coupons = [];
    while ($row = $result->fetch_assoc()) {
        // Ensure data types are correct for the app
        $row['id'] = (int)$row['id'];
        $row['discount_amount'] = (float)$row['discount_amount'];
        $row['is_active'] = (int)$row['is_active'];
        $coupons[] = $row;
    }

    // --- Success: Send the JSON response ---
    echo json_encode($coupons);

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

$stmt->close();
$conn->close();

?>