<?php

namespace App\Http\Controllers\Frontend;

use App\Models\News;
use App\Models\Setting;
use App\Models\NewsCate;
use Carbon\Carbon;

class NewsController extends FrontendController
{
    use \App\Traits\ControllerTrait;

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $pageNum = Setting::get('news_paginate') ?: 20;
        $news = News::with(['cates', 'description'])->flag()->where('created_at', '<', Carbon::now())->latest()->paginate($pageNum);
        $title = self::title('news', 'system');
        $seo = self::meta($title);

        return view('theme::news', compact('news', 'seo'));
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function lists($cid)
    {
        $cate = NewsCate::with('description')->flag()->where('slug', $cid)->first();

        if (!$cate) {
            return response()->view('theme::404', ['message' => 'Page not found !'], 404);
        }
        if (!$cate->isRoot()) {
            $root   = $cate->getRoot();
            $rootId = $root->id;
        } else {
            $rootId = $cate->id;
        }
        $pageNum  = Setting::get('news_paginate') ?: 20;
        $idArr    = $cate->getDescendantsAndSelf(['id'])->pluck('id')->toArray();
        $news = News::with(['cates', 'description'])->whereIn('pid', $idArr)->flag()->where('created_at', '<', Carbon::now())->latest()->paginate($pageNum);

        $title = '';
        if ($cate->description) {
            $title = $cate->description->seo_title ?: $cate->description->cname;
        }

        $seo = self::meta($title, $cate->description);

        return view('theme::news_list', compact('news', 'seo', 'cate', 'rootId'));
        
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function details($id)
    {
        $news = News::with(['cates.description', 'description'])->flag()->where('created_at', '<', Carbon::now())->where('slug', $id)->first();

        if (!$news) {
            return response()->view('theme::404', ['message' => 'Page not found !'], 404);
        }

        if (!$news->cates->isRoot()) {
            $root   = $news->cates->getRoot();
            $rootId = $root->id;
        } else {
            $rootId = $news->cates->id;
        }
        
        $tags = $news->tags()->with('description')->get();
        News::find($news->id)->update(['hits' => $news->hits + 1]);
        $title = '';

        if ($news->description) {
            $title = $news->description->seo_title ?: $news->description->title;
        }
        
        $seo = self::meta($title, $news->description, true);

        return view('theme::news_detail', compact('news', 'seo', 'tags', 'rootId'));
    }

   
}
