<?php
header("Content-Type: application/json");
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'auth_guard.php';
require_once '../config/database.php';
$db = getDB();

$data = json_decode(file_get_contents("php://input"), true);

if (!$data) {
    echo json_encode(["success" => false, "message" => "Empty coupon data parsed"]);
    exit;
}

// Extract and sanitize input values fields cleanly
$code             = trim($db->real_escape_string($data['code'] ?? ''));
$discount_percent = intval($data['discount_percent'] ?? 0);
$expiry_date      = trim($db->real_escape_string($data['expiry_date'] ?? '')); // Expected Format: YYYY-MM-DD

if (empty($code) || $discount_percent <= 0 || empty($expiry_date)) {
    echo json_encode(["success" => false, "message" => "All fields including code, percentage, and valid expiry date are required"]);
    exit;
}

// Convert input coupon code completely to uppercase to eliminate duplicate casing bugs
$code = strtoupper($code);

// Guard condition: Ensure the coupon code doesn't already exist in the records
$check = $db->query("SELECT id FROM coupons WHERE code = '$code' LIMIT 1");
if ($check && $check->num_rows > 0) {
    echo json_encode(["success" => false, "message" => "Coupon code '$code' already exists in your store records"]);
    exit;
}

// Insert the new promotional coupon voucher safely into your target columns
$query = "INSERT INTO coupons (code, discount_percent, is_active, expiry_date) 
          VALUES ('$code', $discount_percent, 1, '$expiry_date')";

if ($db->query($query)) {
    echo json_encode(["success" => true, "message" => "Coupon code '$code' published successfully with auto-expiry logic"]);
} else {
    echo json_encode(["success" => false, "message" => "Database insertion error: " . $db->error]);
}