<?php

namespace App\Models;

use App\Utils\Model;
use PDOException;

/**
 * This model is used to manage the zabbix data.
 */
class ZabbixModel extends Model
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Get all username
     */
    public function getUsernamesAndRoleids(): array
    {
        $this->logger->debug('User Name Retrieve From Zabbix DB is started', ['controller' => __METHOD__, 'user' => $_SESSION['userInfo']['userName']]);
        try {
            $this->zabbixdb->query("SELECT username,roleid FROM users");
            $results = $this->zabbixdb->resultSet();
        } catch (PDOException $e) {
            $this->logger->error($e->getMessage(), ['controller' => __METHOD__, 'user' => $_SESSION['userInfo']['userName']]);
            return [];
        }
        $this->logger->debug('User Name Retrieve From Zabbix DB process is finished.', ['controller' => __METHOD__, 'user' => $_SESSION['userInfo']['userName']]);
        return $results;
    }

    /**
     * Get userid and username by userId
     */
    public function getUserById($userId)
    {
        $this->logger->debug('Retrieve userid and username by useId From Zabbix DB is started', ['controller' => __METHOD__, 'user' => $_SESSION['userInfo']['userName']]);
        try {
            $sql = "SELECT userid,username FROM users WHERE userid = :userid";
            $this->zabbixdb->query($sql);
            $this->zabbixdb->bind(':userid', $userId);
            $result = $this->zabbixdb->single();
        } catch (PDOException $e) {
            $this->logger->error($e->getMessage(), ['controller' => __METHOD__, 'user' => $_SESSION['userInfo']['userName']]);
            return null;
        }
        $this->logger->debug('Retrieve userid and username by useId From Zabbix DB is finished.', ['controller' => __METHOD__, 'user' => $_SESSION['userInfo']['userName']]);
        return $result ?: null;
    }

    /**
     * Get user info by username
     */
    public function getUserByName($username)
    {
        $this->logger->debug('Retrieve userid and username by username From Zabbix DB is started', ['controller' => __METHOD__, 'user' => $_SESSION['userInfo']['userName']]);
        try {
            $sql = "SELECT userid, username FROM users WHERE username = :username";
            $this->zabbixdb->query($sql);
            $this->zabbixdb->bind(':username', $username);
            $result = $this->zabbixdb->single();
        } catch (PDOException $e) {
            $this->logger->error($e->getMessage(), ['controller' => __METHOD__, 'user' => $_SESSION['userInfo']['userName']]);
            return null;
        }
        $this->logger->debug('Retrieve userid and username by username From Zabbix DB is finished', ['controller' => __METHOD__, 'user' => $_SESSION['userInfo']['userName']]);
        return $result ?: null;
    }

    /**
     * Get all user ids in same groups (for group-based access)
     */
    public function getGroupUserNames($userId)
    {
        $this->logger->debug('Retrieve User Group Name by userId From Zabbix DB is started', ['controller' => __METHOD__, 'user' => $_SESSION['userInfo']['userName']]);
        try {
            $sql = "SELECT U.username
                FROM users AS U, users_groups AS UG1, users_groups AS UG2
                WHERE U.userid = UG1.userid
                AND UG2.userid = :userid
                AND UG1.usrgrpid = UG2.usrgrpid";
            $this->zabbixdb->query($sql);
            $this->zabbixdb->bind(':userid', $userId);
            $rows = $this->zabbixdb->resultSet();
        } catch (PDOException $e) {
            $this->logger->error($e->getMessage(), ['controller' => __METHOD__, 'user' => $_SESSION['userInfo']['userName']]);
            return [];
        }

        $this->logger->debug('Retrieve User Group Name by userId From Zabbix DB is finished', ['controller' => __METHOD__, 'user' => $_SESSION['userInfo']['userName']]);
        return array_map(fn($row) => $row->username, $rows);
    }

    /**
     * Check if the given user belongs to any group.
     *
     * @param int $userId The user ID to check.
     * @return bool True if the user is in at least one group, false otherwise.
     */
    public function checkUserGroupExist($userId): bool
    {
        $this->logger->debug('Check the given user belongs to any group From Zabbix DB is started', ['controller' => __METHOD__, 'user' => $_SESSION['userInfo']['userName']]);
        try {
            $sql = "SELECT g.usrgrpid, g.name
                FROM users_groups ug
                INNER JOIN usrgrp g ON ug.usrgrpid = g.usrgrpid
                WHERE ug.userid = :userid";
            $this->zabbixdb->query($sql);
            $this->zabbixdb->bind(':userid', $userId);
            $result =  $this->zabbixdb->resultSet();
        } catch (PDOException $e) {
            $this->logger->error($e->getMessage(), ['controller' => __METHOD__, 'user' => $_SESSION['userInfo']['userName']]);
        }
        $this->logger->debug('Check the given user belongs to any group From Zabbix DB is finished', ['controller' => __METHOD__, 'user' => $_SESSION['userInfo']['userName']]);
        return !empty($result);
    }
}
