<?php

namespace Modules\LandingPage\Http\Controllers;

use App\Http\Controllers\Controller;
use Modules\LandingPage\Entities\LpPage;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\File;

class FrontendPageController extends Controller
{
    protected function getActiveTheme()
    {
        return setting('landingpage_active_theme', 'general'); // Default to 'general'
    }

    public function show($slug = null)
    {
        $activeTheme = $this->getActiveTheme();
        $page = null;

        if (empty($slug) || $slug === '/') { // Handle homepage
            $page = LpPage::where('slug', 'home')->where('is_published', true)->first();
            // If no 'home' slug page, you might have a default homepage template in the theme
            if (!$page) {
                // Check if a theme-specific home view exists
                if (View::exists("landingpage::themes.{$activeTheme}.home")) {
                    return view("landingpage::themes.{$activeTheme}.home", ['activeTheme' => $activeTheme]);
                }
                // Fallback if no specific home page or theme home view
                return view("landingpage::themes.{$activeTheme}.page_not_found", ['activeTheme' => $activeTheme])->withErrors(['Page not found.']);
            }
        } else {
            $page = LpPage::where('slug', $slug)->where('is_published', true)->firstOrFail();
        }

        $themeView = "landingpage::themes.{$activeTheme}.page"; // Default page template
        if ($page->theme_template && View::exists("landingpage::themes.{$activeTheme}.templates.{$page->theme_template}")) {
            $themeView = "landingpage::themes.{$activeTheme}.templates.{$page->theme_template}";
        } elseif (!View::exists($themeView)) {
            // Fallback if default page template doesn't exist in the theme
             return view("landingpage::themes.{$activeTheme}.page_not_found", ['activeTheme' => $activeTheme])->withErrors(['Page template not found in active theme.']);
        }

        return view($themeView, compact('page', 'activeTheme'));
    }

    // You can add methods here to fetch data from other modules
    // e.g., getFeaturedProjects(), getLatestJobs(), etc.
    // These would then be passed to your theme views.
}