<?php

use Illuminate\Support\Facades\Route;

// ── 🌉 Legacy php-api/ Bridge (old compiled build compatibility) ──────────────
// Old public/build assets call /php-api/* directly (not /api/*).  
// These routes catch them before the React SPA catch-all.
Route::any('php-api/super-admin', [\App\Http\Controllers\Api\LegacySuperAdminController::class, 'handle']);
Route::any('php-api/analytics',   [\App\Http\Controllers\Api\LegacyAnalyticsController::class,  'handle']);

/*
|--------------------------------------------------------------------------
| Web Routes — ShophyFast
| The React SPA catches all routes via this catch-all.
|--------------------------------------------------------------------------
*/

Route::get('/{any?}', function () {
    $host = request()->getHost();
    $parts = explode('.', $host);
    
    $slug = null;
    $isRoot = true;

    // subdomain detection: xxx.shophyfast.com
    if (count($parts) >= 3 && $parts[0] !== 'www') {
        $slug = $parts[0];
        $isRoot = false;
    } elseif ($parts[0] !== 'localhost' && $parts[0] !== 'shophyfast' && $parts[0] !== 'superadmin' && count($parts) >= 2) {
        $slug = $parts[0];
        $isRoot = false;
    }

    $favicon = '/favicon.ico';
    $title = 'ShophyFast — Premium E-commerce Platform';

    try {
        $globalBrand = \Illuminate\Support\Facades\DB::table('global_settings')
            ->whereIn('setting_key', ['favicon_url', 'site_name'])
            ->pluck('setting_value', 'setting_key');
            
        $globalFavicon = !empty($globalBrand['favicon_url']) ? $globalBrand['favicon_url'] : $favicon;
        $globalSiteName = !empty($globalBrand['site_name']) ? $globalBrand['site_name'] : $title;

        // Try Custom Domain First
        $hostWithoutWww = preg_replace('/^www\./', '', $host);
        $tenant = \App\Models\Tenant::where('custom_domain', $host)
            ->orWhere('custom_domain', $hostWithoutWww)
            ->first();

        if ($tenant) {
            $isRoot = false; // It's a tenant store via custom domain
        } elseif ($slug && !$isRoot) {
            // Fallback to Subdomain
            $tenant = \App\Models\Tenant::where('business_slug', $slug)->first();

            if ($tenant && !empty($tenant->custom_domain)) {
                // Accessed via subdomain but tenant has a custom domain -> redirect to custom domain
                if (!request()->is('admin*') && !request()->is('api/admin*')) {
                    return redirect('http://' . $tenant->custom_domain . request()->getRequestUri(), 301);
                }
            }
        }

        if ($tenant) {
            $siteSettings = \App\Models\SiteSetting::where('tenant_id', $tenant->id)->first();
            if ($siteSettings) {
                $favicon = !empty($siteSettings->favicon) ? $siteSettings->favicon : $globalFavicon;
                $title = !empty($siteSettings->tab_title) ? $siteSettings->tab_title : (!empty($siteSettings->site_name) ? $siteSettings->site_name : $globalSiteName);
            } else {
                $favicon = $globalFavicon;
                $title = $globalSiteName;
            }
        } elseif (!$isRoot) {
            // Non-existent tenant slug or custom domain -> redirect to main domain
            // Determine the main host safely
            $mainHost = env('APP_URL', 'http://shophyfast.com');
            return redirect($mainHost);
        } else {
            // Root domain (SaaS super admin layer) uses global settings natively!
            $favicon = $globalFavicon;
            $title = $globalSiteName;
        }
    } catch (\Exception $e) {
        // Safe fallback if database isn't ready
    }

    return view('app', compact('favicon', 'title'));
})->where('any', '.*');
