<?php

namespace App\Controllers\View;
use App\Controllers\BaseController;
use App\Models\UserRoleModel;
use App\Models\ConfigurationModel;
use CodeIgniter\Controller;
use App\Models\RoleModel;

class RoleSwitcherController extends BaseController
{
    protected $db;
    protected $configModel;
    protected $semester;
    protected $schoolYear;
    protected $userRoleModel;

    public function __construct()
    {
                // Load the database service
        $this->db = \Config\Database::connect();
        // Check if the database connection is established
        if (!$this->db->connect()) {
            log_message('error', 'Database connection failed.');
            throw new \Exception('Database connection failed.');
        } else {
            log_message('info', 'Database connection successful.');
        }
        $this->configModel = new ConfigurationModel(); 
        $this->userRoleModel = new UserRoleModel();
        $this->semester = $this->configModel->getConfig('semester');
        $this->schoolYear = $this->configModel->getConfig('school_year');
    }

    public function index()
    {
        $userId = session()->get('user_id');

        if (!$userId) {
            return redirect()->to('/login')->with('error', 'Please log in first.');
        }
        $roles = $this->userRoleModel
            ->select('roles.name')
            ->join('roles', 'roles.id = user_roles.role_id')
            ->where('user_roles.user_id', $userId)
            ->findAll();

        if (empty($roles)) {
            return redirect()->back()->with('error', 'No roles assigned to this user.');
        }

        $roleNames = array_column($roles, 'name');

        if (count($roleNames) === 1) {
            return $this->redirectToDashboard($roleNames[0]);
        }

        return view('account/choose_account', ['roles' => $roleNames]);
    }

    public function switchTo($role)
    {
        session()->set('active_role', $role);
        return $this->redirectToDashboard($role);
    }

/*
    private function redirectToDashboard($role)
    {
        return match ($role) {
            'administrator'        => redirect()->to('administrator/administratordashboard'),
            'administrative staff' => redirect()->to('/landing_page/admin_dashboard'),
            'teacher'              => redirect()->to('/teacher_dashboard'),
            'student'              => redirect()->to('/landing_page/student_dashboard'),
            'parent'               => redirect()->to('/parent_dashboard'),
            'head_of_department' => redirect()->to('/hod/dashboard'),
            default              => redirect()->to('/')->with('error', 'Unknown role.'),
        };
    }
*/


private function redirectToDashboard($role)
{
    $key = is_string($role) ? $role : (string) $role;

    $route = (new RoleModel())->getRouteByNameOrSlug($key)
          ?? '/landing_page/guest_dashboard';

    log_message('debug', 'Redirecting user to: ' . $route);
    return redirect()->to($route);
}

}
