<?php
require_once __DIR__ . '/../config/db.php';

$action = $_GET['action'] ?? 'list';

if ($action === 'list') {
    $stmt = $pdo->query("SELECT * FROM coupons WHERE is_active = 1 AND expiry_date >= CURDATE() ORDER BY id DESC");
    sendResponse(true, ['data' => $stmt->fetchAll()]);
}

if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    requireAuth(['admin']);
    $body = getJsonInput();
    $stmt = $pdo->prepare("INSERT INTO coupons (code, discount_type, discount_value, min_spend, expiry_date) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([
        strtoupper(trim($body['code'])),
        $body['discount_type'] ?? 'fixed',
        $body['discount_value'],
        $body['min_spend'] ?? 0,
        $body['expiry_date']
    ]);
    sendResponse(true, 'สร้างคูปองเรียบร้อย');
}

if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    requireAuth(['admin']);
    $body = getJsonInput();
    $stmt = $pdo->prepare("UPDATE coupons SET is_active = 0 WHERE id = ?");
    $stmt->execute([$body['id']]);
    sendResponse(true, 'ลบคูปองเรียบร้อย');
}
