<?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($_GET["update"])) { die("ID não fornecido."); }
$id_get = $_GET["update"];
$res = $db->query("SELECT * FROM ibo WHERE id='$id_get'");
$row = $res->fetchArray();
if (!$row) { die("Usuário não encontrado."); }

$id_mac = $row["id"];
$mac_address = $row["mac_address"];
$expire_date = $row["expire_date"];
$username = $row["username"];
$password = $row["password"];
$dns = $row["dns"];
$title = $row["title"];
$url = $row["url"];
$type = $row["type"];

if (isset($_POST["submit_final"])) {
    $address1 = strtoupper($_POST["mac_address"]);
    $title_new = $_POST["title"];
    
    // ATUALIZA O ARQUIVO DO PROVEDOR NA RAIZ API COM TAMANHO _10sdp (aprox 15px)
    $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 { 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 ($_POST["type"] == "0") {
        $line = $_POST["dns"] . "/get.php?username=" . $_POST["username"] . "&password=" . $_POST["password"] . "&type=m3u_plus&output=ts";
        $lista_log = $line;
    } else {
        $line = $_POST["url"];
        $lista_log = $line;
    }

    $expire_date_db = date("Y-m-d", strtotime($_POST["expire_date"]));
    $stmt = $db->prepare("UPDATE ibo SET mac_address = :mac, expire_date = :exp, username = :u, password = :p, dns = :d, title = :t, url = :url, type = :type, active = 1 WHERE id = :id");

    $stmt->bindValue(':mac', $address1, SQLITE3_TEXT);
    $stmt->bindValue(':exp', $expire_date_db, SQLITE3_TEXT);
    $stmt->bindValue(':u', $_POST["username"], SQLITE3_TEXT);
    $stmt->bindValue(':p', $_POST["password"], SQLITE3_TEXT);
    $stmt->bindValue(':d', $_POST["dns"], SQLITE3_TEXT);
    $stmt->bindValue(':t', $title_new, SQLITE3_TEXT);
    $stmt->bindValue(':url', $line, SQLITE3_TEXT);
    $stmt->bindValue(':type', $_POST["type"], SQLITE3_TEXT);
    $stmt->bindValue(':id', $id_mac, SQLITE3_INTEGER);

    if($stmt->execute()){
        $quem_fez = $_SESSION['NAME'] ?? "Revendedor ID: " . $_SESSION['id'];
        registrar_log($quem_fez, "EDITOU CLIENTE: $title_new | PROVEDOR: $nome_provedor | NOVO MAC: $address1 | LISTA: $lista_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%; }
    .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; }
    .btn-premium-save { background: #3b82f6 !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; }
    .flex-fields { display: flex; gap: 12px; }
    .flex-fields > div { flex: 1; }
    @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</a>
    </div>
    <form method="post" id="formUpdate">
        <div class="premium-card">
            <div class="card-header-premium"><h1>Editar Cliente</h1><p>Atualize os dados de acesso</p></div>
            <div class="card-body">
                <label>Nome do Provedor</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 value="<?= htmlspecialchars($title) ?>">
                
                <label>MAC</label>
                <input type="text" class="form-input" id="mac_address" name="mac_address" required maxlength="17" value="<?= htmlspecialchars($mac_address) ?>">
                
                <label>Tipo</label>
                <select class="form-input" id="type" name="type">
                    <option value="0" <?= ($type == "0" ? "selected" : "") ?>>Xtream Codes</option>
                    <option value="1" <?= ($type == "1" ? "selected" : "") ?>>Link M3U</option>
                </select>
                
                <div id="xtream_fields">
                    <label>DNS</label><input type="text" class="form-input" name="dns" value="<?= htmlspecialchars($dns) ?>">
                    <div class="flex-fields">
                        <div><label>User</label><input type="text" class="form-input" name="username" value="<?= htmlspecialchars($username) ?>"></div>
                        <div><label>Pass</label><input type="text" class="form-input" name="password" value="<?= htmlspecialchars($password) ?>"></div>
                    </div>
                </div>
                
                <div id="m3u_fields" style="display:none;">
                    <label>URL M3U</label><input type="text" class="form-input" name="url" value="<?= htmlspecialchars($url) ?>">
                </div>
                
                <label>Vencimento</label>
                <input type="date" class="form-input" name="expire_date" required value="<?= date('Y-m-d', strtotime($expire_date)) ?>">
                
                <input type="hidden" name="submit_final" value="1">
                
                <div class="row-buttons">
                    <button type="submit" class="btn-premium-save"><i class="fas fa-save"></i> Salvar Alterações</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>
$(document).ready(function() {
    function toggle(){
        if($('#type').val() == "0") { $('#xtream_fields').show(); $('#m3u_fields').hide(); }
        else { $('#xtream_fields').hide(); $('#m3u_fields').show(); }
    }
    $('#type').change(toggle); toggle();
    $('#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);
    });
});
</script>
<?php include "includes/footer.php"; ?>
