<?php

namespace App\Http\Controllers\Frontend;

use App\Models\Album;
use App\Models\Setting;
use App\Models\AlbumCate;

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

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

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

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function lists($cid)
    {
        $cate = AlbumCate::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('album_paginate') ?: 6;
        $idArr    = $cate->getDescendantsAndSelf(['id'])->pluck('id')->toArray();
        $albums   = Album::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::album_list', compact('albums', 'seo', 'cate', 'rootId'));
        
    }

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

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

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

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

        return view('theme::album_detail', compact('album', 'seo', 'tags', 'rootId'));
    }

   
}
