<?php

namespace Bot\Database;

trait ChatDbTrait
{

    public function getLeaderChannel($chatId)
    {
        $stmt = $this->mysqli->prepare("SELECT channel FROM explorers WHERE chat_id = ?");
        $stmt->bind_param("i", $chatId);
        $stmt->execute();
        $result = $stmt->get_result();
        $leader = $result->fetch_assoc();
        $stmt->close();

        return $leader['channel'];
    }


    public function getLeaderGroup($chatId)
    {
        $stmt = $this->mysqli->prepare("SELECT group_link FROM explorers WHERE chat_id = ?");
        $stmt->bind_param("i", $chatId);
        $stmt->execute();
        $result = $stmt->get_result();
        $leader = $result->fetch_assoc();
        $stmt->close();

        return $leader['group_link'];
    }


    public function registerLeaderChat($chatId, $leaderId, $title, $username, $type): bool
    {
        $stmt = $this->mysqli->prepare("INSERT INTO leader_chats (chat_id, leader_id, title, username, type) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE title = VALUES(title), username = VALUES(username)");
        $stmt->bind_param("iisss", $chatId, $leaderId, $title, $username, $type);
        $success = $stmt->execute();
        $stmt->close();
        return $success;
    }


    public function getLeaderChats($leaderId): array
    {
        $stmt = $this->mysqli->prepare("SELECT * FROM leader_chats WHERE leader_id = ?");
        $stmt->bind_param("i", $leaderId);
        $stmt->execute();
        $res = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        return $res;
    }


    public function getExplorerChannel(int $chatId): ?string
    {
        $stmt = $this->mysqli->prepare("SELECT channel FROM explorers WHERE chat_id = ? AND deleted = 0 LIMIT 1");
        $stmt->bind_param("i", $chatId);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($row = $result->fetch_assoc()) {
            return !empty($row['channel']) ? $row['channel'] : null;
        }

        return null;
    }


    public function getExplorerGroup(int $chatId): ?string
    {
        $stmt = $this->mysqli->prepare("SELECT group_link FROM explorers WHERE chat_id = ? AND deleted = 0 LIMIT 1");
        $stmt->bind_param("i", $chatId);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($row = $result->fetch_assoc()) {
            return !empty($row['group_link']) ? $row['group_link'] : null;
        }

        return null;
    }


    public function getChatIdByUsername($username)
    {
        $stmt = $this->mysqli->prepare("SELECT chat_id FROM users WHERE username = ?");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $stmt->bind_result($chatId);
        $result = $stmt->fetch() ? $chatId : null;
        $stmt->close();
        return $result;
    }

}
