<?php
session_start();
if(!isset($_SESSION['rev_logado'])){ header("Location: index_rev.php"); exit(); }
include('../api/conexao_rev.php');

$id_rev = $_SESSION['rev_logado'];

// Verifica se o ID do cliente foi passado
if(!isset($_GET['id'])){ header("Location: clientes_rev.php"); exit(); }
$id_cli = $_GET['id'];

// Busca dados atuais no MySQL (Painel da Revenda)
$sql = $conn_rev->query("SELECT * FROM clientes_rev WHERE id_cli = '$id_cli' AND id_rev_pai = '$id_rev'");
$cli = $sql->fetch_assoc();

if(!$cli){ header("Location: clientes_rev.php"); exit(); }

// Lógica de Atualização
if(isset($_POST['atualizar_cli'])){
    $nome    = $_POST['nome'];
    $login   = $_POST['login'];
    $senha   = $_POST['senha'];
    $venc    = $_POST['vencimento'];
    $dns     = $_POST['url_xtream'];
    $mac_novo = strtoupper($_POST['mac_cli']); 
    $mac_antigo = strtoupper($cli['mac_cli']); // Necessário para localizar no SQLite caso o MAC mude
    $m3u_input = $_POST['url_m3u'];

    // Define a URL final e o tipo para o IBO
    if(!empty($dns) && !empty($login) && !empty($senha)){
        $type = "0"; // Xtream Codes
        $url_final = $dns . "/get.php?username=" . $login . "&password=" . $senha . "&type=m3u_plus&output=ts";
    } else {
        $type = "1"; // M3U Externo
        $url_final = $m3u_input;
    }

    // 1. ATUALIZA NO MYSQL (Controlo do Revendedor)
    $update_mysql = "UPDATE clientes_rev SET 
                nome_cli = '$nome', login_cli = '$login', senha_cli = '$senha', 
                vencimento_cli = '$venc', url_m3u = '$url_final', url_xtream = '$dns', mac_cli = '$mac_novo' 
               WHERE id_cli = '$id_cli' AND id_rev_pai = '$id_rev'";
    
    if($conn_rev->query($update_mysql)){
        
        // 2. ATUALIZA NO SQLITE (App IBO)
        try {
            // Caminho configurado para: public_html/2026/api/.ansdb.db
            $db_app = new SQLite3("../api/.ansdb.db");
            
            $stmt = $db_app->prepare("UPDATE ibo SET 
                                    mac_address = :mac_novo, 
                                    title = :title, 
                                    username = :user, 
                                    password = :pass, 
                                    dns = :dns, 
                                    url = :url, 
                                    type = :type, 
                                    expire_date = :expire 
                                    WHERE mac_address = :mac_antigo");
            
            $stmt->bindValue(':mac_novo', $mac_novo, SQLITE3_TEXT);
            $stmt->bindValue(':title', $nome, SQLITE3_TEXT);
            $stmt->bindValue(':user', $login, SQLITE3_TEXT);
            $stmt->bindValue(':pass', $senha, SQLITE3_TEXT);
            $stmt->bindValue(':dns', $dns, SQLITE3_TEXT);
            $stmt->bindValue(':url', $url_final, SQLITE3_TEXT);
            $stmt->bindValue(':type', $type, SQLITE3_TEXT);
            $stmt->bindValue(':expire', $venc, SQLITE3_TEXT);
            $stmt->bindValue(':mac_antigo', $mac_antigo, SQLITE3_TEXT);
            
            $stmt->execute();
            $db_app->close();
            
            $status = "sucesso_update";
        } catch (Exception $e) {
            $status = "erro_sqlite";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="pt-pt">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Editar Cliente | Premium</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        html, body { background-color: #020617 !important; color: #e2e8f0 !important; font-family: sans-serif; margin: 0; padding: 0; }
        .container { padding: 15px; max-width: 600px; margin: 0 auto; }
        .btn-voltar { color: #3b82f6; text-decoration: none; font-size: 0.8rem; font-weight: 800; text-transform: uppercase; display: flex; align-items: center; gap: 5px; margin-bottom: 15px; }
        .premium-header { background: linear-gradient(135deg, #0f172a 0%, #020617 100%); padding: 20px; border-radius: 20px; border: 1px solid #1e293b; margin-bottom: 20px; }
        .card-form { background: #070e1b; border: 1px solid #1e293b; border-radius: 18px; padding: 25px; }
        .label-input { color: #3b82f6; font-size: 0.7rem; font-weight: 800; text-transform: uppercase; margin-bottom: 6px; display: block; margin-left: 5px; }
        input { width: 100%; background: #0f172a; border: 1px solid #1e293b; border-radius: 10px; padding: 12px; margin-bottom: 18px; color: #fff; outline: none; box-sizing: border-box; }
        .btn-update { width: 100%; background: #22c55e; color: #fff; border: none; padding: 14px; border-radius: 10px; font-weight: 800; cursor: pointer; text-transform: uppercase; }
        .swal2-popup { background: #0f172a !important; color: #fff !important; border: 1px solid #1e293b !important; border-radius: 20px !important; }
    </style>
</head>
<body>

<div class="container">
    <a href="clientes_rev.php" class="btn-voltar"><i class="fas fa-arrow-left"></i> Cancelar e Voltar</a>
    
    <div class="premium-header">
        <h2 style="margin:0; font-size: 1.3rem;">Editar e Sincronizar TV</h2>
        <p style="margin:5px 0 0; font-size: 0.8rem; color: #64748b;">As alterações refletem no App IBO instantaneamente.</p>
    </div>

    <div class="card-form">
        <form method="POST">
            <span class="label-input">Nome do Cliente</span>
            <input type="text" name="nome" value="<?php echo $cli['nome_cli']; ?>" required>

            <span class="label-input">Endereço MAC</span>
            <input type="text" id="mac_input" name="mac_cli" value="<?php echo $cli['mac_cli']; ?>" placeholder="00:00:00:00:00:00" required maxlength="17">

            <span class="label-input">DNS / Painel (Xtream)</span>
            <input type="text" name="url_xtream" value="<?php echo $cli['url_xtream']; ?>" placeholder="http://exemplo.com:8080">

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                <div>
                    <span class="label-input">Usuário</span>
                    <input type="text" name="login" value="<?php echo $cli['login_cli']; ?>">
                </div>
                <div>
                    <span class="label-input">Senha</span>
                    <input type="text" name="senha" value="<?php echo $cli['senha_cli']; ?>">
                </div>
            </div>

            <span class="label-input">Ou URL M3U Direta</span>
            <input type="text" name="url_m3u" value="<?php echo $cli['url_m3u']; ?>" placeholder="https://...">

            <span class="label-input">Data de Vencimento</span>
            <input type="date" name="vencimento" value="<?php echo $cli['vencimento_cli']; ?>" required>

            <button type="submit" name="atualizar_cli" class="btn-update">
                <i class="fas fa-save"></i> SALVAR E ATUALIZAR TV
            </button>
        </form>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// Formata o MAC automaticamente durante a edição
$('#mac_input').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);
});

<?php if(isset($status)): ?>
    <?php if($status == "sucesso_update"): ?>
        Swal.fire({ 
            background: '#0f172a', 
            color:'#fff', 
            icon: 'success', 
            title: 'Atualizado!', 
            text: 'Os dados foram sincronizados com o App.', 
            confirmButtonColor: '#3b82f6' 
        }).then(() => { window.location.href = 'clientes_rev.php'; });
    <?php else: ?>
        Swal.fire({ 
            background: '#0f172a', 
            color:'#fff', 
            icon: 'warning', 
            title: 'Atenção', 
            text: 'Dados guardados no painel, mas falha ao sincronizar com o SQLite.', 
            confirmButtonColor: '#3b82f6' 
        });
    <?php endif; ?>
<?php endif; ?>
</script>

</body>
</html>
