<?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),
 extra VARCHAR(200),
 seller VARCHAR(100),
 created_at VARCHAR(100)
)');

if(!isset($_GET['update'])){
    header('Location: users.php');
    exit;
}

$user_id = (int)$_GET['update'];

$stmt = $db->prepare("SELECT * FROM ibo WHERE id = :id");
$stmt->bindValue(':id', $user_id, SQLITE3_INTEGER);
$res = $stmt->execute();
$row = $res->fetchArray(SQLITE3_ASSOC);

if(!$row){
    echo "<script>alert('Usuário não encontrado!');window.location='users.php'</script>";
    exit;
}

$mac_old = $row['mac_address'];
$username = $row['username'];
$password = $row['password'];
$expire_date = $row['expire_date'];
$dns = $row['url'];
$title = $row['title'];
$extra = $row['extra'];

$success = "";
$error = "";

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'] ?: $dns;
        $username = $extracted_data['username'] ?: $username;
        $password = $extracted_data['password'] ?: $password;
        $title = $extracted_data['title'] ?: $title;
        $success = "Dados extraídos com sucesso!";
    }
}

if(isset($_POST['submit'])){
    $new_mac = strtolower(trim($_POST['mac_address']));
    $new_username = trim($_POST['username']);
    $new_pass = trim($_POST['password']);
    $new_exp = date("Y-m-d", strtotime($_POST['expire_date']));
    $new_dns = trim($_POST['url']);
    $new_title = trim($_POST['title']);
    $new_extra = trim($_POST['Descricao'] ?? '');

    $stmt = $db->prepare("SELECT COUNT(*) AS total FROM ibo WHERE mac_address = :mac AND id <> :id");
    $stmt->bindValue(':mac', $new_mac, SQLITE3_TEXT);
    $stmt->bindValue(':id', $user_id, SQLITE3_INTEGER);
    $exists = $stmt->execute()->fetchArray(SQLITE3_ASSOC)['total'];

    if($exists > 0){
        $error = "Já existe outro usuário com este MAC!";
    } else {
        $stmt = $db->prepare("UPDATE ibo SET mac_address = :mac, username = :user, password = :pass, expire_date = :exp, url = :url, title = :title, extra = :extra WHERE id = :id");
        $stmt->bindValue(':mac', $new_mac, SQLITE3_TEXT);
        $stmt->bindValue(':user', $new_username, SQLITE3_TEXT);
        $stmt->bindValue(':pass', $new_pass, SQLITE3_TEXT);
        $stmt->bindValue(':exp', $new_exp, SQLITE3_TEXT);
        $stmt->bindValue(':url', $new_dns, SQLITE3_TEXT);
        $stmt->bindValue(':title', $new_title, SQLITE3_TEXT);
        $stmt->bindValue(':extra', $new_extra, SQLITE3_TEXT);
        $stmt->bindValue(':id', $user_id, SQLITE3_INTEGER);
        
	        if($stmt->execute()){
	            $success = "Usuário atualizado com sucesso!";
	            header("refresh:1;url=dashboard.php");
	        } else {
            $error = "Erro ao atualizar: " . $db->lastErrorMsg();
        }
    }
}

include 'includes/header.php';
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Editar 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:900px; 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; }
    .btn-primary{ 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>Editar 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" value="<?= htmlspecialchars($mac_old) ?>" 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="url" class="input" value="<?= htmlspecialchars($dns) ?>" required>

            <label>Data de Expiração</label>
            <input type="date" name="expire_date" class="input" value="<?= htmlspecialchars($expire_date) ?>" required>

            <label>Descrição (Extra)</label>
            <input type="text" name="Descricao" class="input" value="<?= htmlspecialchars($extra) ?>">

            <button type="submit" name="submit" class="btn btn-primary">Salvar Alterações</button>
        </form>
        <a href="users.php" style="display:block; text-align:center; margin-top:20px; color:#8ba7ff; text-decoration:none;">Voltar</a>
    </div>
</div>
</body>
</html>
<?php $db->close(); ?>
