<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\File;

class FrontendController extends Controller
{
    public function index()
    {
        // Try dist folder first (production build)
        $distPath = base_path('frontend/hotili-frontend/dist/index.html');
        
        if (File::exists($distPath)) {
            $html = File::get($distPath);
            // Fix asset paths to use /frontend prefix
            $html = str_replace(
                ['src="/assets/', 'href="/assets/'],
                ['src="/frontend/assets/', 'href="/frontend/assets/'],
                $html
            );
            return response($html)->header('Content-Type', 'text/html');
        }

        return response()->view('errors.404', [], 404);
    }

    public function asset($path)
    {
        // Handle /frontend/assets/{path}
        if (strpos($path, 'assets/') === 0) {
            $path = substr($path, 7); // Remove 'assets/' prefix
            $filePath = base_path('frontend/hotili-frontend/dist/assets/' . $path);
        } else {
            // Handle root level assets (favicon, svg, json)
            $filePath = base_path('frontend/hotili-frontend/dist/' . $path);
        }
        
        if (!File::exists($filePath)) {
            return response('Not Found', 404);
        }

        return response(File::get($filePath))
            ->header('Content-Type', $this->getMimeType($filePath));
    }

    private function getMimeType($filePath)
    {
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        
        $mimeTypes = [
            'js' => 'application/javascript',
            'css' => 'text/css',
            'svg' => 'image/svg+xml',
            'jpg' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
            'json' => 'application/json',
            'woff' => 'font/woff',
            'woff2' => 'font/woff2',
        ];

        return $mimeTypes[$ext] ?? 'text/plain';
    }
}

