<?php

use App\Http\Controllers\Admin\AdminAuthController;
use App\Http\Controllers\Admin\SponsorController;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;

// Redirect root to admin dashboard (which guards via AdminMiddleware or redirects to login)
Route::get('/', function () {
    return redirect()->route('admin.dashboard');
});

// Admin Auth Routes
Route::get('/admin/login', [AdminAuthController::class, 'showLogin'])->name('admin.login');
Route::post('/admin/login', [AdminAuthController::class, 'login'])->name('admin.login.submit');
Route::post('/admin/logout', [AdminAuthController::class, 'logout'])->name('admin.logout');




// Admin Protected Routes
Route::prefix('admin')->middleware(['admin'])->group(function () {
    Route::get('/dashboard', [\App\Http\Controllers\Admin\DashboardController::class, 'index'])->name('admin.dashboard');
    Route::post('/verifications/approve', [\App\Http\Controllers\Admin\DashboardController::class, 'approveVerification'])->name('admin.verifications.approve');
    Route::post('/verifications/reject', [\App\Http\Controllers\Admin\DashboardController::class, 'rejectVerification'])->name('admin.verifications.reject');

    Route::get('/workers', [\App\Http\Controllers\Admin\WorkerController::class, 'index'])->name('admin.workers');
    Route::post('/workers/{worker}/toggle-status', [\App\Http\Controllers\Admin\WorkerController::class, 'toggleStatus'])->name('admin.workers.toggle-status');
    Route::post('/workers/{worker}/availability-override', [\App\Http\Controllers\Admin\WorkerController::class, 'availabilityOverride'])->name('admin.workers.availability-override');
    Route::post('/workers/{worker}/flag-fraud', [\App\Http\Controllers\Admin\WorkerController::class, 'flagFraud'])->name('admin.workers.flag-fraud');
    Route::post('/workers/{worker}/update-profile', [\App\Http\Controllers\Admin\WorkerController::class, 'updateProfile'])->name('admin.workers.update-profile');
    
    Route::get('/workers/verifications', [\App\Http\Controllers\Admin\WorkerVerificationController::class, 'index'])->name('admin.workers.verifications');
    Route::post('/workers/{worker}/verify', [\App\Http\Controllers\Admin\WorkerVerificationController::class, 'verify'])->name('admin.workers.verify');

    Route::get('/employers', [SponsorController::class, 'index'])->name('admin.employers');
    Route::post('/employers/{id}/verify', [SponsorController::class, 'verify'])->name('admin.employers.verify');
    Route::post('/employers/{id}/suspend', [SponsorController::class, 'suspend'])->name('admin.employers.suspend');
    Route::post('/employers/{id}/activate', [SponsorController::class, 'activate'])->name('admin.employers.activate');
    Route::post('/employers/{id}/update', [SponsorController::class, 'update'])->name('admin.employers.update');
    Route::delete('/employers/{id}', [SponsorController::class, 'delete'])->name('admin.employers.delete');

    Route::get('/subscriptions', function () {
        return Inertia::render('Admin/Subscriptions/Index');
    })->name('admin.subscriptions');

    Route::get('/payments', function () {
        return Inertia::render('Admin/Payments/Index');
    })->name('admin.payments');

    Route::post('/payments/{id}/refund', [\App\Http\Controllers\Admin\AdminExtraController::class, 'refundPayment'])->name('admin.payments.refund');

    Route::get('/master-data/categories', function () {
        return Inertia::render('Admin/MasterData/WorkerCategories');
    })->name('admin.categories');

    Route::get('/announcements', function () {
        return Inertia::render('Admin/Announcements/Index');
    })->name('admin.announcements');

    // New Modules Added
    Route::get('/safety', [\App\Http\Controllers\Admin\AdminExtraController::class, 'safety'])->name('admin.safety');
    Route::post('/safety/reports/{id}/resolve', [\App\Http\Controllers\Admin\AdminExtraController::class, 'resolveSafetyReport'])->name('admin.safety.resolve-report');
    
    Route::get('/disputes', [\App\Http\Controllers\Admin\AdminExtraController::class, 'disputes'])->name('admin.disputes');
    Route::post('/disputes/{id}/resolve', [\App\Http\Controllers\Admin\AdminExtraController::class, 'resolveDispute'])->name('admin.disputes.resolve');
    Route::post('/disputes/{id}/add-note', [\App\Http\Controllers\Admin\AdminExtraController::class, 'addDisputeNote'])->name('admin.disputes.add-note');

    Route::get('/notifications', [\App\Http\Controllers\Admin\AdminExtraController::class, 'notifications'])->name('admin.notifications');
    Route::post('/notifications/broadcast', [\App\Http\Controllers\Admin\AdminExtraController::class, 'broadcastNotification'])->name('admin.notifications.broadcast');

    Route::get('/analytics', [\App\Http\Controllers\Admin\AdminExtraController::class, 'analytics'])->name('admin.analytics');
    Route::get('/audit-logs', [\App\Http\Controllers\Admin\AdminExtraController::class, 'auditLogs'])->name('admin.audit-logs');
});

