<?php
ini_set("display_errors", 0);
ini_set("display_startup_errors", 0);
error_reporting(0);

$db = new SQLite3("./api/.ansdb.db");
require_once __DIR__ . '/includes/app_connection_helper.php';
$db->exec("CREATE TABLE IF NOT EXISTS ibo(id INTEGER PRIMARY KEY NOT NULL, mac_address VARCHAR(100), key VARCHAR(100), username VARCHAR(100), password VARCHAR(100), expire_date VARCHAR(100), dns VARCHAR(100), epg_url VARCHAR(100), title VARCHAR(100), url VARCHAR(100), type VARCHAR(100))");
@$db->exec("ALTER TABLE ibo ADD COLUMN support_contact VARCHAR(100)");

function normalize_mac($mac) {
    $clean = strtoupper(preg_replace('/[^A-Fa-f0-9]/', '', $mac));
    return implode(':', str_split(substr($clean, 0, 12), 2));
}

function parse_playlist_input($input) {
    $input = trim($input);
    if ($input === '') {
        return [null, 'Informe a linha Xtream Codes ou a URL M3U.'];
    }

    if (preg_match('~https?://[^\s]+~i', $input, $m)) {
        $input = $m[0];
    }

    $parts = parse_url($input);
    parse_str($parts['query'] ?? '', $query);

    $host = ($parts['scheme'] ?? 'http') . '://' . ($parts['host'] ?? '');
    if (!empty($parts['port'])) {
        $host .= ':' . $parts['port'];
    }

    $username = trim($query['username'] ?? '');
    $password = trim($query['password'] ?? '');

    if ($host === 'http://' || $host === 'https://' || $username === '' || $password === '') {
        return [null, 'Não foi possível extrair DNS, usuário e senha da linha informada.'];
    }

    return [[
        'dns' => rtrim($host, '/'),
        'username' => $username,
        'password' => $password,
        'url' => rtrim($host, '/') . '/get.php?username=' . rawurlencode($username) . '&password=' . rawurlencode($password) . '&type=m3u_plus&output=ts'
    ], null];
}

$error = '';
if (isset($_POST['submit'])) {
    $mac = normalize_mac($_POST['mac_address'] ?? '');
    $title = trim($_POST['title'] ?? '');
    $expire = trim($_POST['expire_date'] ?? '');
    $playlistInput = trim($_POST['playlist_input'] ?? '');
    $supportContact = trim($_POST['support_contact'] ?? '');

    [$parsed, $parseError] = parse_playlist_input($playlistInput);
    $dateTs = strtotime($expire);
    $expireDate = $dateTs ? date('Y-m-d', $dateTs) : '';

    if ($mac === '' || strlen(str_replace(':', '', $mac)) !== 12) {
        $error = 'Informe um ID do dispositivo válido.';
    } elseif ($title === '') {
        $error = 'Informe o nome do cliente.';
    } elseif ($expireDate === '') {
        $error = 'Informe uma data de expiração válida.';
    } elseif ($parseError) {
        $error = $parseError;
    } else {
        $stmt = $db->prepare('INSERT INTO ibo (mac_address, key, username, password, expire_date, dns, epg_url, title, url, type, support_contact) VALUES (:mac, :key, :username, :password, :expire, :dns, :epg, :title, :url, :type, :support_contact)');
        $stmt->bindValue(':mac', $mac, SQLITE3_TEXT);
        $stmt->bindValue(':key', app_connection_get_app_key($db), SQLITE3_TEXT);
        $stmt->bindValue(':username', $parsed['username'], SQLITE3_TEXT);
        $stmt->bindValue(':password', $parsed['password'], SQLITE3_TEXT);
        $stmt->bindValue(':expire', $expireDate, SQLITE3_TEXT);
        $stmt->bindValue(':dns', $parsed['dns'], SQLITE3_TEXT);
        $stmt->bindValue(':epg', '', SQLITE3_TEXT);
        $stmt->bindValue(':title', $title, SQLITE3_TEXT);
        $stmt->bindValue(':url', $parsed['url'], SQLITE3_TEXT);
        $stmt->bindValue(':type', '0', SQLITE3_TEXT);
        $stmt->bindValue(':support_contact', $supportContact, SQLITE3_TEXT);
        $stmt->execute();
        header('Location: users.php?tab=gerenciar');
        exit;
    }
}

