<?php

use App\Http\Controllers\Admin\DashboardController as AdminDashboardController;
use App\Http\Controllers\Admin\SettingsController as AdminSettingsController;
use App\Http\Controllers\Admin\SubscriptionManagementController as AdminSubscriptionController;
use App\Http\Controllers\Admin\SubscriptionPlanController as AdminSubscriptionPlanController;
use App\Http\Controllers\Auth\RegisterController;
use App\Http\Controllers\AssignmentController;
use App\Http\Controllers\OnboardingController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\SubscriptionController;
use App\Http\Controllers\WeeklyPlannerController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

// Home - Landing page for guests, redirect to app for authenticated users
Route::get('/', function () {
    if (Auth::check()) {
        // Redirect admins to admin dashboard, regular users to weekly planner
        if (Auth::user()->isAdmin()) {
            return redirect()->route('admin.dashboard');
        }
        return redirect()->route('weekly-planner');
    }
    return view('welcome');
});

// Authentication routes
Route::middleware('guest')->group(function () {
    Route::get('/register', [RegisterController::class, 'showRegistrationForm'])->name('register');
    Route::post('/register', [RegisterController::class, 'register']);
    Route::get('/login', function () {
        return view('auth.login');
    })->name('login');
    Route::post('/login', function (\Illuminate\Http\Request $request) {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        if (Auth::attempt($credentials, $request->boolean('remember'))) {
            $request->session()->regenerate();
            
            $user = Auth::user();
            
            // Redirect admins to admin dashboard
            if ($user->isAdmin()) {
                return redirect()->route('admin.dashboard');
            }
            
            if (!$user->preferences || !$user->preferences->onboarding_completed) {
                return redirect()->route('onboarding.start');
            }

            return redirect()->route('weekly-planner');
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ])->onlyInput('email');
    });
    
    // Admin login (separate route)
    Route::get('/admin', function () {
        return view('admin.login');
    })->name('admin.login');
    
    Route::post('/admin', function (\Illuminate\Http\Request $request) {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        if (Auth::attempt($credentials, $request->boolean('remember'))) {
            $request->session()->regenerate();
            
            $user = Auth::user();
            
            // Only allow admin users to login via admin route
            if (!$user->isAdmin()) {
                Auth::logout();
                return back()->withErrors([
                    'email' => 'Access denied. Admin privileges required.',
                ])->onlyInput('email');
            }
            
            // Redirect to admin dashboard
            return redirect()->route('admin.dashboard');
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ])->onlyInput('email');
    });
});

Route::post('/logout', function (\Illuminate\Http\Request $request) {
    $wasAdmin = Auth::check() && Auth::user()->isAdmin();
    Auth::logout();
    $request->session()->invalidate();
    $request->session()->regenerateToken();
    
    // Redirect admins back to admin login, regular users to home
    if ($wasAdmin) {
        return redirect()->route('admin.login');
    }
    return redirect('/');
})->name('logout');

