<?php
// --- DEBUGGING & SETUP ---
// These lines will help show us the exact error.
error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Content-Type: application/json');

// It's safer to put the response structure here.
$response = [
    'status' => 'error',
    'message' => 'An unknown server error occurred.'
];

// --- DATABASE CONNECTION ---
// Using a try-catch block is much safer for database connections.
try {
    require 'db_connect.php';
    if (!isset($conn) || $conn->connect_error) {
        throw new Exception('Database connection failed.');
    }
} catch (Throwable $e) {
    http_response_code(500);
    $response['message'] = 'Server Error: ' . $e->getMessage();
    echo json_encode($response);
    exit;
}

// --- VALIDATE INPUT ---
if (!isset($_POST['code']) || !isset($_POST['discount']) || !isset($_POST['is_active'])) {
    $response['message'] = 'Missing required fields (code, discount, is_active).';
    echo json_encode($response);
    exit;
}

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

if (empty($code) || $discount <= 0) {
    $response['message'] = 'Coupon code cannot be empty and discount must be a positive number.';
    echo json_encode($response);
    exit;
}

// --- PREPARE AND EXECUTE QUERY ---
$sql = "INSERT INTO coupons (code, discount_amount, is_active) VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);

if ($stmt) {
    $stmt->bind_param("sdi", $code, $discount, $isActive);

    if ($stmt->execute()) {
        $response['status'] = 'success';
        $response['message'] = 'Coupon added successfully.';
    } else {
        // Provide a more specific error if the coupon code is a duplicate
        if ($conn->errno == 1062) { // 1062 is the MySQL error code for a duplicate entry
            $response['message'] = 'Database Error: This coupon code already exists.';
        } else {
            $response['message'] = 'Database Error: Could not add coupon. Error: ' . $conn->error;
        }
    }
    $stmt->close();
} else {
    http_response_code(500);
    $response['message'] = 'Server Error: Could not prepare the database statement.';
}

$conn->close();

// --- SEND FINAL RESPONSE ---
echo json_encode($response);

?>