include 'includes/header.php';
?>
<style>
html { scrollbar-width: thin; scrollbar-color: #00a8e1 #1a2a33; }
/* Chrome, Edge e Safari */
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: #1a2a33; border-radius: 10px; }
::-webkit-scrollbar-thumb { background: #00a8e1; border-radius: 10px; }
::-webkit-scrollbar-thumb:hover { background: #0080b3; }
</style>
<div class="container-fluid">
    <div class="page-top-card mb-4">
        <h2 class="mb-2"><span class="icon-bullet"><i class="fas fa-plus-circle"></i></span>Criar novo acesso</h2>
        <p class="mb-0 text-muted"><i class="fas fa-wand-magic-sparkles mr-2"></i>Preencha o tutorial passo a passo. O painel extrai os dados automaticamente da linha informada.</p>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-danger"><i class="fas fa-triangle-exclamation mr-2"></i><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <div class="card shadow mb-4">
        <div class="card-header border-0 py-4">
            <h4 class="mb-0"><i class="fas fa-list-check mr-2"></i>Passos para criar o acesso</h4>
        </div>
        <div class="card-body">
            <form method="post">
                <div class="form-group mb-4">
                    <label for="mac_address"><i class="fas fa-mobile-alt mr-2"></i><strong>Passo 1 — Informe o ID do dispositivo</strong></label>
                    <input class="form-control" id="mac_address" name="mac_address" placeholder="Ex.: 00:11:22:33:44:55" type="text" maxlength="17" required value="<?php echo htmlspecialchars($_POST['mac_address'] ?? ''); ?>">
                </div>

                <div class="form-group mb-4">
                    <label for="title"><i class="fas fa-user mr-2"></i><strong>Passo 2 — Digite o nome do cliente</strong></label>
                    <input type="text" class="form-control" name="title" id="title" placeholder="Ex.: Cliente João" required value="<?php echo htmlspecialchars($_POST['title'] ?? ''); ?>">
                </div>

                <div class="form-group mb-4">
                    <label for="expire_date"><i class="fas fa-calendar-alt mr-2"></i><strong>Passo 3 — Insira a data de expiração</strong></label>
                    <input type="text" class="form-control" name="expire_date" id="datetimepicker" placeholder="YYYY-MM-DD" required value="<?php echo htmlspecialchars($_POST['expire_date'] ?? ''); ?>">
                </div>

                <div class="form-group mb-4">
                    <label for="support_contact"><i class="fab fa-whatsapp mr-2"></i><strong>Passo 4 — Contato Suporte Vendedor</strong></label>
                    <input type="text" class="form-control" name="support_contact" id="support_contact" placeholder="Ex.: 5591999999999 ou +55 (91) 99999-9999" value="<?php echo htmlspecialchars($_POST['support_contact'] ?? ''); ?>">
                    <small class="form-text text-muted"><i class="fas fa-circle-info mr-1"></i>Esse número será usado no QR da splash para abrir o WhatsApp do vendedor responsável por este cadastro.</small>
                </div>

                <div class="form-group mb-4">
                    <label for="playlist_input"><i class="fas fa-link mr-2"></i><strong>Passo 5 — Insira a lista M3U ou linha Xtream Codes</strong></label>
                    <textarea class="form-control" name="playlist_input" id="playlist_input" rows="5" placeholder="Cole aqui a URL M3U ou a linha com username e password" required><?php echo htmlspecialchars($_POST['playlist_input'] ?? ''); ?></textarea>
                    <small class="form-text text-muted"><i class="fas fa-circle-info mr-1"></i>O sistema usa apenas Xtream Codes. Ao colar a linha, ele extrai DNS, usuário e senha automaticamente.</small>
                </div>

                <div class="d-flex flex-wrap" style="gap:10px;">
                    <button class="btn btn-success" name="submit" type="submit"><i class="fas fa-check-circle mr-2"></i>Criar acesso</button>
                    <a href="users.php?tab=gerenciar" class="btn btn-secondary"><i class="fas fa-arrow-left mr-2"></i>Voltar para gerenciar</a>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
<script>
$('#datetimepicker').datetimepicker({
    timepicker:false,
    format:'Y-m-d'
});

document.getElementById('mac_address').addEventListener('input', function() {
    var mac = this.value.replace(/[^a-fA-F0-9]/g, '').toUpperCase().slice(0, 12);
    var match = mac.match(/.{1,2}/g);
    this.value = match ? match.join(':') : mac;
});
</script>
</body>
</html>