<?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';

$id = $_GET['id'] ?? null;
$regra = null;
if ($id) {
    $regra = getChatbotRuleById($id, $admin_id);
    if (!$regra) { header("Location: chatbot.php"); exit; }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $tipo = $_POST['rule_type'];
    $acao = $_POST['rule_action'];
    $resp = $_POST['response'];
    $msgs = $_POST['messages'] ?? []; 

    if ($id) {
        updateChatBotRule($admin_id, $id, $tipo, $acao, $resp, $msgs);
    } else {
        addChatBotRule($admin_id, $tipo, $acao, $resp, $msgs);
    }
    header("Location: chatbot.php");
    exit;
}
?>
<!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>Editar Regra :: Chatbot</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 src="https://vendedorp2p.com/views/_js/jquery/jquery-3.1.1.min.js"></script>
    <script 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; } 
        @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="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><?php echo $id ? 'Editar' : 'Criar'; ?> Regra</h3>
                    <div class="card">
                        <form method="POST">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Tipo</label>
                                        <select name="rule_type" class="form-control">
                                            <option value="equals" <?php echo ($regra && $regra['rule_type']=='equals')?'selected':''; ?>>Igual a (Exato)</option>
                                            <option value="contains" <?php echo ($regra && $regra['rule_type']=='contains')?'selected':''; ?>>Contém (Parte do texto)</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Ação</label>
                                        <select name="rule_action" class="form-control">
                                            <option value="text" <?php echo ($regra && $regra['rule_action']=='text')?'selected':''; ?>>Enviar Texto</option>
                                            <option value="test_iptv" <?php echo ($regra && $regra['rule_action']=='test_iptv')?'selected':''; ?>>Gerar Teste IPTV</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Gatilhos</label>
                                    <div id="triggers-container">
                                        <?php if($regra && !empty($regra['messages'])): ?>
                                            <?php foreach($regra['messages'] as $msg): ?>
                                                <div class="input-group mb-2">
                                                    <input type="text" name="messages[]" class="form-control" value="<?php echo htmlspecialchars($msg); ?>" required>
                                                    <div class="input-group-append"><button type="button" class="btn btn-danger m-0" onclick="this.closest('.input-group').remove()">X</button></div>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <div class="input-group mb-2">
                                                <input type="text" name="messages[]" class="form-control" placeholder="Ex: teste" required>
                                                <div class="input-group-append"><button type="button" class="btn btn-danger m-0" onclick="this.closest('.input-group').remove()">X</button></div>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    <button type="button" class="btn btn-sm btn-info text-white" onclick="addTrigger()">+ Adicionar Gatilho</button>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Resposta de Texto</label>
                                    <textarea name="response" class="form-control" rows="5"><?php echo $regra ? $regra['response'] : ''; ?></textarea>
                                </div>
                            </div>
                            <div class="card-footer">
                                <button type="submit" class="btn btn-primary">Salvar</button>
                                <a href="chatbot.php" class="btn btn-secondary">Cancelar</a>
                            </div>
                        </form>
                    </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);
        function addTrigger() {
            const div = document.createElement('div');
            div.className = 'input-group mb-2';
            div.innerHTML = '<input type="text" name="messages[]" class="form-control" placeholder="Novo gatilho"><div class="input-group-append"><button type="button" class="btn btn-danger m-0" onclick="this.closest(\'.input-group\').remove()">X</button></div>';
            document.getElementById('triggers-container').appendChild(div);
        }
    </script>
</body>
</html>
