<?php
include(__DIR__ . '/includes/functions.php');
$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

$sports_file = __DIR__ . '/api/sports.php';

// Função para salvar o novo link codificado
function saveEncodedLink($new_link) {
    global $sports_file;
    $encoded_link = base64_encode($new_link);

    $sports_code = file_get_contents($sports_file);
    $updated_code = preg_replace(
        '/\$encoded_link\s*=\s*[\'"].*?[\'"];/',
        "\$encoded_link = '$encoded_link';",
        $sports_code
    );

    file_put_contents($sports_file, $updated_code);
    $_SESSION['success_message'] = '✅ Link atualizado com sucesso!';
}

// Função para remover o link existente
function removeLink() {
    global $sports_file;

    $sports_code = file_get_contents($sports_file);
    $updated_code = preg_replace(
        '/\$encoded_link\s*=\s*[\'"].*?[\'"];/',
        "\$encoded_link = '';",
        $sports_code
    );

    file_put_contents($sports_file, $updated_code);
    $_SESSION['success_message'] = '🗑️ Link removido com sucesso!';
}

// Verificações de ações
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['new_link'])) {
        $new_link = trim($_POST['new_link']);
        if (!empty($new_link)) {
            if (!filter_var($new_link, FILTER_VALIDATE_URL)) {
                $_SESSION['error_message'] = '⚠️ Por favor, insira uma URL válida!';
            } else {
                saveEncodedLink($new_link);
                header("Location: " . $_SERVER['PHP_SELF']);
                exit();
            }
        } else {
            $_SESSION['error_message'] = '⚠️ Por favor, insira um link válido!';
        }
    }

    if (isset($_POST['remove_link'])) {
        removeLink();
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }
}

$page_title = "⚽ Gestione sportive (Webview)";

$page_content = '<div class="container mt-5">
    <div class="card mb-5 mb-xl-12">
        <div class="card-body py-12">
            <div class="d-flex align-items-center mb-7">
                <span class="symbol symbol-50px me-5">
                    <span class="symbol-label bg-light-primary">
                        <i class="ki-outline ki-sports fs-2x text-primary"></i>
                    </span>
                </span>
                <h2 class="mb-0">🌐 Gestione Webview sportive</h2>
            </div>';

if (isset($_SESSION['success_message'])) {
    $page_content .= '<div class="alert alert-success d-flex align-items-center" role="alert">
        <i class="ki-outline ki-check-circle fs-2x text-success me-4"></i>
        <div class="d-flex flex-column">
            <h4 class="mb-1 text-success">Sucesso!</h4>
            <span>' . htmlspecialchars($_SESSION['success_message']) . '</span>
        </div>
    </div>';
    unset($_SESSION['success_message']);
}

if (isset($_SESSION['error_message'])) {
    $page_content .= '<div class="alert alert-danger d-flex align-items-center" role="alert">
        <i class="ki-outline ki-cross-circle fs-2x text-danger me-4"></i>
        <div class="d-flex flex-column">
            <h4 class="mb-1 text-danger">Erro!</h4>
            <span>' . htmlspecialchars($_SESSION['error_message']) . '</span>
        </div>
    </div>';
    unset($_SESSION['error_message']);
}

$page_content .= '<div class="row mb-12">
                <div class="col-xl-12 mb-15 mb-xl-0 pe-5">
                    <h4 class="mb-4">🔗 Configurazione Webview sportive</h4>
                    <p class="fs-6 fw-semibold text-gray-600 py-4 m-0">
                        🎯 Aggiorna il link di Sports Webview qui sotto. Assicurati di utilizzare un URL valido.
                    </p>
                    
                    <form method="POST" action="">
                        <div class="form-group mb-6">
                            <label for="new_link" class="fs-5 fw-bold mb-3">🌍 Nuovo URL di Webview:</label>
                            <input 
                                type="url" 
                                class="form-control form-control-lg" 
                                name="new_link" 
                                id="new_link" 
                                placeholder="https://exemplo.com/webview" 
                                required>
                            <div class="text-muted mt-2">🔗 Dovrebbe iniziare con http:// ou https://</div>
                        </div>
                        
                        <div class="d-flex justify-content-between mt-8">
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="ki-outline ki-check fs-2 me-2"></i> 💾 Salva impostazioni
                            </button>
                            <button type="submit" name="remove_link" class="btn btn-danger btn-lg" onclick="return confirmRemover()">
                                <i class="ki-outline ki-trash fs-2 me-2"></i> 🗑️Rimuovi Link
                            </button>
                        </div>
                    </form>
                </div>
            </div>
            
            <div class="row mt-10">
                <div class="col-xl-12">
                    <div class="notice d-flex bg-light-warning rounded border-warning border border-dashed p-6">
                        <span class="svg-icon svg-icon-2tx svg-icon-warning me-4">
                            <i class="ki-outline ki-information fs-2x text-warning"></i>
                        </span>
                        <div class="d-flex flex-stack flex-grow-1">
                            <div class="fw-semibold">
                                <h4 class="text-gray-900 fw-bold">ℹ️ Informazioni importanti</h4>
                                <div class="fs-5 text-gray-700">
                                    Questa impostazione aggiorna il collegamento codificato in base64 che viene utilizzato in visualizzazione web sportive.
                                    <br>Il collegamento verrà codificato automaticamente al momento del salvataggio..
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Confirmação para remoção
function confirmRemover() {
    return confirm("⚠️ Tem certeza que deseja remover o link atual? Esta ação não pode ser desfeita!");
}
</script>';

include 'includes/layout.php';
?>