<?php
require_once __DIR__ . '/includes/header.php';

$message = '';
$message_type = '';
$generated_code = '';
$generated_client = null;
$card_info = [];
$show_form = isset($_GET['novo']) || ($_SERVER['REQUEST_METHOD'] === 'POST');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = str_in($_POST['name'] ?? '');
    $m3u_url = str_in($_POST['m3u_url'] ?? '');
    $card_plan = normalize_card_plan($_POST['card_plan'] ?? 'mensal');

    $result = add_client($name, $m3u_url, $card_plan);

    if ($result['ok']) {
        $generated_client = $result;
        $generated_code = $result['activation_code_formatted'] ?? format_activation_code($result['activation_code'] ?? '');
        $card_info = $result['card'] ?? [];
        $message = 'Cliente criado com sucesso! Código gerado: ' . htmlspecialchars($generated_code);
        $message_type = 'success';
        $show_form = false;
    } else {
        $message = $result['message'] ?? 'Erro ao cadastrar cliente.';
        $message_type = 'error';
    }
}
?>

<style>
    .page-header {
        margin-bottom: 30px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 15px;
    }

    .page-header h1 {
        font-size: 28px;
        margin: 0;
        background: var(--primary-bg);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }

    .page-header p {
        color: #999;
        font-size: 14px;
        margin-top: 8px;
        width: 100%;
    }

    .header-actions {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }

    .btn-primary, .btn-secondary {
        padding: 12px 22px;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 600;
        text-decoration: none;
        border: none;
        cursor: pointer;
        transition: all 0.2s ease;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .btn-primary {
        background: var(--primary-bg);
        color: #fff;
    }

    .btn-secondary {
        background: rgba(255,255,255,.08);
        color: #fff;
        border: 1px solid rgba(255,255,255,.15);
    }

    .btn-primary:hover, .btn-secondary:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0,0,0,.3);
    }

    .alert {
        padding: 15px 20px;
        border-radius: 8px;
        margin-bottom: 20px;
    }

    .alert-success {
        background: rgba(46, 204, 113, 0.2);
        border: 1px solid #2ecc71;
        color: #2ecc71;
    }

    .alert-error {
        background: rgba(231, 76, 60, 0.2);
        border: 1px solid #e74c3c;
        color: #e74c3c;
    }

    .form-container, .code-result, .info-box {
        background: #1a1a1a;
        padding: 30px;
        border-radius: 12px;
        border: 1px solid rgba(255, 255, 255, 0.1);
        max-width: 800px;
    }

    .form-container { margin-bottom: 20px; }

    .form-group {
        display: flex;
        flex-direction: column;
        margin-bottom: 18px;
    }

    .form-group label {
        margin-bottom: 8px;
        color: #fff;
        font-weight: 500;
        font-size: 14px;
    }

    .form-group input, .form-group textarea {
        padding: 12px 15px;
        background: #111;
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 6px;
        color: #fff;
        font-size: 14px;
        font-family: inherit;
    }

    .form-group textarea {
        min-height: 90px;
        resize: vertical;
    }

    .form-group input:focus, .form-group textarea:focus {
        outline: none;
        border-color: var(--primary-solid, #8d2cff);
        box-shadow: 0 0 0 3px rgba(141, 44, 255, 0.15);
    }

    .info-box {
        margin-top: 20px;
    }

    .info-box h3 {
        font-size: 16px;
        margin-bottom: 12px;
        color: #fff;
    }

    .info-box ul {
        list-style: none;
        padding: 0;
        margin: 0;
    }

    .info-box li {
        padding: 8px 0;
        color: #999;
        font-size: 14px;
        border-bottom: 1px solid rgba(255,255,255,.05);
    }

    .info-box li:last-child { border-bottom: none; }

    .info-box li::before {
        content: "•";
        color: var(--primary-solid, #8d2cff);
        font-weight: bold;
        display: inline-block;
        width: 1em;
        margin-right: 8px;
    }

    .empty-state {
        max-width: 800px;
        text-align: center;
        padding: 50px 30px;
        background: #1a1a1a;
        border-radius: 12px;
        border: 1px solid rgba(255,255,255,.1);
    }

    .empty-state h2 {
        color: #fff;
        margin-bottom: 10px;
    }

    .empty-state p {
        color: #999;
        margin-bottom: 24px;
    }

    .card-preview-wrap {
        display: flex;
        justify-content: center;
        margin: 24px 0 8px;
    }

    .card-preview {
        width: min(100%, 320px);
        border-radius: 18px;
        box-shadow: 0 18px 45px rgba(0, 0, 0, .45);
        border: 1px solid rgba(255, 255, 255, .12);
    }

    .card-warning {
        margin-top: 12px;
        padding: 12px 14px;
        border-radius: 10px;
        background: rgba(243, 156, 18, .12);
        border: 1px solid rgba(243, 156, 18, .35);
        color: #f5c56a;
        font-size: 13px;
        text-align: center;
    }

    .plan-selector {
        display: grid;
        grid-template-columns: repeat(3, minmax(0, 1fr));
        gap: 12px;
    }

    .plan-option {
        cursor: pointer;
    }

    .plan-option input {
        position: absolute;
        opacity: 0;
        pointer-events: none;
    }

    .plan-box {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 6px;
        min-height: 92px;
        padding: 14px 10px;
        border-radius: 12px;
        border: 2px solid rgba(255, 255, 255, 0.14);
        background: #111;
        color: #ccc;
        text-align: center;
        transition: all 0.2s ease;
    }

    .plan-box strong {
        color: #fff;
        font-size: 15px;
    }

    .plan-box small {
        color: #888;
        font-size: 12px;
    }

    .plan-option input:checked + .plan-box {
        border-color: #a855f7;
        background: rgba(168, 85, 247, 0.14);
        box-shadow: 0 0 0 3px rgba(168, 85, 247, 0.18);
    }

    .plan-option input:focus-visible + .plan-box {
        outline: 2px solid #a855f7;
        outline-offset: 2px;
    }

    .plan-badge {
        display: inline-block;
        margin-top: 8px;
        padding: 6px 12px;
        border-radius: 999px;
        background: rgba(168, 85, 247, 0.18);
        border: 1px solid rgba(168, 85, 247, 0.45);
        color: #e9ddff;
        font-size: 13px;
        font-weight: 600;
    }

    @media (max-width: 720px) {
        .plan-selector {
            grid-template-columns: 1fr;
        }
    }
</style>

<div class="page-header">
    <div>
        <h1>✅ Ativar Cliente</h1>
        <p>Cadastre clientes com lista M3U e gere um código único de 12 dígitos (XXXX-XXXX-XXXX)</p>
    </div>
    <div class="header-actions">
        <a href="list_dns.php" class="btn-secondary">📋 Ver clientes</a>
        <?php if (!$show_form && !$generated_client): ?>
            <a href="dns.php?novo=1" class="btn-primary">➕ Novo Cliente</a>
        <?php endif; ?>
    </div>
</div>

<?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?>">
        <?php echo $message_type === 'success' ? $message : htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<?php if ($generated_client): ?>
    <?php
        $client_id = (int)($generated_client['id'] ?? 0);
        $card_ok = !empty($card_info['ok']);
        $card_preview_url = 'client_card.php?id=' . $client_id . '&v=' . time();
        $card_download_url = 'client_card.php?id=' . $client_id . '&download=1';
    ?>
    <div class="code-result">
        <h2 style="color:#fff; margin-bottom:8px;">🎉 Cliente ativado!</h2>
        <p style="color:#999; margin-bottom:0;">Card de recarga gerado com o código do cliente:</p>
        <div style="text-align:center;">
            <span class="plan-badge">Plano: <?php echo htmlspecialchars($generated_client['card_plan_label'] ?? card_plan_label($generated_client['card_plan'] ?? 'mensal')); ?></span>
        </div>

        <?php if ($card_ok): ?>
            <div class="card-preview-wrap">
                <img
                    src="<?php echo htmlspecialchars($card_preview_url); ?>"
                    alt="Card de recarga <?php echo htmlspecialchars($generated_code); ?>"
                    class="card-preview">
            </div>
        <?php else: ?>
            <div class="card-warning">
                ⚠️ Não foi possível gerar o card automaticamente:
                <?php echo htmlspecialchars($card_info['message'] ?? 'Erro desconhecido'); ?>
            </div>
        <?php endif; ?>

        <span id="activationCode" style="display:none;"><?php echo htmlspecialchars($generated_code); ?></span>
        <p style="color:#ccc; font-size:14px; text-align:center; margin-top:16px;">
            <strong><?php echo htmlspecialchars($generated_client['name'] ?? ''); ?></strong><br>
            Servidor: <?php echo htmlspecialchars($generated_client['server_url'] ?? ''); ?><br>
            Usuário: <?php echo htmlspecialchars($generated_client['username'] ?? ''); ?>
        </p>
        <div style="display:flex; gap:10px; justify-content:center; flex-wrap:wrap; margin-top:20px;">
            <?php if ($card_ok): ?>
                <a href="<?php echo htmlspecialchars($card_download_url); ?>" class="btn-primary">⬇️ Baixar card PNG</a>
            <?php endif; ?>
            <button type="button" class="btn-primary" onclick="copyCode()">📋 Copiar código</button>
            <a href="dns.php?novo=1" class="btn-secondary">➕ Novo Cliente</a>
            <a href="list_dns.php" class="btn-secondary">📋 Ver todos</a>
        </div>
    </div>
<?php elseif ($show_form): ?>
    <div class="form-container">
        <h2 style="color:#fff; margin-bottom:20px; font-size:18px;">➕ Novo Cliente</h2>
        <form method="POST">
            <div class="form-group">
                <label for="name">🏷️ Nome do cliente (opcional)</label>
                <input type="text" id="name" name="name" placeholder="Ex: João Silva">
            </div>

            <div class="form-group">
                <label for="m3u_url">📺 URL da lista M3U *</label>
                <textarea id="m3u_url" name="m3u_url" placeholder="http://servidor:8080/get.php?username=USUARIO&password=SENHA&type=m3u_plus" required></textarea>
            </div>

            <div class="form-group">
                <label>🎴 Plano do card *</label>
                <div class="plan-selector">
                    <?php foreach (card_plan_options() as $planKey => $planInfo): ?>
                        <label class="plan-option">
                            <input
                                type="radio"
                                name="card_plan"
                                value="<?php echo htmlspecialchars($planKey); ?>"
                                <?php echo $planKey === 'mensal' ? 'checked' : ''; ?>
                                required>
                            <span class="plan-box">
                                <strong><?php echo htmlspecialchars($planInfo['label']); ?></strong>
                                <small><?php echo htmlspecialchars($planInfo['file']); ?></small>
                            </span>
                        </label>
                    <?php endforeach; ?>
                </div>
            </div>

            <div style="display:flex; gap:10px; flex-wrap:wrap;">
                <button type="submit" class="btn-primary">🔑 Gerar código e ativar</button>
                <a href="dns.php" class="btn-secondary">Cancelar</a>
            </div>
        </form>

        <div class="info-box">
            <h3>ℹ️ Como funciona</h3>
            <ul>
                <li>Cole a URL completa da lista M3U do cliente</li>
                <li>Escolha o plano do card: <strong>Mensal</strong>, <strong>Semestral</strong> ou <strong>Anual</strong></li>
                <li>O sistema extrai servidor, usuário e senha automaticamente</li>
                <li>Um código único de 12 dígitos é gerado no formato <strong>XXXX-XXXX-XXXX</strong></li>
                <li>O cliente usa esse código na tela de login do aplicativo</li>
            </ul>
        </div>
    </div>
<?php else: ?>
    <div class="empty-state">
        <h2>Nenhum cliente sendo cadastrado</h2>
        <p>Clique em "Novo Cliente" para colar a lista M3U e gerar o código de ativação.</p>
        <a href="dns.php?novo=1" class="btn-primary">➕ Novo Cliente</a>
    </div>
<?php endif; ?>

<script>
function copyCode() {
    const el = document.getElementById('activationCode');
    if (!el) return;
    const text = el.textContent.trim();
    navigator.clipboard.writeText(text).then(function() {
        alert('Código copiado: ' + text);
    }).catch(function() {
        prompt('Copie o código:', text);
    });
}
</script>

</main>
</body>
</html>
