<?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)
    {
        // Check the global landing page enabled setting first
        if (setting('landing_page_enabled', '0') != '1') {
            // Landing page system is disabled globally
            if (auth()->check()) {
                return redirect()->route('dashboard');
            }
            // Assuming you have a login route named 'login'
            return redirect()->route('login');
            // Alternatively, you could show a specific "site offline" view:
            // if (View::exists('errors.site_offline')) {
            //     return response()->view('errors.site_offline', ['message' => 'Site is currently offline.'], 503);
            // }
        }

        $activeTheme = $this->getActiveTheme();
        $page = null;
        $businessData = [];

        if (empty($slug) || $slug === '/') { // Handle homepage
            $homeSlug = setting('landingpage_homepage_slug', 'home');
            $page = LpPage::with('sections')->where('slug', $homeSlug)->where('is_published', true)->first();

            if (!$page) {
                // No LpPage found for homepage slug, try to render theme's home.blade.php
                if (View::exists("landingpage::themes.{$activeTheme}.home")) {
                    $page = new LpPage([
                        'title' => setting('site_name', 'Homepage'),
                        'meta_title' => setting('site_name', 'Homepage'),
                        'meta_description' => setting('landingpage_global_meta_description', 'Welcome to our site.'),
                        'slug' => $homeSlug,
                        'is_published' => true,
                        'theme_template' => 'home', // Indicate it's using the home template
                    ]);
                    $page->exists = false; // Important for checks like $page->id
                    $page->setRelation('sections', collect()); // Set an empty collection for sections
                    $businessData = $this->getBusinessDataForPage($page, $activeTheme); // Fetch data for hardcoded home
                    return view("landingpage::themes.{$activeTheme}.home", compact('activeTheme', 'page', 'businessData'));
                }
                // If no LpPage and no theme home.blade.php, then it's a 404
                return $this->renderNotFound($activeTheme, 'Homepage not configured.');
            }
        } else {
            $page = LpPage::with('sections')->where('slug', $slug)->where('is_published', true)->firstOrFail();
        }

        // Fetch business data for the resolved page (either found LpPage or constructed for home)
        $businessData = $this->getBusinessDataForPage($page, $activeTheme);

        // Determine the correct view to render
        $finalThemeView = "landingpage::themes.{$activeTheme}.page"; // Default

        // Special handling for homepage if it has a dedicated home.blade.php
        if ($page->slug === setting('landingpage_homepage_slug', 'home')) {
            if (View::exists("landingpage::themes.{$activeTheme}.home")) {
                $finalThemeView = "landingpage::themes.{$activeTheme}.home";
            }
        }

        // Check for a page-specific theme_template
        if ($page->theme_template) {
            $templateInTemplatesDir = "landingpage::themes.{$activeTheme}.templates.{$page->theme_template}";
            $templateInThemeRoot = "landingpage::themes.{$activeTheme}.{$page->theme_template}";

            if (View::exists($templateInTemplatesDir)) {
                $finalThemeView = $templateInTemplatesDir;
            } elseif (View::exists($templateInThemeRoot)) {
                $finalThemeView = $templateInThemeRoot;
            }
            // If theme_template is specified but not found, $finalThemeView remains the base (page or home)
        }

        // Final check: if the determined view (specific template or base page/home) doesn't exist
        if (!View::exists($finalThemeView)) {
            // If even the default 'page.blade.php' for the theme is missing, then 404.
            // This also covers the case where a theme_template was set but invalid, and the fallback (page.blade.php) also doesn't exist.
            if ($finalThemeView === "landingpage::themes.{$activeTheme}.page" && !View::exists("landingpage::themes.{$activeTheme}.page")) {
                 return $this->renderNotFound($activeTheme, 'Default page template missing in theme.');
            }
            // If a specific template was chosen but not found, and the base view (page.blade.php or home.blade.php) exists, use the base.
            // This logic is implicitly handled by $finalThemeView starting as the base.
        }

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

    // 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.

    /**
     * Fetch dynamic business data for a given page.
     * This is a placeholder and should be customized.
     *
     * @param LpPage $page
     * @param string $activeTheme
     * @return array
     */
    protected function getBusinessDataForPage(LpPage $page, string $activeTheme): array
    {
        $data = [];

        // Example: Data for the homepage
        if ($page->slug === setting('landingpage_homepage_slug', 'home') || $page->theme_template === 'home') {
            // $data['featured_jobs'] = \Modules\BusinessDirectory\Entities\Job::where('status', 'open')->latest()->take(3)->get();
            // $data['latest_companies'] = \Modules\BusinessDirectory\Entities\Company::where('status', 'approved')->latest()->take(4)->get();
        }

        // Example: Data for a page with a specific template
        // if ($page->theme_template === 'contact_form_page') {
        //     $data['contact_form_recipient'] = setting('contact_form_email', 'admin@example.com');
        // }

        return $data;
    }

    /**
     * Renders the theme's page_not_found view.
     */
    protected function renderNotFound(string $activeTheme, string $message = 'Page not found.')
    {
        $page = new LpPage(['title' => 'Page Not Found', 'meta_title' => 'Page Not Found', 'slug' => '404']);
        return response()->view("landingpage::themes.{$activeTheme}.page_not_found", [
            'activeTheme' => $activeTheme,
            'page' => $page, // Pass a minimal page object for layout consistency
            'message' => $message
        ], 404);
    }
}