<?php
require 'config.php';
require 'header.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

// Criar nova stream a partir da aplicação escolhida
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $app_name = $_POST['app_name'] ?? '';

    if (!in_array($app_name, ['live1', 'live2', 'live3', 'live4'])) {
        echo "<div class='alert alert-danger text-center mt-4'>❌ Aplicação inválida.</div>";
    } else {
        try {
            // Obter ID da aplicação
            $stmt = $pdo->prepare("SELECT id FROM applications WHERE name = ?");
            $stmt->execute([$app_name]);
            $app = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$app) {
                // Se não existir, cria a aplicação
                $pdo->prepare("INSERT INTO applications (name) VALUES (?)")->execute([$app_name]);
                $app_id = $pdo->lastInsertId();
            } else {
                $app_id = $app['id'];
            }

            // Gerar chave aleatória
            $stream_key = bin2hex(random_bytes(6));

            // Inserir nova stream
            $pdo->prepare("INSERT INTO streams (app_id, stream_key, active) VALUES (?, ?, 0)")
                ->execute([$app_id, $stream_key]);

            echo "<div class='alert alert-success text-center mt-4'>
                    ✅ Live criada com sucesso!<br>
                    <strong>Aplicação:</strong> $app_name<br>
                    <strong>Stream Key:</strong> $stream_key
                  </div>";

        } catch (Exception $e) {
            echo "<div class='alert alert-danger text-center mt-4'>❌ Erro: " . htmlspecialchars($e->getMessage()) . "</div>";
        }
    }
}
?>

<div class="container mt-5" style="max-width:600px;">
    <h3 class="mb-4 text-center">🎬 Criar Nova Live</h3>

    <div class="card shadow-sm p-4">
        <form method="POST">
            <div class="mb-3">
                <label for="app_name" class="form-label fw-bold">Selecione a Aplicação</label>
                <select name="app_name" id="app_name" class="form-select" required>
                    <option value="">-- Escolha uma aplicação --</option>
                    <option value="live1">live1</option>
                    <option value="live2">live2</option>
                    <option value="live3">live3</option>
                    <option value="live4">live4</option>
                </select>
            </div>

            <button type="submit" class="btn btn-success w-100">Criar Live</button>
            <a href="index.php" class="btn btn-secondary w-100 mt-2">Voltar</a>
        </form>
    </div>
</div>

<?php require 'footer.php'; ?>
