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

$db = new SQLite3('./a/.eggziedb.db');
$db->exec('CREATE TABLE IF NOT EXISTS ibo(
    id INTEGER PRIMARY KEY NOT NULL,
    mac_address VARCHAR(100),
    username VARCHAR(100),
    password VARCHAR(100),
    expire_date VARCHAR(100),
    url VARCHAR(100),
    title VARCHAR(100),
    seller VARCHAR(100),
    extra VARCHAR(200),
    created_at VARCHAR(100)
)');

$success = "";
$error = "";
$dns = "";
$username = "";
$password = "";
$title = "";

function extractFromM3UUrl($m3u_url) {
    $data = [
        'username' => '',
        'password' => '',
        'dns' => '',
        'title' => '',
        'raw_url' => $m3u_url
    ];
    
    $parsed_url = parse_url($m3u_url);
    
    if (isset($parsed_url['scheme']) && isset($parsed_url['host'])) {
        $dns_parts = [];
        $dns_parts[] = $parsed_url['scheme'] . '://';
        $dns_parts[] = $parsed_url['host'];
        if (isset($parsed_url['port'])) {
            $dns_parts[] = ':' . $parsed_url['port'];
        }
        $data['dns'] = implode('', $dns_parts);
    }
    
    if (isset($parsed_url['user'])) $data['username'] = $parsed_url['user'];
    if (isset($parsed_url['pass'])) $data['password'] = $parsed_url['pass'];
    
    if (isset($parsed_url['query'])) {
        parse_str($parsed_url['query'], $query_params);
        if (empty($data['username'])) {
            $data['username'] = $query_params['username'] ?? $query_params['user'] ?? '';
        }
        if (empty($data['password'])) {
            $data['password'] = $query_params['password'] ?? $query_params['pass'] ?? '';
        }
    }
    
    if (isset($parsed_url['host'])) {
        $data['title'] = ucfirst(str_replace(['.', '-', '_'], ' ', $parsed_url['host']));
    }
    
    return $data;
}

if(isset($_POST['extract_m3u'])){
    $m3u_url = trim($_POST['m3u_url']);
    if(!empty($m3u_url)){
        if (!preg_match('#^https?://#', $m3u_url)) $m3u_url = 'http://' . $m3u_url;
        $extracted_data = extractFromM3UUrl($m3u_url);
        $dns = $extracted_data['dns'];
        $username = $extracted_data['username'];
        $password = $extracted_data['password'];
        $title = $extracted_data['title'];
        $success = "Dados extraídos com sucesso!";
    }
}

if (isset($_POST['submit'])) {
    $usuario = trim($_POST['username']);
    $mac_address = strtolower(trim($_POST['mac_address']));
    $password = trim($_POST['password']);
    $dns = trim($_POST['dns']);
    $title = trim($_POST['title']);
    $ne = trim($_POST['expire_date']); // Data manual
    
    $full = date('Y-m-d\TH:i:s.000000\Z');
    
    $stmt = $db->prepare("INSERT INTO ibo(mac_address, username, password, expire_date, url, title, created_at, seller, extra) 
            VALUES(:mac, :user, :pass, :exp, :url, :title, :created, 'ADM', '')");
    $stmt->bindValue(':mac', $mac_address, SQLITE3_TEXT);
    $stmt->bindValue(':user', $usuario, SQLITE3_TEXT);
    $stmt->bindValue(':pass', $password, SQLITE3_TEXT);
    $stmt->bindValue(':exp', $ne, SQLITE3_TEXT);
    $stmt->bindValue(':url', $dns, SQLITE3_TEXT);
    $stmt->bindValue(':title', $title, SQLITE3_TEXT);
    $stmt->bindValue(':created', $full, SQLITE3_TEXT);
    
	    if($stmt->execute()) {
	        $db->close();
	        echo "<script>window.location.href='dashboard.php';</script>";
	        exit;
	    } else {
        $error = "Erro ao criar usuário: " . $db->lastErrorMsg();
    }
}

include 'includes/header.php';
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Criar Novo Usuário</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
    body{ margin:0; font-family: "Segoe UI",sans-serif; background: radial-gradient(circle at top,#1b2a45 0%,#050712 55%,#03040a 100%); color:#eef2ff; padding:20px; }
    .wrapper{ max-width:800px; margin:auto; }
    .card{ background:rgba(15,27,52,0.9); padding:30px; border-radius:20px; border:1px solid rgba(114,159,255,0.3); box-shadow:0 15px 35px rgba(0,0,0,0.6); }
    .input{ width:100%; padding:12px; border:1px solid rgba(113,145,232,0.4); border-radius:12px; background:rgba(8,14,30,0.95); color:#eaf0ff; margin-bottom:15px; }
    .btn{ padding:12px 25px; border-radius:12px; border:none; cursor:pointer; font-weight:bold; transition:0.3s; background:linear-gradient(135deg,#52ffb8,#2fcc8a); color:#050712; width:100%; }
    .btn-extract{ background:rgba(120,170,255,0.2); color:#7eb4ff; border:1px solid #7eb4ff; margin-bottom:20px; }
    .alert{ padding:15px; border-radius:10px; margin-bottom:20px; }
    .alert-success{ background:rgba(82,255,184,0.1); color:#52ffb8; border:1px solid #52ffb8; }
    .alert-danger{ background:rgba(255,82,82,0.1); color:#ff5252; border:1px solid #ff5252; }
</style>
</head>
<body>
<div class="wrapper">
    <div class="card">
        <h1>Criar Novo Usuário</h1>
        <?php if($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>
        <?php if($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>

        <form method="post" style="margin-bottom:30px;">
            <label>Extrair de URL M3U</label>
            <input type="text" name="m3u_url" class="input" placeholder="Cole a URL M3U aqui...">
            <button type="submit" name="extract_m3u" class="btn btn-extract">Extrair Dados</button>
        </form>

        <form method="post">
            <label>MAC Address</label>
            <input type="text" name="mac_address" class="input" placeholder="00:00:00:00:00:00" required>
            
            <label>Nome do Servidor</label>
            <input type="text" name="title" class="input" value="<?= htmlspecialchars($title) ?>" required>

            <label>Usuário</label>
            <input type="text" name="username" class="input" value="<?= htmlspecialchars($username) ?>" required>

            <label>Senha</label>
            <input type="text" name="password" class="input" value="<?= htmlspecialchars($password) ?>" required>

            <label>DNS / URL</label>
            <input type="text" name="dns" class="input" value="<?= htmlspecialchars($dns) ?>" placeholder="http://..." required>

            <label>Data de Expiração (Livre)</label>
            <input type="date" name="expire_date" class="input" value="<?= date('Y-m-d', strtotime('+1 year')) ?>" required>

            <button type="submit" name="submit" class="btn">Criar Usuário</button>
        </form>
        <a href="users.php" style="display:block; text-align:center; margin-top:20px; color:#8ba7ff; text-decoration:none;">Voltar para Lista</a>
    </div>
</div>
</body>
</html>
<?php $db->close(); ?>
