<?php

namespace App\Models;

use CodeIgniter\Model;

class Groups extends Model
{
    /**
     * table name
     * @var string
     */
    protected $table = 'groups';
    protected $primaryKey = 'id'; // Primary key of your table
    protected $allowedFields = ['group_name', 'permission']; // Fields allowed for insert/update
    protected $useTimestamps = false; // Set to true if your table has `created_at` and `updated_at` columns


    /**
     * Get group data by groupId or all (excluding id = 1)
     * @param mixed $groupId
     * @return array|object|null
     */
    public function getGroupData($groupId = null)
    {
        if ($groupId) {
            return $this->find($groupId); // Find by id
        }

        return $this->where('id !=', 1)->findAll(); // Get all groups except where id = 1
    }

    /**
     * Create new group
     * @param mixed $data
     * @return bool|int|string
     */
    public function createGroup($data)
    {
        return $this->insert($data); // Insert data into the groups table
    }

    /**
     * Edit group by id
     * @param mixed $data
     * @param mixed $id
     * @return bool
     */
    public function editGroup($data, $id)
    {
        return $this->update($id, $data); // Update group by id
    }

    /**
     * Delete group by id
     * @param mixed $id
     * @return bool|\CodeIgniter\Database\BaseResult
     */
    public function deleteGroup($id)
    {
        return $this->delete($id); // Delete group by id
    }

    /**
     * Check if group exists in user_group table
     * @param mixed $id
     * @return bool
     */
    public function existInUserGroup($id)
    {
        return $this->db->table('user_group')->where('group_id', $id)->countAllResults() > 0;
    }

    /**
     * Get user group by userId
     * @param mixed $userId
     * @return array|null
     */
    public function getUserGroupByUserId($userId)
    {
        return $this->db->table('user_group')
            ->join('groups', 'groups.id = user_group.group_id')
            ->where('user_group.user_id', $userId)
            ->get()
            ->getRowArray();
    }
}