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

class PromotionController {

    private $conn;

    public function __construct() {
        $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if ($this->conn->connect_error) {
            die("Error de conexión: " . $this->conn->connect_error);
        }
    }

    public function applyPromotion($code) {
        $stmt = $this->conn->prepare("SELECT * FROM promotions WHERE code = ? AND (uses_limit IS NULL OR uses_count < uses_limit)");
        $stmt->bind_param("s", $code);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {
            return $result->fetch_assoc();
        } else {
            return null;
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    if (isset($data['action']) && $data['action'] === 'apply_promotion') {
        $promotionController = new PromotionController();
        $promotion = $promotionController->applyPromotion($data['code']);
        if ($promotion) {
            echo json_encode(['success' => true, 'promotion' => $promotion]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Código de promoción inválido o expirado.']);
        }
    }
}
?>