<?php

use App\Enums\BusinessType;
use App\Enums\InquiryType;
use App\Models\Brand;
use App\Models\BusinessInquiry;
use App\Models\Campaign;
use App\Models\Category;
use App\Models\Municipality;
use App\Models\Product;
use App\Models\Province;
use App\Models\Store;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome', app(\App\Services\HomepageService::class)->build());
});

Route::get('/lojas', function () {
    $provinces = Province::orderBy('name')->get();
    $municipalities = Municipality::orderBy('name')->get();
    $services = [];

    \App\Models\StoreService::select('service')->distinct()->orderBy('service')->each(function ($s) use (&$services) {
        $services[] = $s->service;
    });

    $query = Store::with(['province', 'municipality', 'hours', 'services'])->active();

    if ($search = request('search')) {
        $query->search($search);
    }
    if ($provinceId = request('province_id')) {
        $query->byProvince($provinceId);
    }
    if ($municipalityId = request('municipality_id')) {
        $query->byMunicipality($municipalityId);
    }
    if ($serviceType = request('service')) {
        $query->byService($serviceType);
    }
    if (request('open_now') === '1') {
        $query->openNow();
    }

    $stores = $query->orderBy('sort_order')->orderBy('name')->get();

    $day = now()->dayOfWeek;
    $storesJson = $stores->map(fn($s) => [
        'id' => $s->id,
        'name' => $s->name,
        'slug' => $s->slug,
        'latitude' => (float) $s->latitude,
        'longitude' => (float) $s->longitude,
        'address' => trim(($s->neighborhood ? $s->neighborhood . ', ' : '') . ($s->municipality?->name ?? '') . ($s->province?->name ? ' - ' . $s->province->name : '')),
        'status' => $s->status?->label(),
        'today_hours' => ($h = $s->hours->firstWhere('day_of_week', $day)) ? [
            'is_closed' => $h->is_closed,
            'opens_at' => $h->opens_at?->format('H:i'),
            'closes_at' => $h->closes_at?->format('H:i'),
        ] : null,
        'has_coords' => (bool) $s->latitude && (bool) $s->longitude,
        'services' => $s->services?->pluck('service') ?? [],
    ])->values()->toArray();

    return view('pages.stores.index', compact('provinces', 'municipalities', 'services', 'stores', 'storesJson'));
})->name('lojas');

Route::get('/lojas/{slug}', function ($slug) {
    $store = Store::with(['province', 'municipality', 'hours', 'services'])->active()
        ->where('slug', $slug)
        ->firstOrFail();

    $nearbyStores = Store::with(['province', 'municipality'])
        ->active()
        ->where('id', '!=', $store->id)
        ->where('province_id', $store->province_id)
        ->inRandomOrder()
        ->take(4)
        ->get();

    return view('pages.stores.show', compact('store', 'nearbyStores'));
})->name('lojas.detalhes');

Route::get('/produtos', function () {
    $categories = Category::active()->orderBy('sort_order')->get();
    $brands = Brand::active()->orderBy('name')->get();
    $campaigns = Campaign::current()->get();

    $query = Product::with(['category', 'brand', 'images'])->active();

    if ($search = request('search')) {
        $query->where(function ($q) use ($search) {
            $q->where('name', 'like', "%{$search}%")
              ->orWhere('description', 'like', "%{$search}%");
        });
    }
    if ($categoryId = request('category_id')) {
        $query->where('category_id', $categoryId);
    }
    if ($brandId = request('brand_id')) {
        $query->where('brand_id', $brandId);
    }

    $sort = request('sort', 'sort_order');
    $allowed = ['sort_order', 'name', 'price', '-price', 'created_at'];
    $sort = in_array($sort, $allowed) ? $sort : 'sort_order';
    if (str_starts_with($sort, '-')) {
        $query->orderBy(substr($sort, 1), 'desc');
    } else {
        $query->orderBy($sort);
    }

    $products = $query->paginate(24);
    $currentCategory = $categoryId ? Category::find($categoryId) : null;

    return view('pages.products.index', compact('categories', 'brands', 'campaigns', 'products', 'currentCategory'));
})->name('produtos');

Route::get('/produtos/{slug}', function ($slug) {
    $product = Product::with(['category', 'brand', 'images'])->active()->where('slug', $slug)->firstOrFail();
    $related = Product::with(['category', 'brand'])
        ->active()
        ->where('category_id', $product->category_id)
        ->where('id', '!=', $product->id)
        ->inRandomOrder()
        ->take(4)
        ->get();
    $campaigns = Campaign::current()->get();

    return view('pages.products.show', compact('product', 'related', 'campaigns'));
})->name('produtos.detalhes');

