<?php
session_start();
require_once("chatbot_integrado_funcoes.php"); 

if (!isset($_SESSION['user_id'])) { header("Location: index.php"); exit; }
$admin_id = $_SESSION['user_id'];
$user_name = $_SESSION['username'] ?? 'Admin';

// === CORREÇÃO DOS CRÉDITOS ===
$user_credits = "∞"; // Padrão para o Admin (ID 1)

if ($admin_id != 1) {
    // Se for revendedor, busca os créditos reais no banco
    global $pdo;
    // Garante que a conexão existe (caso não venha do include anterior)
    if(!isset($pdo)) { 
        if(file_exists("includes/db.php")) require_once("includes/db.php");
    }

    if(isset($pdo)) {
        $stmt_cred = $pdo->prepare("SELECT credits FROM revendedores WHERE id = ?");
        $stmt_cred->execute([$admin_id]);
        $cred_db = $stmt_cred->fetchColumn();
        // Se achou, usa o valor. Se não achou (erro), define como 0.
        $user_credits = ($cred_db !== false) ? $cred_db : 0;
    }
}
// =============================

$feedback = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'delete') {
    deleteChatBotRule($admin_id, $_POST['id']);
    $feedback = "<div class='alert alert-danger'>Regra apagada com sucesso!</div>";
}

