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

// Função para extrair detalhes do link M3U
function extractM3UDetails($url) {
    $details = [
        'host' => '',
        'username' => '',
        'password' => '',
        'protocol' => ''
    ];

    if (empty($url)) {
        return $details;
    }

    // Verificar se a URL é válida
    $parsedUrl = parse_url($url);
    if ($parsedUrl === false) {
        return $details;
    }

    // Extrair protocolo
    if (isset($parsedUrl['scheme'])) {
        $details['protocol'] = $parsedUrl['scheme'];
    }

    // Extrair host (incluindo a porta, se presente)
    if (isset($parsedUrl['host'])) {
        $details['host'] = $parsedUrl['host'];
        if (isset($parsedUrl['port'])) {
            $details['host'] .= ':' . $parsedUrl['port'];
        }
    }

    // Extrair username e password dos parâmetros da URL
    parse_str(isset($parsedUrl['query']) ? $parsedUrl['query'] : '', $queryParams);
    if (isset($queryParams['username'])) {
        $details['username'] = $queryParams['username'];
    }
    if (isset($queryParams['password'])) {
        $details['password'] = $queryParams['password'];
    }

    return $details;
}

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

$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';
$searchQuery = '';
if (!empty($searchTerm)) {
    $searchQuery = "WHERE mac_address LIKE '%$searchTerm%'";
}

$result = $db1->query("SELECT * FROM ibo $searchQuery ORDER BY id ASC");

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['m3u_link']) && !empty($searchTerm)) {
    $m3uLink = $_POST['m3u_link'];
    $macAddress = $searchTerm;

    // Extrair detalhes do link M3U
    $details = extractM3UDetails($m3uLink);

    // Atualizar os dados do cliente
    $stmt = $db1->prepare("UPDATE ibo SET url = :url, username = :username, password = :password WHERE mac_address = :mac_address");

    if ($stmt) {
        $stmt->bindValue(':url', $details['protocol'] . '://' . $details['host'], SQLITE3_TEXT);
        $stmt->bindValue(':username', $details['username'], SQLITE3_TEXT);
        $stmt->bindValue(':password', $details['password'], SQLITE3_TEXT);
        $stmt->bindValue(':mac_address', $macAddress, SQLITE3_TEXT);

        if ($stmt->execute()) {
            $message = 'Atualização realizada com sucesso!';
        } else {
            $message = 'Erro ao executar a atualização.';
        }
    } else {
        $message = 'Erro ao preparar a instrução SQL.';
    }
}

include 'includes/header.php';
?>

<style>
  .form-group {
    margin-bottom: 15px;
  }
</style>

<main role="main" class="col-15 pt-4 px-5">
    <div class="">
        <div id="main">
            <div class="row">
                <div class="col-lg-12">
                    <div class="card border-left-primary shadow h-100 card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary2"><i class="fas fa-fw fa-search"></i> Atualizar Cliente via Link M3U</h6>
                        </div>
                        <div class="card-body">
                            <form method="get" class="mb-3">
                                <div class="form-group">
                                    <div class="input-group">
                                        <input type="text" name="search" class="form-control" placeholder="Pesquise pelo MAC..." value="<?php echo htmlspecialchars($searchTerm); ?>">
                                        <div class="input-group-append">
                                            <button type="submit" class="btn btn-primary">Pesquisar</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                            
                            <?php if (!empty($searchTerm)): ?>
                                <form method="post" action="">
                                    <div class="form-group">
                                        <label for="m3u_link">Link M3U:</label>
                                        <input type="text" name="m3u_link" class="form-control" id="m3u_link" placeholder="Insira o link M3U..." value="<?php echo isset($_POST['m3u_link']) ? htmlspecialchars($_POST['m3u_link']) : ''; ?>">
                                    </div>
                                    
                                    <div class="form-group">
                                        <button type="submit" class="btn btn-primary">Atualizar Cliente</button>
                                    </div>
                                </form>

                                <?php if (isset($message)): ?>
                                    <div class="alert alert-info">
                                        <?php echo htmlspecialchars($message); ?>
                                    </div>
                                <?php endif; ?>

                                <div class="table-responsive">
                                    <table class="table table-striped table-sm">
                                        <thead class="text-primary">
                                            <tr>
                                                <th>Servidor</th>
                                                <th>Endereço Mac</th>
                                                <th>Usuário</th>
                                                <th>Validade</th>
                                                <th>DNS</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while ($row1 = $result->fetchArray()) { ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($row1['title']); ?></td>
                                                    <td><?php echo htmlspecialchars($row1['mac_address']); ?></td>
                                                    <td><?php echo htmlspecialchars($row1['username']); ?></td>
                                                    <td><?php echo htmlspecialchars($row1['expire_date']); ?></td>
                                                    <td><?php echo htmlspecialchars($row1['url']); ?></td>
                                                </tr>
                                            <?php } ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>

                            <?php include 'includes/footer.php'; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>