<?php

namespace App\Http\Controllers\Web;

use App\Helpers\ImageHelper;
use App\Http\Controllers\Controller;
use App\Page;
use App\PageDescription;
use Illuminate\Http\Request;
use \Illuminate\Support\Str;
use Illuminate\View\View;

class PageController extends Controller
{
    private $viewDirectory = 'web.pages.';
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        // $this->middleware('auth')->except('lang');
    }

    /**
     * Show the Pages.
     *
     * @return \View
     */
    public function index(): View
    {
        $query= Page::latest()
            ->join('page_descriptions AS pd', 'pages.id', 'pd.page_id')
            ->where('status', 1)
            ->where('language_id', currentLanguage()->id)
            ->select(['pd.*', 'pages.*'])->get();

        $pages= [];
        if($query){
            $pages= $query->toArray();
        }
        foreach ($pages as $key => $value) {
            $pages[$key]['image']= ImageHelper::get($value['image']);
            $pages[$key]['intro']= Str::words(strip_tags($value['description']), 10, '...');
            $pages[$key]['route']= route('page_details', ['page'=> $value['page_id'], 'slug'=> str_slug($value['slug'])] );
        }
        // dd($pages);
        $settings= settings();
        $title= $settings['website_name'];
        $keywords= $settings['keywords'];
        $meta_description= $settings['meta_description'];

        return view($this->viewDirectory.'index', compact( 'pages', 'title', 'keywords', 'meta_description'));
    }

    /**
     * Show the Page details.
     * @param Page
     * @return \View
     */
    public function details(Page $page, Request $request) :View
    {
        $image= ImageHelper::get($page->image);
        $description = PageDescription::where('page_id', $page->id)
        ->where('language_id', currentLanguage()->id)
        ->first();
        // dd($description->toArray(), $image);

        $title= $description->title;
        $keywords= $description->keywords;
        $meta_description= $description->meta_description;

        return view( $this->viewDirectory.'details', compact('page', 'description', 'image', 'title', 'keywords', 'meta_description') );
    }
}
