<?php

namespace FluxCms\Core\Http\Controllers;

use FluxCms\Core\Models\BlogPost;
use FluxCms\Core\Models\Page;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class PageController extends Controller
{
    /**
     * Display a CMS page
     */
    public function show(Request $request, string $slug = '/')
    {
        $domainKey = $this->getCurrentDomainKey($request);

        $page = Page::forDomain($domainKey)
            ->published()
            ->bySlugWithFallback($slug)
            ->with(['components'])
            ->firstOrFail();

        // Load active components
        $components = $page->components()->get();

        return view('flux-cms::pages.show', compact('page', 'components'));
    }

    /**
     * Blog index page
     */
    public function blogIndex(Request $request)
    {
        $domainKey = $this->getCurrentDomainKey($request);
        $locale = app()->getLocale();

        $posts = BlogPost::forDomain($domainKey)
            ->published()
            ->orderBy('published_at', 'desc')
            ->paginate(10);

        return view('flux-cms::blog.index', compact('posts'));
    }

    /**
     * Blog post page
     */
    public function blogPost(Request $request, string $slug)
    {
        $domainKey = $this->getCurrentDomainKey($request);

        $post = BlogPost::forDomain($domainKey)
            ->published()
            ->bySlugWithFallback($slug)
            ->firstOrFail();

        // Get related posts
        $relatedPosts = BlogPost::forDomain($domainKey)
            ->published()
            ->where('id', '!=', $post->id)
            ->where('category', $post->category)
            ->limit(3)
            ->get();

        return view('flux-cms::blog.show', compact('post', 'relatedPosts'));
    }

    /**
     * Generate sitemap
     */
    public function sitemap(Request $request)
    {
        $domainKey = $this->getCurrentDomainKey($request);
        $locale = app()->getLocale();

        $pages = Page::forDomain($domainKey)
            ->published()
            ->get();

        $blogPosts = BlogPost::forDomain($domainKey)
            ->published()
            ->get();

        return response()->view('flux-cms::sitemap', compact('pages', 'blogPosts'))
            ->header('Content-Type', 'application/xml');
    }

    /**
     * Generate robots.txt
     */
    public function robots(Request $request)
    {
        $domainKey = $this->getCurrentDomainKey($request);
        $baseUrl = $this->getBaseUrl($request);

        return response()->view('flux-cms::robots', compact('baseUrl'))
            ->header('Content-Type', 'text/plain');
    }

    /**
     * Preview page (for authenticated users)
     */
    public function preview(Request $request, Page $page)
    {
        $this->middleware('auth');
        $this->middleware('can:flux-cms.view');

        $components = $page->allComponents()->get();

        return view('flux-cms::pages.preview', compact('page', 'components'));
    }

    /**
     * Get current domain key
     */
    protected function getCurrentDomainKey(Request $request): string
    {
        if (! config('flux-cms.domains.enabled')) {
            return config('flux-cms.domains.default_domain', 'default');
        }

        $host = $request->getHost();
        $domains = config('domains.domains', []);

        foreach ($domains as $key => $config) {
            if (isset($config['url'])) {
                $domainHost = parse_url($config['url'], PHP_URL_HOST);
                if ($domainHost === $host) {
                    return $key;
                }
            }
        }

        return config('flux-cms.domains.default_domain', 'default');
    }

    /**
     * Get base URL for current domain
     */
    protected function getBaseUrl(Request $request): string
    {
        $domainKey = $this->getCurrentDomainKey($request);
        $domains = config('domains.domains', []);

        if (isset($domains[$domainKey]['url'])) {
            return $domains[$domainKey]['url'];
        }

        return $request->getSchemeAndHttpHost();
    }
}
