<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

include '../includes/header3.php';
require_once '../includes/DNSDatabase.php';
require_once 'sync_mac_consistency.php';

$reseller_name = null;
if (isset($_SESSION['reseller_name'])) {
    $reseller_name = $_SESSION['reseller_name'];
} elseif (isset($_SESSION['reseller'])) {
    $reseller_name = $_SESSION['reseller'];
} elseif (isset($_SESSION['username'])) {
    $reseller_name = $_SESSION['username'];
} elseif (isset($_SESSION['user'])) {
    $reseller_name = $_SESSION['user'];
} else {
    foreach ($_SESSION as $key => $value) {
        if (!empty($value) && (stripos($key, 'reseller') !== false || stripos($key, 'sub') !== false || stripos($key, 'user') !== false)) {
            $reseller_name = $value;
            break;
        }
    }
}

if (empty($reseller_name)) {
    die("Erro: Sessão de sub revenda não encontrada. Faça login novamente.");
}

$db = new SQLite3('../a/.eggziedb.db');

$db->exec('CREATE TABLE IF NOT EXISTS ibo(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    mac_address VARCHAR(100),
    username VARCHAR(100),
    password VARCHAR(100),
    expire_date VARCHAR(100),
    url VARCHAR(100),
    title VARCHAR(100),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    seller VARCHAR(100),
    extra TEXT,
    is_test INTEGER DEFAULT 0
)');

$cols = $db->query("PRAGMA table_info(ibo)");
$existing = [];
while ($c = $cols->fetchArray(SQLITE3_ASSOC)) {
    $existing[] = $c['name'];
}
if (!in_array('is_test', $existing)) $db->exec("ALTER TABLE ibo ADD COLUMN is_test INTEGER DEFAULT 0");

$dnsDB = DNSDatabase::getInstance();

$result_macs = $db->query("SELECT macs FROM sub_revenda WHERE usuario = '$reseller_name'");
$row_macs = $result_macs->fetchArray(SQLITE3_ASSOC);
$macs_disponiveis = $row_macs ? intval($row_macs['macs']) : 0;

