<?php
/**
 * Coupons API Endpoint
 * Coupon validation
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/constants.php';
require_once __DIR__ . '/../includes/Database.php';
require_once __DIR__ . '/../includes/Auth.php';
require_once __DIR__ . '/../includes/Order.php';

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

$auth = new Auth();
$order = new Order();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            if ($action === 'validate') {
                $code = $_GET['code'] ?? '';
                $subtotal = floatval($_GET['subtotal'] ?? 0);
                
                $coupon = $order->validateCoupon($code, $subtotal);
                
                if ($coupon) {
                    echo json_encode(['success' => true, 'coupon' => $coupon]);
                } else {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Invalid or expired coupon']);
                }
            }
            break;

        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>

