<?php

namespace Ignite\Core\Http\Controllers;

use Ignite\Core\Contracts\Repositories\PageRepository;
use Illuminate\Auth\AuthenticationException;

class PageController extends Controller
{
    /** @var PageRepository */
    protected $pageRepository;

    /**
     * PageController constructor.
     *
     * @param PageRepository $pageRepository
     */
    public function __construct(PageRepository $pageRepository)
    {
        $this->pageRepository = $pageRepository;
    }

    /**
     * Show the homepage.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (auth()->guest() && !config('core.theming.enable_home_as_guest', true)) {
            return redirect()->route('login');
        }

        $page = $this->pageRepository->findHomepage();

        return view('cms.pages.home', compact('page'));
    }

    /**
     * Show the given page.
     *
     * @param  string $code
     * @return \Illuminate\Http\Response
     */
    public function show($code)
    {
        $page = $this->pageRepository->findByCode($code);

        if (! $page) {
            return abort(404);
        }

        if ($page->cannotBeViewed()) {
            throw new AuthenticationException();
        }

        $template = $page->template ?? 'default';

        return view("cms.pages.$template", compact('page'));
    }
}