if (isset($_POST['submit'])) {
    $usuario = trim($_POST['username']);
    $mac_address = strtoupper(trim($_POST['mac_address']));
    $password = trim($_POST['password']);
    $title = trim($_POST['title']);
    $dns_url = trim($_POST['dns']);
    $descricao = trim($_POST['Descricao']);
    $is_test_input = isset($_POST['is_test']) ? 1 : 0;

    if (empty($usuario) || empty($mac_address) || empty($password) || empty($title) || empty($dns_url) || empty($descricao)) {
        echo "<script>alert('Preencha todos os campos!'); window.history.back();</script>";
        exit();
    }

    if (!preg_match('/^([0-9A-F]{2}:){7}[0-9A-F]{2}$/', $mac_address)) {
        echo "<script>alert('Formato de MAC inválido! Use 00:11:22:33:44:55:66:77'); window.history.back();</script>";
        exit();
    }

    // Verifica se o MAC já existe para este sub revendedor
    $check_mac = $db->query("SELECT id, extra, expire_date, is_test FROM ibo 
                             WHERE mac_address = '$mac_address' AND seller = '$reseller_name' LIMIT 1");
    $existing_mac = $check_mac->fetchArray(SQLITE3_ASSOC);
    
    if ($existing_mac) {
        // Força consistência: usa os dados da primeira playlist
        $descricao = $existing_mac['extra'];
        $expire_date = $existing_mac['expire_date'];
        $is_test = (int)$existing_mac['is_test'];
        if ($is_test_input != $is_test) {
            echo "<script>alert('Este MAC já possui playlists. O tipo (teste/anual) não pode ser alterado. Usando tipo existente.');</script>";
        }
    } else {
        // Novo MAC: usa os valores do formulário e verifica saldo se for anual
        $descricao = trim($_POST['Descricao']);
        $is_test = $is_test_input;
        if ($is_test) {
            $expire_date = date('Y-m-d', strtotime('+10 days'));
        } else {
            $expire_date = date('Y-m-d', strtotime('+1 year'));
            if ($macs_disponiveis <= 0) {
                echo "<script>alert('Você não possui MACs disponíveis para criar usuário anual!'); window.history.back();</script>";
                exit();
            }
        }
    }
    
    // Contagem de playlists para este MAC
    $count_result = $db->query("SELECT COUNT(*) as count FROM ibo WHERE mac_address = '$mac_address' AND seller = '$reseller_name'");
    $count_row = $count_result->fetchArray(SQLITE3_ASSOC);
    $playlist_count = $count_row['count'];
    $already_exists = ($playlist_count > 0);

    if($playlist_count >= 8) {
        echo "<script>alert('Limite de 8 playlists por MAC atingido! Este MAC já possui $playlist_count playlist(s).'); window.location.href='index.php';</script>";
        exit();
    }

    $created_at = date('Y-m-d H:i:s');

    $sql = "INSERT INTO ibo (mac_address, username, password, expire_date, url, title, created_at, seller, extra, is_test) 
            VALUES (
                '" . SQLite3::escapeString($mac_address) . "',
                '" . SQLite3::escapeString($usuario) . "',
                '" . SQLite3::escapeString($password) . "',
                '$expire_date',
                '" . SQLite3::escapeString($dns_url) . "',
                '" . SQLite3::escapeString($title) . "',
                '$created_at',
                '" . SQLite3::escapeString($reseller_name) . "',
                '" . SQLite3::escapeString($descricao) . "',
                $is_test
            )";

    $db->exec('BEGIN IMMEDIATE');
    $result = $db->exec($sql);
    if ($result) {
        $last_id = $db->lastInsertRowID();
        if ($last_id > 0) {
            if ($is_test == 0 && !$already_exists) {
                $nova_quantidade = $macs_disponiveis - 1;
                $db->exec("UPDATE sub_revenda SET macs = $nova_quantidade WHERE usuario = '$reseller_name'");
            }
            // Sincroniza todas as playlists do MAC (garantia de consistência)
            syncMacPlaylists($db, $mac_address, $reseller_name);
            $db->exec('COMMIT');
            echo "<script>alert('Usuário criado com sucesso!'); window.location.href='index.php';</script>";
        } else {
            $db->exec('ROLLBACK');
            echo "<script>alert('Erro: Nenhum ID gerado.'); window.history.back();</script>";
        }
    } else {
        $db->exec('ROLLBACK');
        echo "<script>alert('Erro ao salvar: " . addslashes($db->lastErrorMsg()) . "'); window.history.back();</script>";
    }
    exit();
}
?>
<style>
    .status-card { border-radius: 12px; padding: 12px 16px; margin-bottom: 16px; font-weight: bold; color: white; border-left: 6px solid #0d6efd; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
    .status-annual { background-color: #198754; }
    .status-test { background-color: #fd7e14; }
    .status-expired { background-color: #dc3545; }
    .status-new { background-color: #6c757d; }
    .status-line { margin: 4px 0; }
    .btn-sync { background-color: #ffc107; color: #000; border: none; padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; margin-left: 12px; }
    .btn-sync:hover { background-color: #e0a800; }
    .btn-renew { background-color: #0dcaf0; color: #000; border: none; padding: 6px 12px; border-radius: 20px; font-size: 0.8rem; margin-top: 8px; }
    .btn-renew:hover { background-color: #0bb5d8; }
</style>

<div class="container-fluid">
    <div class="card border-left-primary shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-user-plus"></i> CRIAR USUÁRIO</h6>
        </div>
        <div class="card-body">
            <!-- Seção EXTRAIR LISTA M3U dentro do card -->
            <div class="alert alert-secondary mb-4">
                <form onsubmit="return false;">
                    <div class="form-group">
                        <label class="control-label"><strong>EXTRAIR LISTA M3U</strong></label>
                        <div class="input-group">
                            <input class="form-control" id="m3u_address" placeholder="COLE AQUI SUA LISTA M3U">
                            <div class="input-group-append">
                                <button class="btn btn-success" type="button" onclick="extract(event)"><i class="fa fa-expand"></i> EXTRAIR</button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>

            <form method="post" id="createUserForm">
                <input type="hidden" id="confirmedField" name="confirmed" value="0">

                <div class="form-group">
                    <label><strong>ENDEREÇO MAC</strong> <span class="text-danger">*</span></label>
                    <input class="form-control" id="mac_address" name="mac_address" placeholder="00:11:22:33:44:55:66:77" required>
                    <div id="macStatusContainer" class="mt-3"></div>
                </div>

                <div class="form-group">
                    <label><strong>NOME DO SERVIDOR</strong> <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" name="title" placeholder="Digite o Nome do Servidor" required>
                </div>

                <div class="form-group">
                    <label><strong>DNS</strong> <span class="text-danger">*</span></label>
                    <select class="form-control" name="dns" id="server_url" required>
                        <option value="" disabled selected>Escolher DNS</option>
                        <?php
                        $dns_options = $dnsDB->getAll('sub_revenda', $reseller_name);
                        if ($dns_options) {
                            while ($dns_row = $dns_options->fetchArray(SQLITE3_ASSOC)) {
                                echo "<option value='" . htmlspecialchars($dns_row['dns']) . "'>" . htmlspecialchars($dns_row['nome']) . "</option>";
                            }
                        }
                        ?>
                    </select>
                </div>

                <div class="form-group">
                    <label><strong>NOME DO CLIENTE</strong> <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" name="Descricao" placeholder="Digite o nome do Cliente" required>
                </div>

                <div class="form-group">
                    <label><strong>USUÁRIO</strong> <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" name="username" id="username" placeholder="Digite o USUÁRIO" required>
                </div>

                <div class="form-group">
                    <label><strong>SENHA</strong> <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" name="password" id="password" placeholder="Digite a SENHA" required>
                </div>

                <div class="form-group">
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="is_test" name="is_test" value="1">
                        <label class="custom-control-label" for="is_test"><strong>MAC MODO TESTE</strong> - Expira em 10 dias (não consome MAC)</label>
                    </div>
                    <div id="testInfo" style="display: none;"></div>
                </div>

                <div class="form-group">
                    <button class="btn btn-success" type="submit" name="submit"><i class="fas fa-check"></i> CRIAR USUÁRIO</button>
                    <a href="index.php" class="btn btn-secondary"><i class="fas fa-times"></i> Cancelar</a>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal de confirmação para ativação anual -->
<div class="modal fade" id="confirmAnnualModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="fas fa-exclamation-triangle"></i> Confirmação</h5>
                <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <p><strong>MAC MODO TESTE NÃO SELECIONADO.</strong></p>
                <p>Deseja prosseguir com a <strong>ativação ANUAL</strong> do MAC?<br>
                <span class="text-info">Esta ação consumirá 1 MAC do seu saldo (apenas se for o primeiro registro deste endereço).</span></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Não</button>
                <button type="button" class="btn btn-primary" id="confirmAnnualBtn">Sim</button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

<script>
// Máscara do MAC
document.getElementById('mac_address').addEventListener('input', function(e) {
    var val = e.target.value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();
    if (val.length > 16) val = val.substring(0,16);
    var fmt = "";
    for (var i=0; i<val.length; i++) {
        fmt += val[i];
        if ((i+1)%2===0 && i<val.length-1) fmt += ":";
    }
    e.target.value = fmt;
});

var testCheckbox = document.getElementById("is_test");
var testInfo = document.getElementById("testInfo");
if (testCheckbox) {
    testCheckbox.addEventListener("change", function() {
        if (this.checked) {
            testInfo.style.display = "block";
            testInfo.className = "alert alert-info mt-2";
            testInfo.innerHTML = '<i class="fas fa-info-circle"></i> <strong>Modo TESTE ativado!</strong><br>- Expira em 10 dias<br>- Nenhum MAC consumido';
        } else {
            testInfo.style.display = "none";
        }
    });
}

var form = document.getElementById("createUserForm");
var confirmBtn = document.getElementById("confirmAnnualBtn");
var confirmedField = document.getElementById("confirmedField");

if (form) {
    form.addEventListener("submit", function(event) {
        var isTestChecked = testCheckbox && testCheckbox.checked;
        var confirmed = confirmedField && confirmedField.value === "1";
        if (isTestChecked || confirmed) return true;
        event.preventDefault();
        $('#confirmAnnualModal').modal('show');
        return false;
    });
}
if (confirmBtn) {
    confirmBtn.addEventListener("click", function() {
        if (confirmedField) confirmedField.value = "1";
        $('#confirmAnnualModal').modal('hide');
        form.submit();
    });
}

let currentAbortController = null;
let macTimeout = null;

document.getElementById('mac_address').addEventListener('input', function() {
    if (currentAbortController) currentAbortController.abort();
    const mac = this.value;
    const statusDiv = document.getElementById('macStatusContainer');
    const submitBtn = document.querySelector('button[type="submit"]');
    const isTestCheckbox = document.getElementById('is_test');
    const clienteField = document.querySelector('input[name="Descricao"]');
    
    if (mac.length < 17) {
        statusDiv.innerHTML = '';
        if (submitBtn) submitBtn.disabled = false;
        if (isTestCheckbox) isTestCheckbox.disabled = false;
        return;
    }
    
    clearTimeout(macTimeout);
    macTimeout = setTimeout(() => {
        currentAbortController = new AbortController();
        const signal = currentAbortController.signal;
        
        fetch(`check_mac_status.php?mac=${encodeURIComponent(mac)}`, { signal })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    statusDiv.innerHTML = `<div class="alert alert-danger">${data.error}</div>`;
                    if (submitBtn) submitBtn.disabled = false;
                    if (isTestCheckbox) isTestCheckbox.disabled = false;
                    return;
                }
                
                let html = '';
                let statusClass = '';
                let statusText = '';
                let playlistLine = '';
                
                if (data.status_geral === 'NÃO REGISTRADO - NOVO') {
                    statusClass = 'status-new';
                    statusText = '👉 STATUS DO MAC: NÃO REGISTRADO - NOVO';
                } else if (data.first_status === 'ATIVO ANUAL') {
                    statusClass = 'status-annual';
                    statusText = '👉 STATUS DO MAC: ATIVO (ANUAL)';
                    playlistLine = `<div class="status-line">👉 PLAYLISTS DO MAC: ${data.total}/8</div>`;
                } else if (data.first_status === 'MODO TESTE') {
                    statusClass = 'status-test';
                    statusText = '👉 STATUS DO MAC: MODO TESTE';
                    playlistLine = `<div class="status-line">👉 PLAYLISTS DO MAC: ${data.total}/8</div>`;
                } else if (data.first_status === 'EXPIRADO') {
                    statusClass = 'status-expired';
                    statusText = '👉 STATUS DO MAC: EXPIRADO';
                    playlistLine = `<div class="status-line">👉 PLAYLISTS DO MAC: ${data.total}/8</div>`;
                } else {
                    statusClass = 'status-partial';
                    statusText = `👉 STATUS DO MAC: ${data.status_geral}`;
                    if (data.total > 0) playlistLine = `<div class="status-line">👉 PLAYLISTS DO MAC: ${data.total}/8</div>`;
                }
                
                html += `<div class="status-card ${statusClass}">
                            <div class="status-line">${statusText}</div>
                            ${playlistLine}
                            ${!data.consistent ? `<div class="status-line"><button type="button" class="btn-sync" onclick="fixInconsistency('${mac}')"><i class="fas fa-sync"></i> Sincronizar agora</button></div>` : ''}
                            ${data.is_expired && data.can_renew ? `<div class="status-line"><button type="button" class="btn-renew" onclick="renewMac('${mac}')"><i class="fas fa-sync-alt"></i> Renovar Licença (Anual)</button></div>` : ''}
                        </div>`;
                
                if (data.exists && data.first_cliente) {
                    html += `<div class="small text-muted mt-1">📋 Cliente: ${data.first_cliente} | Validade: ${data.first_validade}</div>`;
                }
                
                statusDiv.innerHTML = html;
                if (submitBtn) {
                    submitBtn.disabled = !data.can_add;
                    if (!data.can_add) submitBtn.title = "Limite de 8 playlists por MAC atingido";
                    else submitBtn.title = "";
                }
                
                if (data.exists && data.first_cliente) {
                    if (clienteField && !clienteField.value) clienteField.value = data.first_cliente;
                    if (isTestCheckbox) {
                        isTestCheckbox.disabled = true;
                        isTestCheckbox.checked = (data.first_tipo === 'teste');
                    }
                } else {
                    if (isTestCheckbox) isTestCheckbox.disabled = false;
                }
            })
            .catch(error => {
                if (error.name !== 'AbortError') {
                    console.error('Erro:', error);
                    statusDiv.innerHTML = '<div class="alert alert-danger">Erro ao consultar status do MAC.</div>';
                    if (submitBtn) submitBtn.disabled = false;
                    if (isTestCheckbox) isTestCheckbox.disabled = false;
                }
            });
    }, 500);
});

function fixInconsistency(mac) {
    fetch(`fix_mac_consistency.php?mac=${encodeURIComponent(mac)}`)
        .then(response => response.text())
        .then(data => {
            if (data === 'OK') {
                alert('Sincronização concluída! Recarregando...');
                location.reload();
            } else {
                alert('Erro ao sincronizar: ' + data);
            }
        })
        .catch(error => alert('Erro na requisição: ' + error));
}

function renewMac(mac) {
    if (confirm('Renovar este MAC? Consumirá 1 MAC do seu saldo.')) {
        fetch('renew_mac.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'mac=' + encodeURIComponent(mac)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(data.message);
                location.reload();
            } else {
                alert('Erro: ' + data.error);
            }
        })
        .catch(error => alert('Erro na requisição: ' + error));
    }
}

function extract(event) {
    event.preventDefault();
    var m3uLink = document.getElementById("m3u_address").value;
    if (m3uLink) {
        var serverUrl = m3uLink.split("/get.php")[0];
        document.getElementById("server_url").value = serverUrl;
        var username = getParameterByName("username", m3uLink);
        if (username) document.getElementById("username").value = username;
        var password = getParameterByName("password", m3uLink);
        if (password) document.getElementById("password").value = password;
        if (username && password) alert("Usuário e senha extraídos com sucesso!");
        else alert("Não foi possível extrair usuário e senha.");
    } else {
        alert("Cole uma lista M3U válida.");
    }
}

function getParameterByName(name, url) {
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return "";
    if (!results[2]) return "";
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>

<?php include '../includes/footer3.php'; ?>