<?php
require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/whatsapp_helper.php';
require_once dirname(__DIR__) . '/includes/revenda_schema.php';
require_once dirname(__DIR__) . '/api/_auth_common.php';
require_once dirname(__DIR__) . '/api/_multiserver.php';

revenda_ensure_schema($db);
wa_ensure_schema($db);
auth_ensure_schema($db);

$activationCode = '';
$createError = '';
$revId = $isRev ? (int)($_SESSION['revendedor_id'] ?? ($user['id'] ?? 0)) : 0;

if ($isRev && $revId <= 0) {
    session_destroy();
    header('Location: index.php');
    exit;
}

$limitInfo = $isRev
    ? revenda_limit_info($db, $revId)
    : ['unlimited' => true, 'used' => 0, 'limit' => 0, 'remaining' => null];

$dnsOptions = [];
try {
    if ($isRev) {
        $stDns = $db->prepare("SELECT nome, url FROM revendedor_dns WHERE revendedor_id=? ORDER BY nome ASC");
        $stDns->execute([$revId]);
        $dnsOptions = $stDns->fetchAll(PDO::FETCH_ASSOC) ?: [];
    } else {
        $stDns = $db->query("SELECT nome, url FROM dns ORDER BY nome ASC");
        $dnsOptions = $stDns ? ($stDns->fetchAll(PDO::FETCH_ASSOC) ?: []) : [];
    }
} catch (Throwable $e) {}

function usersCreateNormalizeMac(string $mac): string {
    $mac = preg_replace('/[^A-Fa-f0-9]/', '', trim($mac));
    $mac = strtoupper(substr((string)$mac, 0, 12));
    if (strlen($mac) !== 12) return '';
    return implode(':', str_split($mac, 2));
}

