<?php

namespace App\Http\Controllers\Frontend;

use App\Models\Cases;
use App\Models\Setting;
use App\Models\CaseCate;

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

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $title = self::title('case');
        $seo = self::meta($title);

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

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function lists($cid)
    {
        $cate = CaseCate::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('case_paginate') ?: 6;
        $idArr    = $cate->getDescendantsAndSelf(['id'])->pluck('id')->toArray();
        $cases    = Cases::with(['cates', 'description'])->whereIn('pid', $idArr)->flag()->latest()->paginate($pageNum);

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

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

        return view('theme::case_list', compact('cases', 'seo', 'cate', 'rootId'));
        
    }

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

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

        if (!$case->cates->isRoot()) {
            $root   = $case->cates->getRoot();
            $rootId = $root->id;
        } else {
            $rootId = $case->cates->id;
        }

        $tags = $case->tags()->with('description')->get();
        Cases::find($case->id)->update(['hits' => $case->hits + 1]);
        $title = '';
        
        if ($case->description) {
            $title = $case->description->seo_title ?: $case->description->title;
        }
        
        $seo = self::meta($title, $case->description, true);

        return view('theme::case_detail', compact('case', 'seo', 'tags', 'rootId'));
    }

   
}
