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

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

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

if (empty($seller_name)) die("Erro: Sessão de revenda não encontrada.");

$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 revenda WHERE usuario = '$seller_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!'); window.history.back();</script>"; exit();
    }

    $check_mac = $db->query("SELECT id, extra, expire_date, is_test FROM ibo WHERE mac_address = '$mac_address' AND seller = '$seller_name' LIMIT 1");
    $existing_mac = $check_mac->fetchArray(SQLITE3_ASSOC);
    if ($existing_mac) {
        $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 não pode ser alterado.');</script>";
    } else {
        $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('Sem MACs disponíveis!'); window.history.back();</script>"; exit(); }
        }
    }

    $count_result = $db->query("SELECT COUNT(*) as count FROM ibo WHERE mac_address = '$mac_address' AND seller = '$seller_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 atingido!'); 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($seller_name) . "', '" . SQLite3::escapeString($descricao) . "', $is_test)";

    $db->exec('BEGIN IMMEDIATE');
    if ($db->exec($sql)) {
        $last_id = $db->lastInsertRowID();
        if ($last_id > 0) {
            if ($is_test == 0 && !$already_exists) {
                $nova_quantidade = $macs_disponiveis - 1;
                $db->exec("UPDATE revenda SET macs = $nova_quantidade WHERE usuario = '$seller_name'");
            }
            syncMacPlaylists($db, $mac_address, $seller_name);
            $db->exec('COMMIT');
            echo "<script>alert('Usuário criado!'); window.location.href='index.php';</script>";
        } else { $db->exec('ROLLBACK'); echo "<script>alert('Erro no ID'); window.history.back();</script>"; }
    } else { $db->exec('ROLLBACK'); echo "<script>alert('Erro: " . 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-renew { background-color: #0dcaf0; color: #000; border: none; padding: 6px 12px; border-radius: 20px; font-size: 0.8rem; margin-top: 8px; }
</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">CRIAR USUÁRIO</h6></div>
        <div class="card-body">
            <div class="alert alert-secondary mb-4">
                <form onsubmit="return false;">
                    <div class="form-group">
                        <label><strong>EXTRAIR LISTA M3U</strong></label>
                        <div class="input-group">
                            <input class="form-control" id="m3u_address" placeholder="COLE AQUI SUA LISTA M3U">
                            <button class="btn btn-success" type="button" onclick="extract(event)">EXTRAIR</button>
                        </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></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></label><input type="text" class="form-control" name="title" required></div>
                <div class="form-group">
                    <label><strong>DNS</strong></label>
                    <select class="form-control" name="dns" id="server_url" required>
                        <option value="">Escolher DNS</option>
                        <?php $dns_options = $dnsDB->getAll('revenda', $seller_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></label><input type="text" class="form-control" name="Descricao" required></div>
                <div class="form-group"><label><strong>USUÁRIO</strong></label><input type="text" class="form-control" name="username" id="username" required></div>
                <div class="form-group"><label><strong>SENHA</strong></label><input type="text" class="form-control" name="password" id="password" 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> (10 dias)</label>
                    </div>
                    <div id="testInfo" style="display: none;"></div>
                </div>
                <div class="form-group">
                    <button class="btn btn-success" type="submit" name="submit">CRIAR USUÁRIO</button>
                    <a href="index.php" class="btn btn-secondary">Cancelar</a>
                </div>
            </form>
        </div>
    </div>
</div>
<div class="modal fade" id="confirmAnnualModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content"><div class="modal-header bg-primary text-white"><h5 class="modal-title">Confirmação</h5><button type="button" class="close text-white" data-dismiss="modal">&times;</button></div><div class="modal-body"><p>Deseja ativação ANUAL? Consome 1 MAC.</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>
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"), 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> Modo TESTE ativado! Expira em 10 dias, não consome MAC.'; } else testInfo.style.display="none"; });
var form = document.getElementById("createUserForm"), confirmBtn = document.getElementById("confirmAnnualBtn"), confirmedField = document.getElementById("confirmedField");
if(form) form.addEventListener("submit", function(e) { var isTestChecked = testCheckbox && testCheckbox.checked, confirmed = confirmedField && confirmedField.value === "1"; if(isTestChecked || confirmed) return true; e.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, macTimeout = null;
document.getElementById('mac_address').addEventListener('input', function() {
    if(currentAbortController) currentAbortController.abort();
    const mac = this.value, statusDiv = document.getElementById('macStatusContainer'), submitBtn = document.querySelector('button[type="submit"]'), isTestCheckbox = document.getElementById('is_test'), 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();
        fetch(`check_mac_status.php?mac=${encodeURIComponent(mac)}`, { signal: currentAbortController.signal })
            .then(r=>r.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 = '', statusClass = '', statusText = '', 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}')">Sincronizar</button></div>`:''}${data.is_expired && data.can_renew?`<div class="status-line"><button type="button" class="btn-renew" onclick="renewMac('${mac}')">Renovar Licença (Anual)</button></div>`:''}</div>`;
                if(data.exists && data.first_cliente) html += `<div class="small text-muted">📋 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"; 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(e=>{ if(e.name !== 'AbortError') { statusDiv.innerHTML='<div class="alert alert-danger">Erro na consulta.</div>'; if(submitBtn) submitBtn.disabled=false; if(isTestCheckbox) isTestCheckbox.disabled=false; } });
    }, 500);
});
function fixInconsistency(mac) { fetch(`fix_mac_consistency.php?mac=${encodeURIComponent(mac)}`).then(r=>r.text()).then(d=>{ if(d==='OK'){ alert('Sincronizado!'); location.reload(); } else alert('Erro: '+d); }).catch(e=>alert('Erro: '+e)); }
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(r=>r.json()).then(d=>{ if(d.success){ alert(d.message); location.reload(); } else alert('Erro: '+d.error); }).catch(e=>alert('Erro: '+e)); } }
function extract(e) { e.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("Extraído!"); else alert("Não foi possível extrair."); } else alert("Cole uma lista M3U."); }
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/footer2.php'; ?>