<?php

namespace App\Models;

use CodeIgniter\Model;

class UserRoleModel extends Model
{
    protected $table = 'user_roles';
    protected $primaryKey = 'id';
    protected $returnType = 'array';

    protected $allowedFields = [
        'user_id',
        'role_id',
        'created_at',
        'updated_at',
        'updated_by',
        'deleted_at'
    ];

    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';
    protected $deletedField = 'deleted_at';

    /**
     * ✅ Fetch all role names assigned to a specific user
     * 
     * @param int $userId
     * @return array Array of roles, e.g., [['name' => 'parent'], ['name' => 'teacher']]
     */
    public function create()
    {
        $users = $this->db->table('users')
            ->select('users.*')
            ->join('user_roles', 'user_roles.user_id = users.id')
            ->join('roles', 'roles.id = user_roles.role_id')
            ->whereNotIn('roles.name', ['parent', 'teacher'])
            ->groupBy('users.id')  // prevent duplicates if user has multiple roles
            ->get()
            ->getResultArray();

        return view('expenses/create', ['users' => $users]);
    }




    /**
     * 🔁 Deprecated: Use getAllRolesByUserId instead
     * Get the first role name by user ID
     * 
     * @param int $userId
     * @return string|null
     */
public function getRolesByUserId(int $userId): array
{
    $roles = $this->select('roles.name as role_name')
                  ->join('roles', 'roles.id = user_roles.role_id')
                  ->where('user_roles.user_id', $userId)
                  ->get()
                  ->getResultArray();

    // Always return an array
    return is_array($roles) ? $roles : [];
}





    /**
     * ✅ Insert or update a role assignment
     *
     * @param int $userId
     * @param int $roleId
     * @return bool|int
     */
    public function updateOrInsertRole($userId, $roleId)
    {
        // Check if this exact (user_id, role_id) already exists
        $exists = $this->where([
            'user_id' => $userId,
            'role_id' => $roleId
        ])->first();

        if ($exists) {
            // Already exists, nothing to do
            return true;
        }

        // Otherwise, insert new user-role mapping
        return $this->insert([
            'user_id'    => $userId,
            'role_id'    => $roleId,
            'updated_by' => session()->get('user_id')
        ]);
    }
}
