<?php

namespace App\Controllers\View;

use CodeIgniter\Controller;
use App\Models\RoleModel;

class DashboardRedirectController extends Controller
{
    public function dashboard()
    {
        $session = session();
        $roles = $session->get('roles') ?? [];

        // Fallback: if only a single role is stored
        if (empty($roles) && $session->get('role')) {
            $roles = [$session->get('role')];
        }

        // Use your existing method
        return $this->redirectToDashboard($roles);
    }

    // Your existing function (unchanged)

private function redirectToDashboard(array $roles)
{
    if (empty($roles)) {
        log_message('error', 'Empty roles array passed to redirectToDashboard.');
        return redirect()->to('/landing_page/guest_dashboard');
    }

    $roleModel = new RoleModel();

    // Resolve all candidate roles (by name or slug), ordered by priority ASC
    $rows = $roleModel->findByNamesOrSlugs($roles);

    if (!empty($rows)) {
        $route = $rows[0]['dashboard_route'] ?? '/landing_page/guest_dashboard';
        log_message('debug', 'Redirecting user to: ' . $route);
        return redirect()->to($route);
    }

    log_message('warning', 'No matching role found. Redirecting to guest dashboard.');
    return redirect()->to('/landing_page/guest_dashboard');
}

}