<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\File;
use App\Http\Controllers\AuthController;

Route::get('/', function () {
    return redirect()->route('login');
});

// Serve uploaded images so they load in admin and public (works even when document root is not public/)
Route::get('/uploads/{path}', function (string $path) {
    $path = urldecode($path);
    $path = str_replace('\\', '/', $path);
    $path = preg_replace('/\.\./u', '', $path);
    $path = ltrim($path, '/');
    if ($path === '') {
        abort(404);
    }
    $fullPath = public_path('uploads/' . $path);
    $uploadsBase = realpath(public_path('uploads'));
    if (!$uploadsBase) {
        abort(404);
    }
    if (!File::exists($fullPath) || !File::isFile($fullPath)) {
        abort(404);
    }
    $realFull = realpath($fullPath);
    if ($realFull === false || strpos($realFull, $uploadsBase) !== 0) {
        abort(404);
    }
    $mime = match (strtolower(pathinfo($realFull, PATHINFO_EXTENSION))) {
        'jpg', 'jpeg' => 'image/jpeg',
        'png' => 'image/png',
        'gif' => 'image/gif',
        'webp' => 'image/webp',
        'svg' => 'image/svg+xml',
        default => null,
    };
    if ($mime) {
        return response()->file($realFull, ['Content-Type' => $mime, 'Content-Disposition' => 'inline']);
    }
    return response()->file($realFull);
})->where('path', '.*')->name('uploads.serve');

Route::get('/login', [AuthController::class, 'showLogin'])->name('login');
Route::post('/login', [AuthController::class, 'login']);
Route::post('/logout', [AuthController::class, 'logout'])->name('logout');