Route::get('/categorias/{slug}', function ($slug) {
    $category = Category::active()->where('slug', $slug)->firstOrFail();
    $brands = Brand::active()->orderBy('name')->get();
    $campaigns = Campaign::current()->get();

    $query = Product::with(['category', 'brand', 'images'])->active()->where('category_id', $category->id);

    if ($search = request('search')) {
        $query->where(function ($q) use ($search) {
            $q->where('name', 'like', "%{$search}%")
              ->orWhere('description', 'like', "%{$search}%");
        });
    }
    if ($brandId = request('brand_id')) {
        $query->where('brand_id', $brandId);
    }

    $sort = request('sort', 'sort_order');
    $allowed = ['sort_order', 'name', 'price', '-price', 'created_at'];
    $sort = in_array($sort, $allowed) ? $sort : 'sort_order';
    if (str_starts_with($sort, '-')) {
        $query->orderBy(substr($sort, 1), 'desc');
    } else {
        $query->orderBy($sort);
    }

    $products = $query->paginate(24);

    return view('pages.categories.show', compact('category', 'brands', 'campaigns', 'products'));
})->name('categorias.detalhes');

Route::prefix('para-negocios')->group(function () {
    Route::get('/', function () {
        $categories = Category::active()->orderBy('sort_order')->get();
        $provinces = Province::orderBy('name')->get();

        return view('pages.business', compact('categories', 'provinces'));
    })->name('negocios');

    Route::post('/', function () {
        $validated = request()->validate([
            'name' => 'required|max:150',
            'company' => 'required|max:150',
            'business_type' => 'nullable|max:50',
            'phone' => 'required|max:50',
            'email' => 'required|email|max:150',
            'province_id' => 'nullable|exists:provinces,id',
            'message' => 'required',
        ]);

        $validated['type'] = InquiryType::B2B;
        $validated['status'] = \App\Enums\InquiryStatus::New;

        BusinessInquiry::create($validated);

        return redirect('/para-negocios?success=1#form-section');
    })->middleware('throttle:form');
});

Route::permanentRedirect('/negocios', '/para-negocios');

Route::get('/noticias', function () {
    return view('pages.news.index');
})->name('noticias');

Route::get('/noticias/{slug}', function ($slug) {
    return view('pages.news.show', compact('slug'));
})->name('noticias.detalhes');

Route::get('/campanhas', function () {
    return view('pages.campaigns.index');
})->name('campanhas');

Route::prefix('fornecedores')->name('suppliers.')->group(function () {
    Route::get('/', [\App\Http\Controllers\SupplierPortalController::class, 'index'])
        ->name('index');

    Route::get('/candidatura', [\App\Http\Controllers\SupplierApplicationController::class, 'create'])
        ->name('application.create');

    Route::post('/candidatura', [\App\Http\Controllers\SupplierApplicationController::class, 'store'])
        ->middleware('throttle:form')
        ->name('application.store');
});

Route::get('/oportunidades', function () {
    return view('pages.opportunities.index');
})->name('oportunidades');

Route::get('/oportunidades/{slug}', function ($slug) {
    return view('pages.opportunities.show', compact('slug'));
})->name('oportunidades.detalhes');

Route::get('/parceiros', function () {
    return view('pages.partners.index');
})->name('parceiros');

Route::get('/carreiras', function () {
    return view('pages.careers.index');
})->name('carreiras');

Route::get('/retalhistas', function () {
    return view('pages.retailers.index');
})->name('retalhistas');

