<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Content-Type: application/json; charset=UTF-8");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once __DIR__ . '/../config/Database.php';
require_once __DIR__ . '/../models/Promotion.php';

$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

$promotion = new Promotion();

if ($method === 'GET' && $action === 'get_all') {
    $promotions = $promotion->getAllPromotions();
    echo json_encode($promotions);
} else if ($method === 'GET' && $action === 'active') {
    $promotions = $promotion->getActivePromotions();
    echo json_encode($promotions);
} else if ($method === 'GET' && $action === 'get') {
    $id = isset($_GET['id']) ? $_GET['id'] : '';
    $promo = $promotion->getPromotion($id);
    
    if ($promo) {
        echo json_encode($promo);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'Promotion not found']);
    }
} else if ($method === 'POST' && $action === 'create') {
    $data = json_decode(file_get_contents("php://input"), true);
    
    if (!isset($data['id'])) {
        $data['id'] = 'p-' . time();
    }
    
    $result = $promotion->createPromotion($data);
    echo json_encode($result);
} else if ($method === 'GET' && $action === 'get_discount') {
    $productId = isset($_GET['product_id']) ? $_GET['product_id'] : 0;
    $quantity = isset($_GET['quantity']) ? $_GET['quantity'] : 1;
    $totalAmount = isset($_GET['total_amount']) ? $_GET['total_amount'] : 0;
    
    $discount = $promotion->getAppliedDiscount($productId, $quantity, $totalAmount);
    echo json_encode(['discount_amount' => $discount]);
} else {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid action']);
}
?>