// Employer Auth Routes
Route::get('/employer/login', [\App\Http\Controllers\Employer\EmployerAuthController::class, 'showLogin'])->name('employer.login');
Route::post('/employer/login', [\App\Http\Controllers\Employer\EmployerAuthController::class, 'login'])->name('employer.login.submit');
Route::get('/employer/register', [\App\Http\Controllers\Employer\EmployerAuthController::class, 'showRegister'])->name('employer.register');
Route::post('/employer/register', [\App\Http\Controllers\Employer\EmployerAuthController::class, 'register'])->name('employer.register.submit');
Route::get('/employer/verify-email', [\App\Http\Controllers\Employer\EmployerAuthController::class, 'showVerifyEmail'])->name('employer.verify-email');
Route::post('/employer/verify-email', [\App\Http\Controllers\Employer\EmployerAuthController::class, 'verifyEmail'])->name('employer.verify-email.submit')->middleware('throttle:5,1');
Route::post('/employer/resend-otp', [\App\Http\Controllers\Employer\EmployerAuthController::class, 'resendOtp'])->name('employer.resend-otp')->middleware('throttle:3,1');
Route::get('/employer/register-payment', [\App\Http\Controllers\Employer\EmployerAuthController::class, 'showRegisterPayment'])->name('employer.register-payment');
Route::post('/employer/register-payment', [\App\Http\Controllers\Employer\EmployerAuthController::class, 'storeRegisterPayment'])->name('employer.register-payment.submit');
Route::get('/employer/create-password', [\App\Http\Controllers\Employer\EmployerAuthController::class, 'showCreatePassword'])->name('employer.create-password');
Route::post('/employer/create-password', [\App\Http\Controllers\Employer\EmployerAuthController::class, 'createPassword'])->name('employer.create-password.submit');
Route::post('/employer/logout', [\App\Http\Controllers\Employer\EmployerAuthController::class, 'logout'])->name('employer.logout');
Route::get('/employer/pending-verification', function () {
    return Inertia::render('Employer/Auth/PendingVerification');
})->name('employer.pending-verification');
Route::get('/employer/forgot-password', function () {
    return Inertia::render('Employer/Auth/ForgotPassword');
})->name('employer.forgot-password');

