<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    /**
     * Show the main dashboard (redirects to role-based dashboard).
     */
    public function index()
    {
        $user = Auth::user();
        
        if (!$user) {
            return redirect()->route('login')->with('error', 'Please log in to access the dashboard.');
        }
        
        // Redirect to role-based dashboard
        return redirect()->route($this->getRoleBasedRoute($user->role));
    }

    /**
     * Show the doctor dashboard.
     */
    public function doctorDashboard(Request $request)
    {
        $user = Auth::user();
        
        // Check if user has doctor or receptionist role
        if (!$user || !in_array($user->role, ['doctor', 'receptionist'])) {
            abort(403, 'Access denied. Doctor privileges required.');
        }
        
        return view('dashboard');
    }

    /**
     * Show the patient dashboard.
     */
    public function patientDashboard()
    {
        $user = Auth::user();
        
        if (!$user || $user->role !== 'patient') {
            abort(403, 'Access denied. Patient privileges required.');
        }
        
        return view('dashboard');
    }

    /**
     * Show the admin dashboard.
     */
    public function adminDashboard()
    {
        $user = Auth::user();
        
        if (!$user || $user->role !== 'hospital_admin') {
            abort(403, 'Access denied. Admin privileges required.');
        }
        
        return view('dashboard');
    }

    /**
     * Show the nurse dashboard.
     */
    public function nurseDashboard()
    {
        $user = Auth::user();
        
        if (!$user || $user->role !== 'nurse') {
            abort(403, 'Access denied. Nurse privileges required.');
        }
        
        return view('dashboard');
    }

    /**
     * Get the role-based dashboard route name.
     */
    private function getRoleBasedRoute($role)
    {
        $routes = [
            'doctor' => 'doctor.dashboard',
            'patient' => 'patient.dashboard',
            'hospital_admin' => 'admin.dashboard',
            'nurse' => 'nurse.dashboard',
            'receptionist' => 'doctor.dashboard', // Receptionist uses doctor dashboard
        ];

        return $routes[$role] ?? 'patient.dashboard';
    }
}