<?php
// chatbot_integrado_funcoes.php
// Caminho absoluto para garantir o carregamento do banco
if (file_exists(__DIR__ . '/includes/db.php')) {
    require_once __DIR__ . '/includes/db.php';
}

function getChatbotUrl($admin_id) {
    global $pdo; 
    
    // Tabela 'adm' conforme seu banco
    $stmt = $pdo->prepare("SELECT chatbot_token FROM adm WHERE id = ?");
    $stmt->execute([$admin_id]);
    $token = $stmt->fetchColumn();

    if (!$token) {
        $token = bin2hex(random_bytes(32));
        $stmt_update = $pdo->prepare("UPDATE adm SET chatbot_token = ? WHERE id = ?");
        $stmt_update->execute([$token, $admin_id]);
    }
    
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
    return $protocol . "://" . $_SERVER['HTTP_HOST'] . "/api/chatbot_office_api.php?key=" . $token;
}

function addChatBotRule($admin_id, $rule_type, $rule_action, $response, $messages) {
    global $pdo;
    $stmt = $pdo->prepare("INSERT INTO chatbot (admin_id, rule_type, rule_action, response, status) VALUES (?, ?, ?, ?, 1)");
    $stmt->execute([$admin_id, $rule_type, $rule_action, $response]);
    $chatbot_id = $pdo->lastInsertId();

    if ($chatbot_id && is_array($messages)) {
        foreach ($messages as $message) {
            if (!empty(trim($message))) {
                $stmt_msg = $pdo->prepare("INSERT INTO chatbot_messages (chatbot_id, admin_id, message) VALUES (?, ?, ?)");
                $stmt_msg->execute([$chatbot_id, $admin_id, trim($message)]);
            }
        }
    }
    return $chatbot_id;
}

function updateChatBotRule($admin_id, $rule_id, $rule_type, $rule_action, $response, $messages) {
    global $pdo;
    $check = $pdo->prepare("SELECT id FROM chatbot WHERE id = ? AND admin_id = ?");
    $check->execute([$rule_id, $admin_id]);
    if(!$check->fetch()) return false;

    $stmt = $pdo->prepare("UPDATE chatbot SET rule_type = ?, rule_action = ?, response = ? WHERE id = ?");
    $stmt->execute([$rule_type, $rule_action, $response, $rule_id]);
    
    $stmt_del = $pdo->prepare("DELETE FROM chatbot_messages WHERE chatbot_id = ?");
    $stmt_del->execute([$rule_id]);

    if(is_array($messages)){
        foreach ($messages as $message) {
            if (!empty(trim($message))) {
                $stmt_msg = $pdo->prepare("INSERT INTO chatbot_messages (chatbot_id, admin_id, message) VALUES (?, ?, ?)");
                $stmt_msg->execute([$rule_id, $admin_id, trim($message)]);
            }
        }
    }
    return true;
}

function deleteChatBotRule($admin_id, $rule_id) {
    global $pdo;
    $stmt = $pdo->prepare("DELETE FROM chatbot WHERE id = ? AND admin_id = ?");
    $stmt->execute([$rule_id, $admin_id]);
    $stmt_msg = $pdo->prepare("DELETE FROM chatbot_messages WHERE chatbot_id = ?");
    $stmt_msg->execute([$rule_id]);
    return true;
}

function getAllChatbotRulesByAdmin($admin_id) {
     global $pdo;
     $stmt = $pdo->prepare("SELECT * FROM chatbot WHERE admin_id = ? ORDER BY id DESC");
     $stmt->execute([$admin_id]);
     $rules = $stmt->fetchAll(PDO::FETCH_ASSOC);

     foreach ($rules as $key => $rule) {
        $stmt_msg = $pdo->prepare("SELECT message FROM chatbot_messages WHERE chatbot_id = ?");
        $stmt_msg->execute([$rule['id']]);
        $rules[$key]['messages'] = $stmt_msg->fetchAll(PDO::FETCH_COLUMN);
     }
     return $rules;
}

function getChatbotRuleById($rule_id, $admin_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM chatbot WHERE id = ? AND admin_id = ?");
    $stmt->execute([$rule_id, $admin_id]);
    $rule = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($rule) {
        $stmt_msg = $pdo->prepare("SELECT message FROM chatbot_messages WHERE chatbot_id = ?");
        $stmt_msg->execute([$rule_id]);
        $rule['messages'] = $stmt_msg->fetchAll(PDO::FETCH_COLUMN);
    }
    return $rule;
}
?>