// Employer Protected Routes
Route::prefix('employer')->middleware(['employer'])->group(function () {
    Route::get('/dashboard', [\App\Http\Controllers\Employer\DashboardController::class, 'index'])->name('employer.dashboard');
    Route::get('/workers', [\App\Http\Controllers\Employer\WorkerController::class, 'index'])->name('employer.workers');
    Route::get('/workers/{id}', [\App\Http\Controllers\Employer\WorkerController::class, 'show'])->name('employer.workers.show');
    Route::get('/workers/{id}/hire', function ($id) {
        $worker = \App\Models\Worker::with('category')->findOrFail($id);
        $workerData = [
            'id' => $worker->id,
            'name' => $worker->name,
            'nationality' => $worker->nationality,
            'category' => $worker->category->name ?? 'General Worker',
            'salary' => (int) $worker->expected_salary,
        ];
        return Inertia::render('Employer/Hiring/Confirm', ['worker' => $workerData]);
    })->name('employer.hiring.confirm');
    Route::post('/workers/{id}/hire', [\App\Http\Controllers\Employer\WorkerController::class, 'sendOffer'])->name('employer.workers.send-offer');
    Route::get('/workers/{id}/hire/success', function ($id) {
        $worker = \App\Models\Worker::findOrFail($id);
        $workerData = [
            'id' => $worker->id,
            'name' => $worker->name,
        ];
        return Inertia::render('Employer/Hiring/Success', ['worker' => $workerData]);
    })->name('employer.hiring.success');

    // Job Management
    Route::get('/jobs', [\App\Http\Controllers\Employer\JobController::class, 'index'])->name('employer.jobs');
    Route::get('/jobs/create', [\App\Http\Controllers\Employer\JobController::class, 'create'])->name('employer.jobs.create');
    Route::post('/jobs/create', [\App\Http\Controllers\Employer\JobController::class, 'store'])->name('employer.jobs.store');
    Route::get('/jobs/{id}/applicants', [\App\Http\Controllers\Employer\JobController::class, 'applicants'])->name('employer.jobs.applicants');
    Route::get('/subscription', function () {
        $sess = session('user');
        $sessId = is_array($sess) ? ($sess['id'] ?? null) : ($sess->id ?? null);
        $user = $sessId ? \App\Models\User::find($sessId) : \App\Models\User::where('role', 'employer')->first();

        $sub = $user ? \Illuminate\Support\Facades\DB::table('subscriptions')->where('user_id', $user->id)->where('status', 'active')->latest('id')->first() : null;
        $expiresAt = $sub && $sub->expires_at ? date('Y-m-d', strtotime($sub->expires_at)) : '2026-12-31';
        $planName = $sub ? (ucfirst($sub->plan_id) . ' Pass') : 'Premium Employer Pass';

        return Inertia::render('Employer/Subscription', [
            'currentPlan' => $planName,
            'expiresAt' => $expiresAt,
            'plans' => [
                [
                    'id' => 'basic',
                    'name' => 'Basic Search',
                    'price' => '99 AED',
                    'period' => 'month',
                    'features' => ['Browse 500+ verified workers', 'Shortlist up to 10 candidates', 'Standard OCR vetting'],
                    'popular' => false,
                ],
                [
                    'id' => 'premium',
                    'name' => 'Premium Employer Pass',
                    'price' => '199 AED',
                    'period' => 'month',
                    'features' => ['Unlimited shortlisting', 'Direct candidate messaging', 'Priority interview scheduling', 'Dedicated support'],
                    'popular' => true,
                ],
                [
                    'id' => 'enterprise',
                    'name' => 'VIP Concierge',
                    'price' => '499 AED',
                    'period' => 'month',
                    'features' => ['All Premium features', 'Assigned recruitment manager', 'Background medical verification guarantee', 'Free replacement within 30 days'],
                    'popular' => false,
                ],
            ]
        ]);
    })->name('employer.subscription');

    Route::get('/messages', [\App\Http\Controllers\Employer\MessageController::class, 'index'])->name('employer.messages');
    Route::get('/messages/{id}', [\App\Http\Controllers\Employer\MessageController::class, 'show'])->name('employer.messages.show');
    Route::post('/messages/{id}/send', [\App\Http\Controllers\Employer\MessageController::class, 'send'])->name('employer.messages.send');
    Route::get('/messages/start/{workerId}', [\App\Http\Controllers\Employer\MessageController::class, 'startConversation'])->name('employer.messages.start');

    Route::get('/shortlist', [\App\Http\Controllers\Employer\ShortlistController::class, 'index'])->name('employer.shortlist');
    Route::post('/shortlist/toggle', [\App\Http\Controllers\Employer\ShortlistController::class, 'toggle'])->name('employer.shortlist.toggle');
    Route::post('/shortlist/{id}/remove', [\App\Http\Controllers\Employer\ShortlistController::class, 'remove'])->name('employer.shortlist.remove');

    Route::get('/candidates', [\App\Http\Controllers\Employer\CandidateController::class, 'index'])->name('employer.candidates');
    Route::post('/candidates/{id}/status', [\App\Http\Controllers\Employer\CandidateController::class, 'updateStatus'])->name('employer.candidates.status');

    Route::get('/announcements', [\App\Http\Controllers\Employer\AnnouncementController::class, 'index'])->name('employer.announcements');
    Route::post('/announcements/create', [\App\Http\Controllers\Employer\AnnouncementController::class, 'store'])->name('employer.announcements.store');

    Route::get('/profile', [\App\Http\Controllers\Employer\ProfileController::class, 'index'])->name('employer.profile');
    Route::post('/profile/update', [\App\Http\Controllers\Employer\ProfileController::class, 'update'])->name('employer.profile.update');
});

Route::get('/api/documentation', function () {
    return view('swagger');
})->name('api.documentation');
