<?php

use App\Http\Controllers\DashboardController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\DepartmentController;
use App\Http\Controllers\ClientController;
use App\Http\Controllers\VisitController;
use App\Http\Controllers\LeaveRequestController;
use App\Http\Controllers\PayrollController;
use App\Http\Controllers\ReportController;
use App\Http\Controllers\GPSTrackerController;
use App\Http\Controllers\SettingController;
use App\Http\Controllers\LiveTrackingController; 
use App\Http\Controllers\EmployeeDashboardController;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;

// Redirect root to login
Route::get('/', function () {
    return redirect('/login');
});

// Include auth routes
require __DIR__.'/auth.php';

// All routes that require authentication
Route::middleware(['auth'])->group(function () {
    // Dashboard - Role-based redirection handled in LoginController
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    
    // Employee Dashboard
    Route::get('/employee-dashboard', [EmployeeDashboardController::class, 'index'])->name('employee.dashboard');

    // Admin only routes
    Route::middleware(['role:admin'])->group(function () {
        // Users Management
        Route::resource('users', UserController::class);
        Route::post('/users/{user}/deactivate', [UserController::class, 'deactivate'])->name('users.deactivate');
        Route::post('/users/{user}/activate', [UserController::class, 'activate'])->name('users.activate');
        
        // Departments Management
        Route::resource('departments', DepartmentController::class);
        
        // Settings Management
        Route::prefix('settings')->group(function () {
            Route::get('/', [SettingController::class, 'index'])->name('settings.index');
            Route::put('/', [SettingController::class, 'update'])->name('settings.update');
            Route::post('/seed', [SettingController::class, 'seedDefaultSettings'])->name('settings.seed');
            Route::post('/test-email', [SettingController::class, 'testEmail'])->name('settings.test-email');
            Route::post('/clear-cache', [SettingController::class, 'clearCache'])->name('settings.clear-cache');
        });
        
        // Clients Management
        Route::resource('clients', ClientController::class);
        Route::get('/clients/cities', [ClientController::class, 'getCities'])->name('clients.cities');
        Route::post('/clients/search-location', [ClientController::class, 'searchLocation'])->name('clients.search-location');
        
        // Payroll Management
        Route::resource('payrolls', PayrollController::class);
        Route::post('/payrolls/{payroll}/process', [PayrollController::class, 'process'])->name('payrolls.process');
        Route::post('/payrolls/{payroll}/mark-paid', [PayrollController::class, 'markAsPaid'])->name('payrolls.mark-paid');
        Route::post('/payrolls/generate', [PayrollController::class, 'generate'])->name('payrolls.generate');
        Route::get('/payrolls/employee-salary', [PayrollController::class, 'getEmployeeSalary'])->name('payrolls.employee-salary');
        
        // Reports
        Route::get('/reports', [ReportController::class, 'index'])->name('reports.index');
        Route::post('/reports/generate', [ReportController::class, 'generate'])->name('reports.generate');
        Route::get('/reports/dashboard-stats', [ReportController::class, 'dashboardStats'])->name('reports.dashboard-stats');
        Route::get('/reports/filters/{reportType}', [ReportController::class, 'getFilters'])->name('reports.filters');
    });

    // Admin and Supervisor routes
    Route::middleware(['role:admin|supervisor'])->group(function () {
        // Additional routes that admins and supervisors can access
        Route::get('/supervisor/visits', [VisitController::class, 'supervisorVisits'])->name('visits.supervisor');
        Route::get('/supervisor/employees', [UserController::class, 'supervisorEmployees'])->name('users.supervisor');
    });

    // Visits Management - Accessible to all authenticated users with restrictions
    Route::prefix('visits')->group(function () {
        Route::get('/', [VisitController::class, 'index'])->name('visits.index');
        Route::get('/create', [VisitController::class, 'create'])->name('visits.create');
        Route::post('/', [VisitController::class, 'store'])->name('visits.store');
        Route::get('/{visit}', [VisitController::class, 'show'])->name('visits.show');
        
        // Edit and update only for admin/supervisor or the assigned employee
        Route::middleware(['can:update,visit'])->group(function () {
            Route::get('/{visit}/edit', [VisitController::class, 'edit'])->name('visits.edit');
            Route::put('/{visit}', [VisitController::class, 'update'])->name('visits.update');
        });
        
        // Delete only for admin
        Route::middleware(['role:admin'])->delete('/{visit}', [VisitController::class, 'destroy'])->name('visits.destroy');
        
        // Employee-specific routes
        Route::get('/my/visits', [VisitController::class, 'myVisits'])->name('visits.my-visits');
        Route::post('/{visit}/start', [VisitController::class, 'startVisit'])->name('visits.start')->middleware('can:start,visit');
        Route::post('/{visit}/complete', [VisitController::class, 'completeVisit'])->name('visits.complete')->middleware('can:complete,visit');
        
        Route::get('/client-data', [VisitController::class, 'getClientData'])->name('visits.client-data');
    });

    // Leave Management
    Route::prefix('leaves')->group(function () {
        Route::get('/', [LeaveRequestController::class, 'index'])->name('leaves.index');
        Route::get('/create', [LeaveRequestController::class, 'create'])->name('leaves.create');
        Route::post('/', [LeaveRequestController::class, 'store'])->name('leaves.store');
        Route::get('/my-leaves', [LeaveRequestController::class, 'myLeaves'])->name('leaves.my-leaves');
        
        // Approve/Reject only for admin/supervisor
        Route::middleware(['role:admin|supervisor'])->group(function () {
            Route::post('/{leaveRequest}/approve', [LeaveRequestController::class, 'approve'])->name('leaves.approve');
            Route::post('/{leaveRequest}/reject', [LeaveRequestController::class, 'reject'])->name('leaves.reject');
        });
        
        // Delete only for admin or the owner
        Route::middleware(['can:delete,leaveRequest'])->delete('/{leaveRequest}', [LeaveRequestController::class, 'destroy'])->name('leaves.destroy');
    });

    // GPS Tracking Routes - Accessible to all authenticated users
    Route::prefix('gps')->group(function () {
        Route::get('/track/{visit}', [GPSTrackerController::class, 'trackVisit'])->name('gps.track');
        Route::post('/{visit}/update-location', [GPSTrackerController::class, 'updateLocation'])->name('gps.update-location');
        Route::get('/{visit}/location', [GPSTrackerController::class, 'getVisitLocation'])->name('gps.location');
        Route::get('/{visit}/route-history', [GPSTrackerController::class, 'getRouteHistory'])->name('gps.route-history');
        Route::post('/{visit}/proximity', [GPSTrackerController::class, 'calculateProximity'])->name('gps.proximity');
        Route::post('/{visit}/auto-complete', [GPSTrackerController::class, 'autoCompleteVisit'])->name('gps.auto-complete');
        Route::get('/active-visits/map', [GPSTrackerController::class, 'activeVisitsMap'])->name('gps.active-map');
        Route::get('/active-visits', [GPSTrackerController::class, 'getActiveVisits'])->name('gps.active-visits');
    });

    // LIVE TRACKING ROUTES - Accessible to all authenticated users with data filtering
    Route::prefix('live-tracking')->group(function () {
        Route::get('/', [LiveTrackingController::class, 'index'])->name('live-tracking.index');
        Route::get('/map', [LiveTrackingController::class, 'map'])->name('live-tracking.map');
        Route::get('/employees', [LiveTrackingController::class, 'employees'])->name('live-tracking.employees');
        Route::get('/employee/{employee}/location', [LiveTrackingController::class, 'getEmployeeLocation'])->name('live-tracking.employee-location');
        Route::get('/employee/{employee}/route', [LiveTrackingController::class, 'getEmployeeRoute'])->name('live-tracking.employee-route');
        Route::get('/active-employees', [LiveTrackingController::class, 'getActiveEmployees'])->name('live-tracking.active-employees');
        Route::get('/history/{employee}', [LiveTrackingController::class, 'history'])->name('live-tracking.history');
        Route::get('/alerts', [LiveTrackingController::class, 'alerts'])->name('live-tracking.alerts');
    });

    // Profile routes - Accessible to all authenticated users
    Route::prefix('profile')->group(function () {
        Route::get('/', function () {
            $user = Auth::user();
            return view('profile.index', compact('user'));
        })->name('profile.index');
        
        Route::get('/edit', function () {
            $user = Auth::user();
            return view('profile.edit', compact('user'));
        })->name('profile.edit');
        
        Route::put('/', function (Request $request) {
            $user = Auth::user();
            
            $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'required|string|email|max:255|unique:users,email,' . $user->id,
                'phone' => 'nullable|string|max:20',
                'address' => 'nullable|string|max:500',
            ]);
            
            $user->update($request->only(['name', 'email', 'phone', 'address']));
            
            return redirect()->route('profile.index')->with('success', 'Profile updated successfully.');
        })->name('profile.update');
        
        Route::get('/change-password', function () {
            return view('profile.change-password');
        })->name('profile.change-password');
        
        Route::post('/change-password', function (Request $request) {
            $request->validate([
                'current_password' => 'required|current_password',
                'password' => 'required|string|min:8|confirmed',
            ]);
            
            $user = Auth::user();
            $user->update([
                'password' => bcrypt($request->password),
            ]);
            
            return redirect()->route('profile.index')->with('success', 'Password changed successfully.');
        })->name('profile.update-password');
    });

    // Logout route
    Route::post('/logout', function (Request $request) {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/login');
    })->name('logout');
});

// Health check route
Route::get('/up', function () {
    return response()->json(['status' => 'ok', 'timestamp' => now()]);
});

// Fallback route for 404 errors
Route::fallback(function () {
    if (Auth::check()) {
        $user = Auth::user();
        if ($user->isAdmin() || $user->isSupervisor()) {
            return redirect()->route('dashboard');
        } else {
            return redirect()->route('employee.dashboard');
        }
    }
    return redirect('/login');
});