<?php

namespace Ignite\Core\Http\Controllers\Admin;

use Ignite\Core\Contracts\Repositories\PageRepository;
use Ignite\Core\Entities\Page;
use Ignite\Core\Http\Controllers\Controller;
use Ignite\Core\Http\Requests\CreatePageRequest;
use Ignite\Core\Http\Requests\UpdatePageRequest;

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

    /**
     * Create a new controller instance.
     *
     * @param PageRepository $pageRepository
     */
    public function __construct(PageRepository $pageRepository)
    {
        $this->pageRepository = $pageRepository;
    }

    /**
     * Display a listing of the pages resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $pages = $this->pageRepository->findAll();

        return view('Core::admin.cms.pages.index', compact('pages'));
    }

    /**
     * Show the form for creating a new resource.
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $page = new Page();

        return view('Core::admin.cms.pages.create', compact('page'));
    }

    /**
     * Store a newly created resource in storage.
     * @param  CreatePageRequest $request
     * @return \Illuminate\Http\Response
     */
    public function store(CreatePageRequest $request)
    {
        try {
            $this->pageRepository->create($request->all());
            $this->flash('success', 'Page created successfully.');
        } catch (\Exception $e) {
            $this->flash('error', $e->getMessage());
        }

        return redirect()->route('admin.pages.index');
    }

    /**
     * Show the specified resource.
     * @return \Illuminate\Http\Response
     */
    public function show()
    {
        return view('Core::admin.cms.pages.show');
    }

    /**
     * Show the form for editing the specified resource.
     * @param $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $page = $this->pageRepository->find($id);

        return view('Core::admin.cms.pages.edit', compact('page', 'id'));
    }

    /**
     * Update the specified resource in storage.
     * @param  UpdatePageRequest $request
     * @return \Illuminate\Http\Response
     */
    public function update(UpdatePageRequest $request, $id)
    {
        try {
            $this->pageRepository->update($id, $request->all());
            $this->flash('success', 'Page updated successfully.');
        } catch (\Exception $e) {
            $this->flash('error', $e->getMessage());
        }

        return redirect()->route('admin.pages.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy()
    {
        $this->flash('info', 'Deleting pages is not allowed.');

        return redirect()->route('admin.pages.index');
    }
}