Route::middleware(['auth'])->prefix('admin')->name('admin.')->group(function () {
    Route::get('/dashboard', function () {
        $stats = [
            'folders' => \App\Models\Folder::count(),
            'images' => \App\Models\Image::count(),
            'products' => \App\Models\Product::count(),
            'services' => \App\Models\Service::count(),
            'blogs' => \App\Models\Blog::count(),
            'orders' => \App\Models\Order::count(),
        ];
            
        $recentOrders = \App\Models\Order::latest()->take(10)->get();
        
        return view('admin.dashboard', compact('stats', 'recentOrders'));
    })->name('dashboard');

    // Pages CMS
    Route::get('/pages/about', [\App\Http\Controllers\Admin\PageCmsController::class, 'about'])->name('pages.about');
    Route::post('/pages/about', [\App\Http\Controllers\Admin\PageCmsController::class, 'updateAbout'])->name('pages.about.update');
    Route::get('/pages/footer', [\App\Http\Controllers\Admin\PageCmsController::class, 'footer'])->name('pages.footer');
    Route::post('/pages/footer', [\App\Http\Controllers\Admin\PageCmsController::class, 'updateFooter'])->name('pages.footer.update');
    Route::get('/pages/contact', [\App\Http\Controllers\Admin\PageCmsController::class, 'contact'])->name('pages.contact');
    Route::post('/pages/contact', [\App\Http\Controllers\Admin\PageCmsController::class, 'updateContact'])->name('pages.contact.update');
    Route::get('/contact/messages', [\App\Http\Controllers\Admin\PageCmsController::class, 'messages'])->name('contact.messages');

    // Image Management
    Route::get('/images', [\App\Http\Controllers\Admin\ImageController::class, 'index'])->name('images.index');
    Route::get('/images/folder/{folder:slug}', [\App\Http\Controllers\Admin\ImageController::class, 'showFolder'])->name('images.show');
    Route::post('/images/folder', [\App\Http\Controllers\Admin\ImageController::class, 'storeFolder'])->name('images.folder.store');
    Route::put('/images/folder/{folder}', [\App\Http\Controllers\Admin\ImageController::class, 'updateFolder'])->name('images.folder.update');
    Route::delete('/images/folder/{folder}', [\App\Http\Controllers\Admin\ImageController::class, 'deleteFolder'])->name('images.folder.delete');

    Route::post('/images/upload', [\App\Http\Controllers\Admin\ImageController::class, 'uploadImages'])->name('images.upload');
    Route::get('/images/fetch', [\App\Http\Controllers\Admin\ImageController::class, 'getImagesAjax'])->name('images.ajax');
    Route::put('/images/{image}/move', [\App\Http\Controllers\Admin\ImageController::class, 'moveImage'])->name('images.move');
    Route::delete('/images/{image}', [\App\Http\Controllers\Admin\ImageController::class, 'deleteImage'])->name('images.delete');

    // Image Modal System
    Route::get('/modal/folders', [\App\Http\Controllers\Admin\ImageModalController::class, 'getFolders'])->name('modal.folders');
    Route::get('/modal/images/{folder?}', [\App\Http\Controllers\Admin\ImageModalController::class, 'getImages'])->name('modal.images');

    // Category Management
    Route::resource('categories', \App\Http\Controllers\Admin\CategoryController::class)->except(['create', 'show', 'edit']);

    // Product Management
    Route::resource('products', \App\Http\Controllers\Admin\ProductController::class);

    // Tag Management
    Route::resource('tags', \App\Http\Controllers\Admin\TagController::class)->except(['create', 'show', 'edit']);

    // Blog Management
    Route::resource('blogs', \App\Http\Controllers\Admin\BlogController::class);

    // Entity CRUDs
    Route::resource('distributors', \App\Http\Controllers\Admin\DistributorController::class)->except(['show']);
    Route::resource('registrations', \App\Http\Controllers\Admin\RegistrationController::class)->except(['show']);
    Route::resource('testimonials', \App\Http\Controllers\Admin\TestimonialController::class)->except(['show']);
    Route::resource('why-choose-us', \App\Http\Controllers\Admin\WhyChooseUsController::class)->except(['show'])->names([
        'index' => 'why-choose-us.index',
        'create' => 'why-choose-us.create',
        'store' => 'why-choose-us.store',
        'edit' => 'why-choose-us.edit',
        'update' => 'why-choose-us.update',
        'destroy' => 'why-choose-us.destroy',
    ]);
    Route::resource('social-media', \App\Http\Controllers\Admin\SocialMediaController::class)->except(['show', 'create', 'edit']);

    // Profile & Password
    Route::get('/profile/password', [\App\Http\Controllers\AuthController::class, 'showPasswordChange'])->name('profile.password');
    Route::post('/profile/password', [\App\Http\Controllers\AuthController::class, 'updatePassword'])->name('profile.password.update');

    // Why Choose Us Section
    Route::get('/pages/why-choose-us', [\App\Http\Controllers\Admin\PageCmsController::class, 'whyChooseUs'])->name('pages.why-choose-us');
    Route::post('/pages/why-choose-us', [\App\Http\Controllers\Admin\PageCmsController::class, 'updateWhyChooseUs'])->name('pages.why-choose-us.update');

    // Home Page CMS
    Route::get('/pages/home/hero', [\App\Http\Controllers\Admin\PageCmsController::class, 'homeHero'])->name('pages.home.hero');
    Route::post('/pages/home/hero', [\App\Http\Controllers\Admin\PageCmsController::class, 'updateHomeHero'])->name('pages.home.hero.update');
    Route::get('/pages/home/banner', [\App\Http\Controllers\Admin\PageCmsController::class, 'homeBanner'])->name('pages.home.banner');
    Route::post('/pages/home/banner', [\App\Http\Controllers\Admin\PageCmsController::class, 'updateHomeBanner'])->name('pages.home.banner.update');

    // New Modules
    Route::resource('service-categories', \App\Http\Controllers\Admin\ServiceCategoryController::class);
    Route::get('service-categories/{category}/details', [\App\Http\Controllers\Admin\ServiceCategoryDetailController::class, 'edit'])->name('service-categories.details.edit');
    Route::post('service-categories/{category}/details', [\App\Http\Controllers\Admin\ServiceCategoryDetailController::class, 'update'])->name('service-categories.details.update');
    Route::resource('services', \App\Http\Controllers\Admin\ServiceController::class);
    Route::resource('service-areas', \App\Http\Controllers\Admin\ServiceAreaController::class);
    Route::resource('faqs', \App\Http\Controllers\Admin\FaqController::class);
    Route::resource('page-seos', \App\Http\Controllers\Admin\PageSeoController::class);
    Route::resource('navbar-links', \App\Http\Controllers\Admin\NavbarLinkController::class);
    Route::resource('pest-categories', \App\Http\Controllers\Admin\PestCategoryController::class);
    Route::resource('pests', \App\Http\Controllers\Admin\PestController::class);

    // Order Management
    Route::get('/orders', [\App\Http\Controllers\Admin\OrderController::class, 'index'])->name('orders.index');
    Route::get('/orders/{order}', [\App\Http\Controllers\Admin\OrderController::class, 'show'])->name('orders.show');
    Route::put('/orders/{order}/status', [\App\Http\Controllers\Admin\OrderController::class, 'updateStatus'])->name('orders.status');

    // Review Management
    Route::get('/reviews', [\App\Http\Controllers\Admin\ReviewController::class, 'index'])->name('reviews.index');
    Route::delete('/reviews/{review}', [\App\Http\Controllers\Admin\ReviewController::class, 'destroy'])->name('reviews.delete');

    // Settings
    Route::get('/settings', [\App\Http\Controllers\Admin\SettingController::class, 'index'])->name('settings.index');
    Route::post('/settings', [\App\Http\Controllers\Admin\SettingController::class, 'store'])->name('settings.store');
});
