<?php

namespace App\Http\Controllers\Support;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Tighten\Ziggy\Ziggy;

class ZiggyController extends Controller
{
    /**
     * Generate and return Ziggy routes as JavaScript
     * Routes are filtered by both user role and requested page scope:
     * - Public/frontend pages: only frontend routes
     * - Admin pages: admin routes, but only for authenticated admins
     */
    public function routes(Request $request)
    {
        $user = $request->user();
        $isAdmin = $user && $user->role === 'admin';
        $requestedGroup = $request->query('group');
        $shouldExposeAdminRoutes = $isAdmin && $requestedGroup === 'admin';

        // Generate Ziggy routes with appropriate filter
        // Public pages always get the frontend group, even for admin users.
        // Admin pages must opt in via ?group=admin and still require an admin session.
        // Use base URL only, not the current request URL (which would be /js/routes.js)
        $baseUrl = rtrim(config('app.url'), '/');
        $ziggy = new Ziggy($shouldExposeAdminRoutes ? null : 'frontend', $baseUrl);
        $ziggyArray = $ziggy->toArray();

        // Additional filtering: ensure no admin routes leak to non-admin users
        if (! $shouldExposeAdminRoutes) {
            $ziggyArray['routes'] = array_filter(
                $ziggyArray['routes'],
                function ($key) {
                    return ! str_starts_with($key, 'admin.');
                },
                ARRAY_FILTER_USE_KEY
            );
        }

        return response()
            ->view('ziggy-routes', ['ziggyArray' => $ziggyArray])
            ->header('Content-Type', 'application/javascript')
            ->header('Cache-Control', 'private, no-cache, no-store, must-revalidate')
            ->header('Pragma', 'no-cache')
            ->header('Expires', '0')
            ->header('X-Content-Type-Options', 'nosniff')
            ->header('X-Frame-Options', 'SAMEORIGIN')
            ->header('Vary', 'Cookie'); // Important: cache per user session
    }
}