Route::get('/sitemap.xml', function () {
    $static = [
        ['loc' => url('/'), 'priority' => '1.0', 'changefreq' => 'weekly'],
        ['loc' => url('lojas'), 'priority' => '0.9', 'changefreq' => 'weekly'],
        ['loc' => url('produtos'), 'priority' => '0.9', 'changefreq' => 'daily'],
        ['loc' => url('campanhas'), 'priority' => '0.8', 'changefreq' => 'weekly'],
        ['loc' => url('noticias'), 'priority' => '0.8', 'changefreq' => 'daily'],
        ['loc' => url('fornecedores'), 'priority' => '0.9', 'changefreq' => 'weekly'],
        ['loc' => url('fornecedores/candidatura'), 'priority' => '0.8', 'changefreq' => 'monthly'],
        ['loc' => url('oportunidades'), 'priority' => '0.7', 'changefreq' => 'weekly'],
        ['loc' => url('parceiros'), 'priority' => '0.6', 'changefreq' => 'monthly'],
        ['loc' => url('carreiras'), 'priority' => '0.7', 'changefreq' => 'weekly'],
        ['loc' => url('para-negocios'), 'priority' => '0.8', 'changefreq' => 'monthly'],
        ['loc' => url('retalhistas'), 'priority' => '0.7', 'changefreq' => 'monthly'],
    ];

    $stores = \App\Models\Store::active()->get()->map(fn($s) => [
        'loc' => url('lojas/' . $s->slug),
        'priority' => '0.8',
        'changefreq' => 'weekly',
        'lastmod' => $s->updated_at?->toW3cString(),
    ]);

    $products = \App\Models\Product::active()->get()->map(fn($p) => [
        'loc' => url('produtos/' . $p->slug),
        'priority' => '0.7',
        'changefreq' => 'weekly',
        'lastmod' => $p->updated_at?->toW3cString(),
    ]);

    $news = \App\Models\NewsArticle::published()->get()->map(fn($a) => [
        'loc' => url('noticias/' . $a->slug),
        'priority' => '0.7',
        'changefreq' => 'monthly',
        'lastmod' => $a->updated_at?->toW3cString(),
    ]);

    $opportunities = \App\Models\Opportunity::published()->get()->map(fn($o) => [
        'loc' => url('oportunidades/' . $o->slug),
        'priority' => '0.6',
        'changefreq' => 'monthly',
    ]);

    $urls = collect($static)->concat($stores)->concat($products)->concat($news)->concat($opportunities);

    $xml = '<?xml version="1.0" encoding="UTF-8"?>';
    $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    foreach ($urls as $url) {
        $xml .= '<url>';
        $xml .= '<loc>' . e($url['loc']) . '</loc>';
        $xml .= '<priority>' . $url['priority'] . '</priority>';
        $xml .= '<changefreq>' . $url['changefreq'] . '</changefreq>';
        if (!empty($url['lastmod'])) {
            $xml .= '<lastmod>' . $url['lastmod'] . '</lastmod>';
        }
        $xml .= '</url>';
    }
    $xml .= '</urlset>';

    return response($xml, 200, ['Content-Type' => 'application/xml']);
});

Route::get('/robots.txt', function () {
    $content = "User-agent: *\nAllow: /\n\nSitemap: " . url('sitemap.xml');
    return response($content, 200, ['Content-Type' => 'text/plain']);
});

use App\Http\Controllers\Admin\AdminController;
use App\Http\Controllers\Admin\ProductAdminController;
use App\Http\Controllers\Admin\CategoryAdminController;
use App\Http\Controllers\Admin\StoreAdminController;
use App\Http\Controllers\Admin\NewsAdminController;
use App\Http\Controllers\Admin\CampaignAdminController;
use App\Http\Controllers\Admin\SlideAdminController;
use App\Http\Controllers\Admin\UserAdminController;
use App\Http\Controllers\Admin\InquiryAdminController;
use App\Http\Controllers\Admin\SupplierApplicationAdminController;
use App\Http\Controllers\Admin\CardRequestAdminController;
use App\Http\Controllers\CardRequestController;

Route::permanentRedirect('/login', '/admin/login');

Route::prefix('admin')->name('admin.')->group(function () {
    Route::get('/login', [AdminController::class, 'login'])->name('login');
    Route::post('/login', [AdminController::class, 'authenticate']);
    Route::post('/logout', [AdminController::class, 'logout'])->name('logout');

    Route::middleware(['auth', 'admin'])->group(function () {
        Route::get('/dashboard', [AdminController::class, 'dashboard'])->name('dashboard');

        Route::resource('products', ProductAdminController::class)->except(['show']);
        Route::resource('categories', CategoryAdminController::class)->except(['show']);
        Route::resource('stores', StoreAdminController::class)->except(['show']);
        Route::resource('news', NewsAdminController::class)->except(['show']);
        Route::delete('/news/{news}/gallery/{gallery}', [NewsAdminController::class, 'destroyGallery'])->name('news.gallery.destroy');
        Route::resource('campaigns', CampaignAdminController::class)->except(['show']);
        Route::resource('slides', SlideAdminController::class)->except(['show']);
        Route::resource('users', UserAdminController::class)->except(['show']);
        Route::resource('inquiries', InquiryAdminController::class)->only(['index', 'show', 'update', 'destroy']);
        Route::resource('supplier-applications', SupplierApplicationAdminController::class)->only(['index', 'show', 'update', 'destroy']);
        Route::resource('card-requests', CardRequestAdminController::class)->only(['index', 'show', 'update', 'destroy']);
    });
});

Route::post('/cartao/solicitar', [CardRequestController::class, 'store']);