if (isset($_POST["submit"])) {
    $mac = usersCreateNormalizeMac((string)($_POST["mac"] ?? ''));
    $username = trim((string)($_POST["username"] ?? ''));
    $password = trim((string)($_POST["password"] ?? ''));
    $dns = trim((string)($_POST["dns"] ?? ''));
    $status = trim((string)($_POST["status"] ?? ''));
    $vencimentoData = trim((string)($_POST["vencimento"] ?? ''));
    $nomeCliente = trim((string)($_POST["nome_cliente"] ?? ''));
    $whatsapp = trim((string)($_POST["whatsapp"] ?? ''));
    $tipoRegistro = trim((string)($_POST["tipo_registro"] ?? "cliente"));
    $isTeste = ($tipoRegistro === "teste");
    $loginMode = trim((string)($_POST['login_mode'] ?? 'normal'));

    if (!in_array($loginMode, ['normal', 'activation_code'], true)) {
        $loginMode = 'normal';
    }

    if ($mac === '' || $username === '' || $password === '' || $dns === '') {
        $createError = 'Preencha MAC, DNS, usuário e senha.';
    } else {
        $check = $db->prepare("SELECT * FROM usuarios WHERE mac = ? LIMIT 1");
        $check->execute([$mac]);

        $existing = $check->fetch(PDO::FETCH_ASSOC);
        $activationCode = $loginMode === 'activation_code' ? auth_generate_activation_code($db) : '';
        $vencimento = 0;
        if ($vencimentoData !== '') {
            $tmp = strtotime($vencimentoData . " 23:59:59");
            $vencimento = $tmp !== false ? (int)$tmp : 0;
        }
        $agoraWhatsapp = time();

        if ($existing && $isRev) {
            $existingOwner = (int)($existing['usuario_id'] ?? 0);
            $existingStatus = mb_strtolower(trim((string)($existing['status'] ?? '')), 'UTF-8');
            $existingHasCreds = trim((string)($existing['dns'] ?? '')) !== '' || trim((string)($existing['username'] ?? '')) !== '' || trim((string)($existing['password'] ?? '')) !== '';
            $canClaimPending = ($existingOwner <= 0) && (!$existingHasCreds || in_array($existingStatus, ['aguardando','pendente','pending','waiting'], true));
            $sameOwner = ($existingOwner === $revId);

            if (!$sameOwner && !$canClaimPending) {
                $createError = 'MAC já cadastrado e não está aguardando liberação para esta revenda.';
            } elseif (!$sameOwner && !revenda_can_add_mac($db, $revId, 1)) {
                $createError = 'Limite de MACs da revenda atingido. Peça ao admin para aumentar o limite.';
            } else {
                try {
                    $upd = $db->prepare("UPDATE usuarios SET usuario_id=?, dns=?, username=?, password=?, status=?, vencimento=?, nome_cliente=?, whatsapp=?, teste=?, teste_criado_at=?, whatsapp_trial_started_at=?, whatsapp_activated_at=?, whatsapp_account_created_at=?, login_mode=?, activation_code=? WHERE mac=?");
                    $upd->execute([$revId, $dns, $username, $password, $status ?: 'ativo', $vencimento, $nomeCliente, $whatsapp, $isTeste ? 1 : null, $isTeste ? $agoraWhatsapp : (int)($existing['teste_criado_at'] ?? 0), $isTeste ? $agoraWhatsapp : (int)($existing['whatsapp_trial_started_at'] ?? 0), $isTeste ? 0 : $agoraWhatsapp, $agoraWhatsapp, $loginMode, $activationCode, $mac]);
                    $link = $db->prepare("INSERT OR IGNORE INTO revendedor_clientes (mac, revendedor_id) VALUES (?, ?)");
                    $link->execute([$mac, $revId]);
                    try {
                        ms_save_servers($db, $mac, $revId, [[
                            'name' => 'Servidor principal',
                            'dns' => $dns,
                            'username' => $username,
                            'password' => $password,
                        ]]);
                    } catch (Throwable $syncError) {
                        error_log('[users_create] Falha ao sincronizar servidor do MAC ' . $mac . ': ' . $syncError->getMessage());
                    }
                    header("Location: users.php?r=vinculado");
                    exit;
                } catch (Throwable $e) {
                    $createError = 'MAC já cadastrado, mas não foi possível vincular/atualizar para a revenda.';
                }
            }
        } elseif ($existing) {
            $createError = 'MAC já cadastrado.';
        } elseif ($isRev && !revenda_can_add_mac($db, $revId, 1)) {
            $createError = 'Limite de MACs da revenda atingido. Peça ao admin para aumentar o limite.';
        } else {
            $ownerId = $isRev ? $revId : 0;

            $st = $db->prepare("
                INSERT INTO usuarios
                (mac, dns, username, password, status, vencimento, nome_cliente, whatsapp, teste, teste_criado_at, whatsapp_trial_started_at, whatsapp_activated_at, whatsapp_account_created_at, usuario_id, login_mode, activation_code)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");

            $st->execute([
                $mac,
                $dns,
                $username,
                $password,
                $status ?: "ativo",
                $vencimento,
                $nomeCliente,
                $whatsapp,
                $isTeste ? 1 : null,
                $isTeste ? $agoraWhatsapp : 0,
                $isTeste ? $agoraWhatsapp : 0,
                $isTeste ? 0 : $agoraWhatsapp,
                $agoraWhatsapp,
                $ownerId,
                $loginMode,
                $activationCode
            ]);

            if ($isRev) {
                $link = $db->prepare("INSERT OR IGNORE INTO revendedor_clientes (mac, revendedor_id) VALUES (?, ?)");
                $link->execute([$mac, $revId]);
            }

            try {
                ms_save_servers($db, $mac, $ownerId, [[
                    'name' => 'Servidor principal',
                    'dns' => $dns,
                    'username' => $username,
                    'password' => $password,
                ]]);
            } catch (Throwable $syncError) {
                error_log('[users_create] Falha ao sincronizar servidor do MAC ' . $mac . ': ' . $syncError->getMessage());
            }

            $createdUser = [
                'mac' => $mac,
                'dns' => $dns,
                'username' => $username,
                'password' => $password,
                'status' => $status ?: 'ativo',
                'vencimento' => $vencimento,
                'nome_cliente' => $nomeCliente,
                'whatsapp' => $whatsapp,
                'teste' => $isTeste ? 1 : null,
                'usuario_id' => $ownerId,
                'login_mode' => $loginMode,
                'activation_code' => $activationCode,
            ];

            if ($isTeste) {
                wa_send_template_to_user($db, $createdUser, 'teste_criado');
            }

            header("Location: users.php?r=adicionado");
            exit;
        }
    }
    $limitInfo = $isRev ? revenda_limit_info($db, $revId) : $limitInfo;
}

require_once __DIR__ . '/../includes/header.php';
?>
<div class="dns-wrap">
    <div class="card radius-10 dns-card">
        <div class="card-header bg-transparent dns-header">
            <div class="dns-title">
                <div class="ic"><i class="bi bi-person-plus-fill"></i></div>
                <div>
                    <h5>Novo Usuário</h5>
                    <span>Cadastre MAC, DNS, usuário, senha, WhatsApp e vencimento do cliente</span>
                </div>
            </div>

            <div class="dns-actions">
                <span class="badge-soft"><i class="bi bi-shield-check"></i> Cadastro</span>
            </div>
        </div>

        <div class="card-body">
            <?php if ($isRev): ?>
                <div class="alert alert-info d-flex align-items-center gap-2">
                    <i class="bi bi-hdd-network-fill"></i>
                    <div>
                        Seus MACs: <strong><?= (int)$limitInfo['used'] ?></strong> /
                        <strong><?= !empty($limitInfo['unlimited']) ? 'Ilimitado' : (int)$limitInfo['limit'] ?></strong>
                        <?php if (empty($limitInfo['unlimited'])): ?>
                            · Restante: <strong><?= (int)$limitInfo['remaining'] ?></strong>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>

            <?php if (!empty($createError)): ?>
                <div class="alert alert-danger d-flex align-items-center gap-2">
                    <i class="bi bi-x-circle-fill"></i>
                    <div><?= htmlspecialchars($createError, ENT_QUOTES, 'UTF-8') ?></div>
                </div>
            <?php endif; ?>

            <?php if (!empty($activationCode)): ?>
                <div class="alert alert-info d-flex align-items-center gap-2">
                    <i class="bi bi-key-fill"></i>
                    <div>Código de ativação gerado: <strong><?= htmlspecialchars($activationCode, ENT_QUOTES, 'UTF-8') ?></strong></div>
                </div>
            <?php endif; ?>

            <form method="post" class="row g-3">
                <div class="col-lg-4 col-md-6 col-12">
                    <label class="form-label fw-900">MAC</label>
                    <input class="form-control input-radius" name="mac" placeholder="00:11:22:33:44:55" maxlength="17" required>
                </div>

                <div class="col-lg-4 col-md-6 col-12">
                    <label class="form-label fw-900">Usuário</label>
                    <input class="form-control input-radius" name="username" required>
                </div>

                <div class="col-lg-4 col-md-6 col-12">
                    <label class="form-label fw-900">Senha</label>
                    <input class="form-control input-radius" name="password" required>
                </div>

                <div class="col-lg-6 col-md-6 col-12">
                    <label class="form-label fw-900">DNS</label>
                    <input class="form-control input-radius" name="dns" list="dnsOptionsList" placeholder="http://servidor:porta" required>
                    <datalist id="dnsOptionsList">
                        <?php foreach ($dnsOptions as $dnsOpt): ?>
                            <option value="<?= htmlspecialchars((string)$dnsOpt['url'], ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars((string)$dnsOpt['nome'], ENT_QUOTES, 'UTF-8') ?></option>
                        <?php endforeach; ?>
                    </datalist>
                    <?php if ($isRev): ?>
                        <small class="text-muted">Você pode cadastrar seus DNS em <a href="dns.php">dns.php</a>.</small>
                    <?php endif; ?>
                </div>

                <div class="col-lg-6 col-md-6 col-12">
                    <label class="form-label fw-900">Nome do Cliente</label>
                    <input class="form-control input-radius" name="nome_cliente">
                </div>

                <div class="col-lg-4 col-md-6 col-12">
                    <label class="form-label fw-900">WhatsApp</label>
                    <input class="form-control input-radius" name="whatsapp" placeholder="5511999999999">
                </div>

                <div class="col-lg-4 col-md-6 col-12">
                    <label class="form-label fw-900">Login do App</label>
                    <select name="login_mode" class="form-select input-radius" id="login_mode_select">
                        <option value="normal">Login normal</option>
                        <option value="activation_code">Código de ativação</option>
                    </select>
                </div>

                <div class="col-lg-4 col-md-6 col-12">
                    <label class="form-label fw-900">Status</label>
                    <select name="status" class="form-select input-radius">
                        <option value="ativo">Ativo</option>
                        <option value="inativo">Inativo</option>
                    </select>
                </div>

                <div class="col-lg-6 col-md-6 col-12">
                    <label class="form-label fw-900">Tipo</label>
                    <select name="tipo_registro" class="form-select input-radius">
                        <option value="cliente">Cliente</option>
                        <option value="teste">Teste</option>
                    </select>
                </div>

                <div class="col-lg-6 col-md-6 col-12">
                    <label class="form-label fw-900">Vencimento</label>
                    <input type="date" name="vencimento" class="form-control input-radius">
                </div>

                <div class="col-12">
                    <div class="info-box">
                        <strong>Login por código:</strong>
                        ao escolher código de ativação, o painel gera automaticamente um código numérico de 4 dígitos.
                    </div>
                </div>

                <div class="col-12">
                    <div class="form-actions">
                        <a href="users.php" class="btn btn-secondary back-btn">
                            <i class="bi bi-arrow-left"></i> Voltar
                        </a>

                        <button class="btn btn-success save-btn" name="submit">
                            <i class="bi bi-save2"></i> Salvar usuário
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>