// Authenticated routes
Route::middleware('auth')->group(function () {
    // Weekly Planner (default landing)
    Route::get('/weekly-planner', [WeeklyPlannerController::class, 'index'])->name('weekly-planner');

    // Onboarding routes
    Route::prefix('onboarding')->name('onboarding.')->group(function () {
        Route::get('/start', [OnboardingController::class, 'start'])->name('start');
        Route::post('/validate-stress', [OnboardingController::class, 'validateStress'])->name('validate-stress');
        Route::get('/personalize', [OnboardingController::class, 'personalize'])->name('personalize');
        Route::post('/personalize', [OnboardingController::class, 'savePersonalization'])->name('save-personalization');
        Route::get('/create-first-assignment', [OnboardingController::class, 'createFirstAssignment'])->name('create-first-assignment');
    });

    // Assignment routes
    Route::resource('assignments', AssignmentController::class);
    Route::post('/assignments/{assignment}/complete', [AssignmentController::class, 'complete'])->name('assignments.complete');

    // Profile routes
    Route::prefix('profile')->name('profile.')->group(function () {
        Route::get('/', [ProfileController::class, 'show'])->name('show');
        Route::put('/', [ProfileController::class, 'update'])->name('update');
        Route::put('/password', [ProfileController::class, 'updatePassword'])->name('update-password');
        Route::put('/preferences', [ProfileController::class, 'updatePreferences'])->name('update-preferences');
        Route::put('/cancel-subscription', [ProfileController::class, 'cancelSubscription'])->name('cancel-subscription');
    });

    // Subscription routes
    Route::prefix('subscription')->name('subscription.')->group(function () {
        Route::get('/', [SubscriptionController::class, 'index'])->name('index');
        Route::post('/select-plan', [SubscriptionController::class, 'selectPlan'])->name('select-plan');
        Route::post('/upgrade', [SubscriptionController::class, 'upgrade'])->name('upgrade'); // Legacy route
    });

    // Notifications (in-app)
    Route::get('/notifications', function () {
        $notifications = Auth::user()->appNotifications()
            ->orderBy('created_at', 'desc')
            ->paginate(20);
        
        return view('notifications.index', compact('notifications'));
    })->name('notifications.index');

    Route::post('/notifications/{notification}/read', function (\App\Models\AppNotification $notification) {
        if ($notification->user_id !== Auth::id()) {
            abort(403);
        }
        $notification->markAsRead();
        return back();
    })->name('notifications.read');

    // API routes for notifications (for AJAX polling)
    Route::prefix('api')->name('api.')->group(function () {
        Route::get('/notifications/unread-count', function () {
            return response()->json([
                'count' => Auth::user()->appNotifications()->unread()->count()
            ]);
        })->name('notifications.unread-count');

        Route::get('/notifications/latest', function () {
            $notification = Auth::user()->appNotifications()
                ->unread()
                ->latest()
                ->first();

            if (!$notification) {
                return response()->json(['notification' => null]);
            }

            return response()->json([
                'notification' => [
                    'id' => $notification->id,
                    'title' => $notification->title,
                    'message' => $notification->message,
                    'url' => $notification->assignment 
                        ? route('assignments.show', $notification->assignment)
                        : route('notifications.index')
                ]
            ]);
        })->name('notifications.latest');

        // Device token registration for mobile push notifications
        Route::post('/device-tokens/register', [\App\Http\Controllers\Api\DeviceTokenController::class, 'register'])->name('device-tokens.register');
        Route::post('/device-tokens/unregister', [\App\Http\Controllers\Api\DeviceTokenController::class, 'unregister'])->name('device-tokens.unregister');
    });

    // Admin routes
    Route::prefix('admin')->name('admin.')->middleware('admin')->group(function () {
        Route::get('/dashboard', [AdminDashboardController::class, 'index'])->name('dashboard');
        
        // User Management
        Route::get('/users', [AdminDashboardController::class, 'users'])->name('users');
        Route::get('/users/{user}', [AdminDashboardController::class, 'showUser'])->name('users.show');
        Route::post('/users/{user}/toggle-admin', [AdminDashboardController::class, 'toggleAdmin'])->name('users.toggle-admin');
        
        // System Settings
        Route::get('/settings', [AdminSettingsController::class, 'index'])->name('settings');
        Route::put('/settings', [AdminSettingsController::class, 'update'])->name('settings.update');
        Route::post('/settings/test-whatsapp', [AdminSettingsController::class, 'testWhatsApp'])->name('settings.test-whatsapp');
        
        // Subscription Management
        Route::prefix('subscriptions')->name('subscriptions.')->group(function () {
            Route::get('/', [AdminSubscriptionController::class, 'index'])->name('index');
            Route::get('/{user}', [AdminSubscriptionController::class, 'show'])->name('show');
            Route::put('/{user}/status', [AdminSubscriptionController::class, 'updateStatus'])->name('update-status');
            Route::post('/{user}/extend-trial', [AdminSubscriptionController::class, 'extendTrial'])->name('extend-trial');
            Route::post('/{user}/grant-paid', [AdminSubscriptionController::class, 'grantPaid'])->name('grant-paid');
            Route::post('/{user}/revoke', [AdminSubscriptionController::class, 'revokeSubscription'])->name('revoke');
        });

        // Subscription Plans CRUD
        Route::resource('subscription-plans', AdminSubscriptionPlanController::class)->except(['show']);
        Route::get('/subscription-plans/{subscriptionPlan}', [AdminSubscriptionPlanController::class, 'show'])->name('subscription-plans.show');
    });
});