$lista_regras = getAllChatbotRulesByAdmin($admin_id);
$chatbot_url = getChatbotUrl($admin_id);
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 
    <title>Chatbot :: Painel IPTV</title>
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/pre-loader.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/pre-loader-dark.css">
    <script type="text/javascript" src="https://vendedorp2p.com/views/_js/jquery/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="https://vendedorp2p.com/views/_plugins/js-cookie/js.cookie.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_fonts/batch-icons/css/batch-icons.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/bootstrap/bootstrap.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/bootstrap/mdb.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_plugins/custom-scrollbar/jquery.mCustomScrollbar.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/hamburgers/hamburgers.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/style.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_fonts/font-awesome/css/all.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/dark-theme.css">
    <style> 
        .fa-spinner { display: none !important; } 
        .message-badge { background-color: #6c757d; color: white; padding: 4px 8px; border-radius: 12px; margin: 2px; font-size: 0.85em; display: inline-block;}
        /* Ajuste do Input de Copiar */
        .api-input { background-color: #2c2c2c !important; color: #00ff00 !important; border: 1px solid #444; font-family: monospace; font-size: 13px; }
        /* Ajuste Sidebar */
        @media (min-width: 992px) { #sidebar { width: 240px; position: fixed; top: 0; left: 0; height: 100vh; z-index: 1000; overflow-y: auto; } .right-column { margin-left: 240px; width: calc(100% - 240px); } .hamburger { display: none !important; } }
        @media (max-width: 991px) { #sidebar { position: fixed; top: 0; left: -260px; width: 250px; height: 100vh; z-index: 9999; transition: all 0.3s ease; box-shadow: 2px 0 10px rgba(0,0,0,0.5); } #sidebar.active { left: 0; } .right-column { margin-left: 0 !important; width: 100% !important; padding-top: 10px; } .navbar { padding: 10px; } .hamburger { display: block !important; z-index: 10000; padding: 0; } .overlay-menu { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9998; } .overlay-menu.active { display: block; } }
    </style>
</head>
<body>
    <div id="loader-wrapper"><div class="lds-roller"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div></div>
    <div class="overlay-menu" id="overlayMenu"></div>
    <div class="container-fluid p-0"> 
        <div class="row no-gutters"> 
            <?php include 'includes/sidebar.php'; ?>
            <div class="right-column">
                <nav class="navbar navbar-expand-lg navbar-light bg-white border-bottom">
                    <button class="hamburger hamburger--slider" type="button" id="btnToggleMenu"><span class="hamburger-box"><span class="hamburger-inner"></span></span></button>
                    <div class="ml-auto d-flex align-items-center">
                        <div class="mr-3"><span class="badge badge-pill badge-danger py-2 px-3"><?php echo $user_credits; ?> Créditos</span></div>
                        <div class="dropdown">
                            <a class="nav-link dropdown-toggle d-flex align-items-center" data-toggle="dropdown" href="#">
                                <div class="d-none d-md-block mr-2 font-weight-bold"><?php echo htmlspecialchars($user_name); ?></div>
                                <img src="https://vendedorp2p.com/views/_img/profile-pic.png" width="35" height="35" class="rounded-circle">
                            </a>
                            <div class="dropdown-menu dropdown-menu-right">
                                <a class="dropdown-item" href="logout.php"><i class="fa fa-power-off mr-2"></i> Sair</a>
                            </div>
                        </div>
                    </div>
                </nav>
                <main class="main-content p-3 p-md-5" role="main">
                    <h3><i class="fab fa-whatsapp"></i> Chatbot Automático</h3>
                    <?php echo $feedback; ?>

                    <div class="card mb-4">
                        <div class="card-body">
                            <h5><i class="fas fa-link"></i> URL para o App</h5>
                            <p>Copie e cole no <strong>AutoResponder for WA</strong> ou <strong>Auto Reply</strong>:</p>
                            
                            <div class="input-group">
                                <input type="text" id="apiInput" class="form-control api-input" value="<?php echo $chatbot_url; ?>" readonly>
                                <div class="input-group-append">
                                    <button class="btn btn-primary" type="button" id="btnCopy" onclick="copyApi()">
                                        <i class="fa fa-copy"></i> COPIAR
                                    </button>
                                </div>
                            </div>
                            <small class="text-muted mt-2 d-block">Clique no botão para copiar automaticamente.</small>
                        </div>
                    </div>

                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h4>Regras</h4>
                        <a href="chatbot_form.php" class="btn btn-success"><i class="fas fa-plus"></i> Nova Regra</a>
                    </div>

                    <div class="card">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover mb-0">
                                <thead class="thead-dark">
                                    <tr>
                                        <th>Gatilhos</th>
                                        <th>Tipo</th>
                                        <th>Ação</th>
                                        <th>Runs</th>
                                        <th class="text-right">Opções</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if(empty($lista_regras)): ?>
                                        <tr><td colspan="5" class="text-center p-3">Nenhuma regra criada.</td></tr>
                                    <?php endif; ?>
                                    <?php foreach($lista_regras as $regra): ?>
                                    <tr>
                                        <td>
                                            <?php foreach($regra['messages'] as $msg): ?>
                                                <span class="message-badge"><?php echo htmlspecialchars($msg); ?></span>
                                            <?php endforeach; ?>
                                        </td>
                                        <td><?php echo $regra['rule_type'] == 'equals' ? 'Igual' : 'Contém'; ?></td>
                                        <td>
                                            <?php if($regra['rule_action'] == 'test_iptv'): ?>
                                                <span class="badge badge-warning">Gerar Teste</span>
                                            <?php else: ?>
                                                <span class="badge badge-info">Texto</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo $regra['runs']; ?></td>
                                        <td class="text-right">
                                            <a href="chatbot_form.php?id=<?php echo $regra['id']; ?>" class="btn btn-sm btn-primary"><i class="fa fa-edit"></i></a>
                                            <form method="POST" style="display:inline;" onsubmit="return confirm('Apagar regra?');">
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="id" value="<?php echo $regra['id']; ?>">
                                                <button class="btn btn-sm btn-danger"><i class="fa fa-trash"></i></button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </main>
            </div>
        </div>
    </div>
    <script src="https://vendedorp2p.com/views/_js/bootstrap/popper.min.js"></script>
    <script src="https://vendedorp2p.com/views/_js/bootstrap/bootstrap.min.js"></script>
    <script src="https://vendedorp2p.com/views/_js/bootstrap/mdb.min.js"></script>
    <script src="https://vendedorp2p.com/views/_plugins/custom-scrollbar/jquery.mCustomScrollbar.concat.min.js"></script>
    <script src="https://vendedorp2p.com/views/_js/scripts.js"></script>
    <script>
        $(function () { setTimeout(function(){ $("#loader-wrapper").fadeOut(250); }, 100); });
        $('#btnToggleMenu, #overlayMenu').click(function() { $('#sidebar').toggleClass('active'); $('#overlayMenu').toggleClass('active'); $('#btnToggleMenu').toggleClass('is-active'); });
        const default_theme = "dark_theme"; var c_theme_name = Cookies.get('current_theme') || default_theme; $('body').addClass(c_theme_name);
        
        // FUNÇÃO DE COPIAR API
        function copyApi() {
            var copyText = document.getElementById("apiInput");
            copyText.select();
            copyText.setSelectionRange(0, 99999); // Para mobile
            document.execCommand("copy");
            
            // Muda o texto do botão para avisar que copiou
            var btn = document.getElementById("btnCopy");
            var original = btn.innerHTML;
            btn.innerHTML = '<i class="fa fa-check"></i> COPIADO!';
            btn.classList.remove('btn-primary');
            btn.classList.add('btn-success');
            
            setTimeout(function(){
                btn.innerHTML = original;
                btn.classList.remove('btn-success');
                btn.classList.add('btn-primary');
            }, 2000);
        }
    </script>
</body>
</html>
