<?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::get('/employers/export', [SponsorController::class, 'export'])->name('admin.employers.export');
    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 () {
        $payments = \Illuminate\Support\Facades\DB::table('payments')
            ->leftJoin('users', 'payments.user_id', '=', 'users.id')
            ->select('payments.*', 'users.name as user_name', 'users.email as user_email')
            ->orderBy('payments.created_at', 'desc')
            ->get()
            ->map(function($payment) {
                return [
                    'id' => 'PAY-' . str_pad($payment->id, 3, '0', STR_PAD_LEFT),
                    'employer' => $payment->user_name ?: 'System Guest / Sponsor',
                    'plan' => $payment->description ?: 'Subscription Plan',
                    'amount' => (float)$payment->amount,
                    'method' => 'Stripe Gateway',
                    'date' => date('Y-m-d', strtotime($payment->created_at)),
                    'status' => $payment->status === 'success' ? 'Completed' : (ucfirst($payment->status) ?: 'Completed'),
                    'period' => date('M Y', strtotime($payment->created_at)) . ' - ' . date('M Y', strtotime($payment->created_at . ' +1 month')),
                ];
            });

        $totalRevenue = \Illuminate\Support\Facades\DB::table('payments')->where('status', 'success')->sum('amount');
        $activeSubs = \Illuminate\Support\Facades\DB::table('sponsors')->where('subscription_status', 'active')->count();
        $failedPayments = \Illuminate\Support\Facades\DB::table('payments')->where('status', 'failed')->count();
        $avgTicket = \Illuminate\Support\Facades\DB::table('payments')->where('status', 'success')->avg('amount') ?: 0;

        $stats = [
            'total_revenue' => number_format($totalRevenue, 2),
            'active_subscriptions' => $activeSubs,
            'failed_payments' => $failedPayments,
            'average_ticket' => number_format($avgTicket, 2),
        ];

        return Inertia::render('Admin/Payments/Index', [
            'payments' => $payments,
            'stats' => $stats
        ]);
    })->name('admin.payments');

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

    Route::get('/master-data/skills', function () {
        $skills = \App\Models\Skill::all()->map(function ($skill) {
            return [
                'id' => $skill->id,
                'name' => $skill->name,
                'image_url' => $skill->image_path ? asset('storage/' . $skill->image_path) : null,
                'worker_count' => \DB::table('worker_skills')->where('skill_id', $skill->id)->count(),
                'status' => 'Active',
            ];
        });
        return Inertia::render('Admin/MasterData/WorkerSkills', [
            'skills' => $skills
        ]);
    })->name('admin.skills');

    Route::post('/master-data/skills', function (\Illuminate\Http\Request $request) {
        $request->validate([
            'name' => 'required|string|max:255|unique:skills,name',
            'image' => 'nullable|image|max:2048',
        ]);
        $imagePath = null;
        if ($request->hasFile('image')) {
            $imagePath = $request->file('image')->store('skills', 'public');
        }
        \App\Models\Skill::create([
            'name' => strtolower($request->name),
            'image_path' => $imagePath,
        ]);
        return redirect()->back();
    })->name('admin.skills.store');

    Route::post('/master-data/skills/{id}/update', function (\Illuminate\Http\Request $request, $id) {
        $request->validate([
            'name' => 'required|string|max:255|unique:skills,name,' . $id,
            'image' => 'nullable|image|max:2048',
        ]);
        $skill = \App\Models\Skill::findOrFail($id);
        $imagePath = $skill->image_path;
        if ($request->hasFile('image')) {
            if ($imagePath) {
                \Storage::disk('public')->delete($imagePath);
            }
            $imagePath = $request->file('image')->store('skills', 'public');
        }
        $skill->update([
            'name' => strtolower($request->name),
            'image_path' => $imagePath,
        ]);
        return redirect()->back();
    })->name('admin.skills.update');

    Route::delete('/master-data/skills/{id}', function ($id) {
        $skill = \App\Models\Skill::findOrFail($id);
        if ($skill->image_path) {
            \Storage::disk('public')->delete($skill->image_path);
        }
        \DB::table('worker_skills')->where('skill_id', $id)->delete();
        $skill->delete();
        return redirect()->back();
    })->name('admin.skills.delete');

    Route::get('/master-data/reasons', function () {
        $reasons = \App\Models\ReportReason::orderBy('id', 'desc')->get()->map(function ($reason) {
            return [
                'id' => $reason->id,
                'reason' => $reason->reason,
                'status' => $reason->status,
                'type' => $reason->type,
            ];
        });
        return Inertia::render('Admin/MasterData/ReportReasons', [
            'reasons' => $reasons
        ]);
    })->name('admin.reasons');

    Route::post('/master-data/reasons', function (\Illuminate\Http\Request $request) {
        $request->validate([
            'reason' => 'required|string|max:255|unique:report_reasons,reason',
            'type' => 'required|string|in:Chat,Review,Both,Support',
        ]);
        \App\Models\ReportReason::create([
            'reason' => $request->reason,
            'type' => $request->type,
            'status' => 'Active',
        ]);
        return redirect()->back();
    })->name('admin.reasons.store');

    Route::post('/master-data/reasons/{id}/update', function (\Illuminate\Http\Request $request, $id) {
        $request->validate([
            'reason' => 'required|string|max:255|unique:report_reasons,reason,' . $id,
            'status' => 'required|string|in:Active,Inactive',
            'type' => 'required|string|in:Chat,Review,Both,Support',
        ]);
        $reason = \App\Models\ReportReason::findOrFail($id);
        $reason->update([
            'reason' => $request->reason,
            'status' => $request->status,
            'type' => $request->type,
        ]);
        return redirect()->back();
    })->name('admin.reasons.update');

    Route::delete('/master-data/reasons/{id}', function ($id) {
        $reason = \App\Models\ReportReason::findOrFail($id);
        $reason->delete();
        return redirect()->back();
    })->name('admin.reasons.delete');

    Route::get('/announcements', [\App\Http\Controllers\Admin\AdminExtraController::class, 'announcements'])->name('admin.announcements');
    Route::post('/announcements/create', [\App\Http\Controllers\Admin\AdminExtraController::class, 'storeAnnouncement'])->name('admin.announcements.store');
    Route::post('/announcements/{id}/approve', [\App\Http\Controllers\Admin\AdminExtraController::class, 'approveAnnouncement'])->name('admin.announcements.approve');
    Route::post('/announcements/{id}/reject', [\App\Http\Controllers\Admin\AdminExtraController::class, 'rejectAnnouncement'])->name('admin.announcements.reject');
    Route::delete('/announcements/{id}', [\App\Http\Controllers\Admin\AdminExtraController::class, 'deleteAnnouncement'])->name('admin.announcements.delete');

    // 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');
    
    // Disputes have been consolidated into Help & Support module
    // 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');

    // Admin Support Tickets
    Route::get('/tickets', [\App\Http\Controllers\Admin\SupportTicketController::class, 'index'])->name('admin.tickets.index');
    Route::get('/tickets/{id}', [\App\Http\Controllers\Admin\SupportTicketController::class, 'show'])->name('admin.tickets.show');
    Route::post('/tickets/{id}/reply', [\App\Http\Controllers\Admin\SupportTicketController::class, 'reply'])->name('admin.tickets.reply');
    Route::post('/tickets/{id}/status', [\App\Http\Controllers\Admin\SupportTicketController::class, 'updateStatus'])->name('admin.tickets.update-status');
    Route::post('/tickets/{id}/generate-dev-response', [\App\Http\Controllers\Admin\SupportTicketController::class, 'generateDevResponse'])->name('admin.tickets.generate-dev-response');
});

