<?php

namespace App\Http\Controllers;

use App\Models\MarketplacePurchase;
use App\Models\Page;
use App\Models\Setting;
use App\Services\ThemeService;

class FrontController extends Controller
{
    public function __construct(
        protected ThemeService $themeService
    ) {}

    protected function pageForDisplay(?Page $page): ?object
    {
        if (! $page || ! MarketplacePurchase::hasPurchased('plugin', 'multilang')) {
            return $page;
        }
        $locale = app()->getLocale();
        $defaultLocale = Setting::get('multilang_default', 'fr');
        return $page->getTranslatedForDisplay($locale, $defaultLocale);
    }

    public function home()
    {
        $page = Page::where('is_home', true)->where('is_published', true)->first();
        $displayPage = $this->pageForDisplay($page);
        if ($page && ! empty($page->sections)) {
            return $this->themeService->render('page-sections', ['page' => $displayPage]);
        }
        if ($page) {
            return $this->themeService->render('page', ['page' => $displayPage]);
        }
        return $this->themeService->render('home', ['page' => null]);
    }

    public function page(string $slug)
    {
        $page = Page::where('slug', $slug)->where('is_published', true)->firstOrFail();
        $displayPage = $this->pageForDisplay($page);
        if (! empty($page->sections)) {
            return $this->themeService->render('page-sections', ['page' => $displayPage]);
        }
        return $this->themeService->render('page', ['page' => $displayPage]);
    }
}
