<?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');
$trial_settings = get_trial_settings();
$default_m3u_url = str_in((string)($trial_settings['m3u_url'] ?? ''));
$form_name = '';
$form_expires_at = '';
$form_expires_source = 'manual';
$is_reseller = user_is_reseller($user);
$can_create_client = user_can_create_client($user);
$usage = user_client_usage_summary($user);
$form_m3u_url = $is_reseller ? '' : $default_m3u_url;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = str_in($_POST['name'] ?? '');
    $m3u_url = str_in($_POST['m3u_url'] ?? '');
    $expires_source = str_in($_POST['expires_source'] ?? 'manual');
    $expires_at = str_in($_POST['expires_at'] ?? '');
    $form_name = $name;
    $form_m3u_url = $m3u_url;
    $form_expires_source = normalize_client_expires_source($expires_source);
    $form_expires_at = $expires_at;

    if (!$can_create_client) {
        $result = ['ok' => false, 'message' => 'Seu painel nao pode criar novos clientes agora.'];
    } else {
        $result = add_client($name, $m3u_url, $expires_at, $is_reseller ? (int)$user_id : null, $form_expires_source);
    }

    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! Codigo 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;
    }

    .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, .form-group select {
        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 select option {
        background-color: #111 !important;
        color: #fff !important;
    }

    .form-group select option:checked {
        background-color: #6d28d9 !important;
        color: #fff !important;
    }

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

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

    .form-group input:disabled {
        opacity: 0.45;
        cursor: not-allowed;
    }

    .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%, 150px);
        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-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;
    }
</style>

<div class="page-header">
    <div>
        <h1>Clientes</h1>
    </div>
    <div class="header-actions">
        <a href="list_dns.php" class="btn-secondary">Ver clientes</a>
        <?php if (!$show_form && !$generated_client && $can_create_client): ?>
            <a href="dns.php?novo=1" class="btn-primary">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">



        <?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">
                Nao foi possivel 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>

        <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</a>
                <button type="button"
                        class="btn-primary"
                        id="shareGeneratedCard"
                        data-card-url="<?php echo htmlspecialchars($card_download_url . '&share=1', ENT_QUOTES, 'UTF-8'); ?>"
                        data-card-code="<?php echo htmlspecialchars($generated_code, ENT_QUOTES, 'UTF-8'); ?>"
                        data-card-expiry="<?php echo htmlspecialchars($generated_client['expires_label'] ?? '--/--/----', ENT_QUOTES, 'UTF-8'); ?>"
                        onclick="shareGeneratedCard()">
                    Compartilhar
                </button>
            <?php endif; ?>
            <button type="button" class="btn-primary" onclick="copyCode()">Copiar codigo</button>
            <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;">Adicionar:</h2>
        <?php if ($is_reseller): ?>
            <div class="alert <?php echo $can_create_client ? 'alert-success' : 'alert-error'; ?>">
                Limite contratado: <?php echo (int)$usage['contracted']; ?> |
                usados: <?php echo (int)$usage['used']; ?> |
                disponiveis: <?php echo (int)$usage['remaining']; ?> |
                vencimento: <?php echo htmlspecialchars(user_panel_expiry_label($user)); ?>
            </div>
        <?php endif; ?>

        <form method="POST">
            <div class="form-group">
                <label for="name">Nome do cliente;</label>
                <input type="text" id="name" name="name" placeholder="Ex: Joao Silva" value="<?php echo htmlspecialchars($form_name, ENT_QUOTES, 'UTF-8'); ?>">
            </div>

            <div class="form-group">
                <label for="m3u_url">URL M3U Copleta;</label>
                <textarea id="m3u_url" name="m3u_url" placeholder="http://servidor:8080/get.php?username=USUARIO&password=SENHA&type=m3u_plus" required><?php echo htmlspecialchars($form_m3u_url, ENT_QUOTES, 'UTF-8'); ?></textarea>
            </div>

            <div class="form-group">
                <label for="expires_source">Vencimento;</label>
                <select name="expires_source" id="expires_source">
                    <option value="xtream" <?php echo $form_expires_source === 'xtream' ? 'selected' : ''; ?>>Xtream</option>
                    <option value="manual" <?php echo $form_expires_source === 'manual' ? 'selected' : ''; ?>>Manual</option>
                </select>
            </div>

            <div class="form-group">
                <label for="expires_at">Data manual;</label>
                <input type="date" id="expires_at" name="expires_at" value="<?php echo htmlspecialchars($form_expires_at, ENT_QUOTES, 'UTF-8'); ?>">
            </div>

            <div style="display:flex; gap:10px; flex-wrap:wrap;">
                <button type="submit" class="btn-primary" <?php echo $can_create_client ? '' : 'disabled'; ?>>Gerar Gift Card</button>
                <a href="dns.php" class="btn-secondary">Cancelar</a>
            </div>
        </form>

        <div class="info-box">
            <h3>Instruções:</h3>
            <ul>
                <li>Cole a URL completa da lista M3U;</li>
                <li>Escolha Vencimento do Gift Card;</li>

                <li>Envie o código ou Compartilhe o Gift Card com seu Cliente;</strong></li>
                <li>Cliente usa cód de 12 digitos para Logar no App!</li>
            </ul>
        </div>
    </div>
<?php else: ?>
    <div class="empty-state">
        <p><?php echo $can_create_client ? 'Clique abaixo para gerar o codigo de ativacao.' : 'Seu painel nao pode gerar novos clientes agora.'; ?></p>
        <?php if ($can_create_client): ?>
            <a href="dns.php?novo=1" class="btn-primary">Novo Cliente</a>
        <?php endif; ?>
    </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('Codigo copiado: ' + text);
    }).catch(function() {
        prompt('Copie o codigo:', text);
    });
}

function syncExpiresSourceFields() {
    const source = document.getElementById('expires_source');
    const dateInput = document.getElementById('expires_at');
    if (!source || !dateInput) return;

    const manual = source.value === 'manual';
    dateInput.disabled = !manual;
    dateInput.required = manual;
}

document.addEventListener('DOMContentLoaded', function() {
    const source = document.getElementById('expires_source');
    if (source) {
        source.addEventListener('change', syncExpiresSourceFields);
        syncExpiresSourceFields();
    }
});

async function shareGeneratedCard() {
    const btn = document.getElementById('shareGeneratedCard');
    if (!btn) return;

    const url = btn.getAttribute('data-card-url');
    const code = btn.getAttribute('data-card-code') || '';
    const expiry = btn.getAttribute('data-card-expiry') || '--/--/----';

    if (!navigator.share || !navigator.canShare || !url) {
        alert('Compartilhamento nativo indisponivel neste navegador. Use o botao de baixar card.');
        return;
    }

    try {
        btn.disabled = true;
        btn.textContent = 'Preparando...';

        const response = await fetch(url, { credentials: 'same-origin' });
        if (!response.ok) {
            throw new Error('Falha ao gerar a imagem do card.');
        }

        const blob = await response.blob();
        const file = new File([blob], 'card-tvexpress-' + code.replace(/\W+/g, '-') + '.png', { type: 'image/png' });
        const payload = {
            title: 'Card TVExpress',
            text: 'Codigo: ' + code + ' | Vencimento: ' + expiry,
            files: [file]
        };

        if (!navigator.canShare(payload)) {
            throw new Error('Este navegador nao suporta compartilhar imagem diretamente.');
        }

        await navigator.share(payload);
    } catch (error) {
        alert(error && error.message ? error.message : 'Nao foi possivel compartilhar o card.');
    } finally {
        btn.disabled = false;
        btn.textContent = 'Compartilhar';
    }
}
</script>

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