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

if (!isset($_SESSION['id'])) {
    header("Location: login.php");
    exit();
}

include_once 'api/db/logs_helper.php';
$db = new SQLite3("./api/.ansdb.db");

if (isset($_POST["submit_create"])) {
    $mac = strtoupper($_POST["mac_address"]);
    $title = $_POST["title"];
    $type = $_POST["type"];
    $expire = $_POST["expire_date"];
    $id_user = $_SESSION['id']; 
    
    // CAPTURA O NOME DO PROVEDOR E GERA O ARQUIVO COM TAMANHO EQUIVALENTE A _10sdp
    $nome_provedor = $_POST["nome_provedor"];
    
    $conteudo_php = '<?php header("Content-Type: text/html; charset=UTF-8"); ?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <style>
        body { 
            background-color: transparent; 
            margin: 0; 
            padding: 0; 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            height: 100vh; 
            overflow: hidden;
            color: #ffffff;
            font-family: sans-serif;
        }
        .texto-provedor { 
            /* Equivalente visual aproximado ao @dimen/_10sdp */
            font-size: 15px; 
            font-weight: bold; 
            text-align: center;
            text-shadow: 1px 1px 3px rgba(0,0,0,0.8);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
    </style>
</head>
<body>
    <div class="texto-provedor">' . $nome_provedor . '</div>
</body>
</html>';

    file_put_contents("api/panaci_txt_provedor.php", $conteudo_php);

    if ($type == "0") {
        $dns = $_POST["dns"];
        $user = $_POST["username"];
        $pass = $_POST["password"];
        $url_final = $dns . "/get.php?username=" . $user . "&password=" . $pass . "&type=m3u_plus&output=ts";
        $lista_para_log = $url_final; 
    } else {
        $dns = ""; $user = ""; $pass = "";
        $url_final = $_POST["url_m3u"];
        $lista_para_log = $url_final; 
    }

    $stmt = $db->prepare("INSERT INTO ibo (mac_address, title, username, password, dns, url, type, expire_date, id_user, active) 
                          VALUES (:mac, :title, :user, :pass, :dns, :url, :type, :expire, :id_user, 1)");
    
    $stmt->bindValue(':mac', $mac, SQLITE3_TEXT);
    $stmt->bindValue(':title', $title, SQLITE3_TEXT);
    $stmt->bindValue(':user', $user, SQLITE3_TEXT);
    $stmt->bindValue(':pass', $pass, SQLITE3_TEXT);
    $stmt->bindValue(':dns', $dns, SQLITE3_TEXT);
    $stmt->bindValue(':url', $url_final, SQLITE3_TEXT);
    $stmt->bindValue(':type', $type, SQLITE3_TEXT);
    $stmt->bindValue(':expire', $expire, SQLITE3_TEXT);
    $stmt->bindValue(':id_user', $id_user, SQLITE3_INTEGER);

    if ($stmt->execute()) {
        $quem_fez = $_SESSION['NAME'] ?? "Revenda ID: $id_user";
        registrar_log($quem_fez, "CRIOU NOVO CLIENTE: $title | PROVEDOR: $nome_provedor | MAC: $mac | LISTA: $lista_para_log");

        header("Location: users.php?status=success");
        exit();
    }
}

include "includes/header.php";
?>
<style>
    * { box-sizing: border-box; }
    html, body, .wrapper, .main-panel, .content, .container-fluid { 
        background-color: #020617 !important; color: #e2e8f0 !important; overflow-x: hidden;
    }
    .lua-icon, .fa-moon, .fa-sun, .navbar, #dark-mode-switch { display: none !important; }
    .container-fluid { padding: 15px !important; }
    .btn-back-nav {
        display: inline-flex; align-items: center; gap: 8px; color: #64748b; text-decoration: none !important;
        font-size: 0.85rem; font-weight: 600; margin-bottom: 20px; max-width: 650px; margin-left: auto; margin-right: auto;
    }
    .premium-card {
        background: #070e1b !important; border: 1px solid #1e293b !important; border-radius: 20px;
        padding: 25px; box-shadow: 0 10px 25px rgba(0,0,0,0.3); max-width: 650px; margin: 0 auto 40px auto; width: 100%;
        animation: slideUp 0.5s ease-out;
    }
    @keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
    .card-header-premium { margin-bottom: 25px; border-bottom: 1px solid rgba(255,255,255,0.05); padding-bottom: 15px; }
    .card-header-premium h1 { font-size: 1.4rem; font-weight: 800; color: #fff; margin: 0; }
    .card-header-premium p { color: #3b82f6; font-size: 0.8rem; margin-top: 4px; font-weight: 600; }
    label { display: block; color: #3b82f6; font-size: 0.7rem; font-weight: 800; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px; }
    .form-input { 
        width: 100%; background: #0f172a !important; border: 1px solid #1e293b !important; 
        color: #fff !important; padding: 15px; border-radius: 12px; font-size: 0.95rem; margin-bottom: 20px; 
    }
    .import-group { display: flex; gap: 8px; margin-bottom: 25px; background: rgba(59, 130, 246, 0.05); padding: 10px; border-radius: 15px; border: 1px dashed rgba(59, 130, 246, 0.3); }
    .btn-import { background: #3b82f6 !important; color: #fff !important; border: none; padding: 0 25px; border-radius: 12px; font-weight: 800; cursor: pointer; }
    .btn-premium-save { background: #2ecc71 !important; color: #fff !important; padding: 18px; border-radius: 14px; font-weight: 800; text-transform: uppercase; border: none; width: 100%; display: flex; align-items: center; justify-content: center; gap: 10px; }
    .btn-premium-cancel { background: #1e293b !important; color: #94a3b8 !important; padding: 18px; border-radius: 14px; font-weight: 800; text-transform: uppercase; text-align: center; text-decoration: none !important; display: block; }
    .row-buttons { display: grid; grid-template-columns: 1fr; gap: 12px; margin-top: 20px; }
    @media (min-width: 768px) { .row-buttons { grid-template-columns: 2fr 1fr; } }
</style>

<div class="container-fluid">
    <div style="max-width: 650px; margin: 0 auto;">
        <a href="users.php" class="btn-back-nav"><i class="fas fa-chevron-left"></i> Voltar para Lista</a>
    </div>
    <form method="post" id="formCreate">
        <div class="premium-card">
            <div class="card-header-premium">
                <h1>Novo Cliente</h1>
                <p><i class="fas fa-user-plus mr-1"></i> Preencha os dados de acesso</p>
            </div>
            <div class="card-body">
                <label>Nome do Provedor (Exibido na WebView)</label>
                <input type="text" class="form-input" name="nome_provedor" placeholder="Digite o nome da sua marca" required>
                
                <label>Nome do Cliente</label>
                <input type="text" class="form-input" name="title" placeholder="Digite o nome do cliente" required>
                
                <label>Endereço MAC</label>
                <input type="text" class="form-input" id="mac_address" name="mac_address" placeholder="00:00:00:00:00:00" required maxlength="17">
                
                <label>Tipo de Conexão</label>
                <select class="form-input" id="type" name="type">
                    <option value="0">Xtream Codes</option>
                    <option value="1">Link M3U Externo</option>
                </select>
                
                <div id="m3u_import_area">
                    <label>Importação Inteligente</label>
                    <div class="import-group">
                        <input type="text" class="form-input" id="m3u_link_input" style="margin-bottom:0" placeholder="Cole o link M3U...">
                        <button type="button" class="btn-import" onclick="extractData()">EXTRAIR</button>
                    </div>
                </div>
                
                <div id="fields_xtream">
                    <label>Servidor / DNS</label>
                    <input type="text" class="form-input" name="dns" id="dns">
                    <div class="flex-fields">
                        <div><label>Usuário</label><input type="text" class="form-input" name="username" id="username"></div>
                        <div><label>Senha</label><input type="text" class="form-input" name="password" id="password"></div>
                    </div>
                </div>
                
                <div id="fields_m3u" style="display: none;">
                    <label>URL M3U Completa</label>
                    <input type="text" class="form-input" name="url_m3u" id="url_m3u">
                </div>
                
                <label>Vencimento</label>
                <input type="date" class="form-input" name="expire_date" required value="<?= date('Y-m-d', strtotime('+30 days')) ?>">
                
                <input type="hidden" name="submit_create" value="1">
                
                <div class="row-buttons">
                    <button type="button" id="btnFakeSubmit" class="btn-premium-save"><i class="fas fa-check-circle"></i> Criar Acesso</button>
                    <a href="users.php" class="btn-premium-cancel">Cancelar</a>
                </div>
            </div>
        </div>
    </form>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
    $('#type').change(function() {
        if ($(this).val() == "0") { $('#fields_xtream, #m3u_import_area').show(); $('#fields_m3u').hide(); }
        else { $('#fields_xtream, #m3u_import_area').hide(); $('#fields_m3u').show(); }
    });
    $('#mac_address').on('input', function() {
        var v = $(this).val().toUpperCase().replace(/[^A-F0-9]/g, '');
        var m = v.match(/.{1,2}/g);
        $(this).val(m ? m.join(':').substr(0, 17) : v);
    });
    $('#btnFakeSubmit').click(function() {
        if(!$('input[name="nome_provedor"]').val() || !$('input[name="title"]').val() || $('#mac_address').val().length < 17){
             Swal.fire({ icon: 'error', title: 'Erro', text: 'Preencha Provedor, Nome e MAC corretamente!', background: '#070e1b', color: '#fff' });
             return;
        }
        $('#formCreate').submit();
    });
});
function extractData() {
    const link = $('#m3u_link_input').val();
    if(!link) return;
    try {
        const url = new URL(link);
        $('#dns').val(url.origin);
        $('#username').val(url.searchParams.get("username") || url.searchParams.get("user"));
        $('#password').val(url.searchParams.get("password") || url.searchParams.get("pass"));
        $('#url_m3u').val(link);
    } catch(e) { alert('Link inválido'); }
}
</script>
<?php include "includes/footer.php"; ?>