// 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');
Route::post('/employer/forgot-password', [\App\Http\Controllers\Employer\EmployerAuthController::class, 'forgotPassword'])->name('employer.forgot-password.submit');
Route::post('/employer/reset-password', [\App\Http\Controllers\Employer\EmployerAuthController::class, 'resetPassword'])->name('employer.reset-password.submit');

// 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::post('/workers/{id}/mark-hired', [\App\Http\Controllers\Employer\WorkerController::class, 'markHired'])->name('employer.workers.mark-hired');
    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 verification'],
                    '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('/payments', [\App\Http\Controllers\Employer\PaymentController::class, 'index'])->name('employer.payments');

    // Employer Support Tickets
    Route::get('/support', [\App\Http\Controllers\Employer\SupportTicketController::class, 'index'])->name('employer.support.index');
    Route::get('/support/create', [\App\Http\Controllers\Employer\SupportTicketController::class, 'create'])->name('employer.support.create');
    Route::post('/support/create', [\App\Http\Controllers\Employer\SupportTicketController::class, 'store'])->name('employer.support.store');
    Route::get('/support/{id}', [\App\Http\Controllers\Employer\SupportTicketController::class, 'show'])->name('employer.support.show');
    Route::post('/support/{id}/reply', [\App\Http\Controllers\Employer\SupportTicketController::class, 'reply'])->name('employer.support.reply');
});

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

Route::redirect('/api/documention', '/api/documentation');

