<?php

namespace App\Http\Controllers;

use App\Page;
use App\Product;
use App\Category;
use App\Article;

class PageController extends Controller
{
    public function __construct()
    {
        $this->middleware('web');
        $this->middleware('offline');
    }

    public function show()
    {
        $page = Page::with('post.media', 'sections.post.media')->whereHas('post', function($q) {
            $q->where('slug', request()->path());
        })->firstOrFail();

        $method = $page->template;

        if($method && method_exists($this, $method)) {
            return $this->$method($page);
        } else {
            $view = 'templates.page';

            return view($view, [
                'page' => $page
            ]);
        }
    }

    public function home($page)
    {
        $latest_products = Product::with('post')->orderBy('created_at', 'desc')->take(6)->get();
        $featured_products = Product::with('post')->whereHas('post', function($q) {
            $q->where('featured', 1);
        })->orderBy('created_at', 'desc')->take(3)->get();
        $categories = Category::has('products')->orderBy('order')->get();
        $articles = Article::orderBy('published_at', 'desc')->take(4)->get();

        return view('templates.page', [
            'page' => $page,
            'categories' => $categories,
            'featured_products' => $featured_products,
            'articles' => $articles,
            'latest_products' => $latest_products,
        ]);
    }

    public function shop($page)
    {
        $products = Product::with('post')->orderBy('created_at', 'desc')->paginate(12);
        $categories = Category::has('products')->with('products')->withCount('products')->orderBy('title')->get();
        $latest_products = Product::with('post')->orderBy('created_at', 'desc')->take(3)->get();

        return view('templates.shop', [
            'page' => $page,
            'products' => $products,
            'latest_products' => $latest_products,
            'categories' => $categories,
        ]);
    }
}
