<?php

namespace App\Http\Controllers;

use App\Jobs\RestoreXenForoCommentsThread;
use App\Models\Entry;
use Artesaos\SEOTools\Facades\SEOTools;
use Illuminate\Http\Request;

class ModCPController extends Controller
{
    public function __construct()
    {
        SEOTools::setTitle('ModCP');
    }

    public function index()
    {
        $stats = [
            'pending' => Entry::where('state', 'pending')->count(),
            'locked' => Entry::where('state', 'locked')->count(),
            'total' => Entry::count()
        ];

        if( \Auth::user()->can('is-admin') ){
            $stats['draft'] = Entry::where('state', 'draft')->count();
            $stats['hidden'] = Entry::where('state', 'hidden')->count();
            $stats['deleted'] = Entry::where('state', 'deleted')->count();
        }

        $recentDeleted = Entry::onlyTrashed()->latest('deleted_at')->limit(5)->get();

        return view('modcp.index', compact('stats', 'recentDeleted'));
    }

    public function locked()
    {
        $entries = Entry::where('state', 'locked')
            ->with(['game.platform', 'authors'])
            ->latest()->paginate(25);

        return view('modcp.entries', compact('entries'))->with('pageTitle', "Locked Entries")->with('state', 'locked');
    }

    public function draft()
    {
        $entries = Entry::where('state', 'draft')
            ->with(['game.platform', 'authors'])
            ->latest()->paginate(25);

        return view('modcp.entries', compact('entries'))->with('pageTitle', "Draft Entries")->with('state', 'draft');
    }

    public function hidden()
    {
        $entries = Entry::where('state', 'hidden')
            ->with(['game.platform', 'authors'])
            ->latest()->paginate(25);

        return view('modcp.entries', compact('entries'))->with('pageTitle', "Hidden Entries")->with('state', 'hidden');
    }

    public function deleted()
    {
        $entries = Entry::onlyTrashed()
            ->with(['game.platform', 'authors'])
            ->latest('deleted_at')->paginate(25);
        return view('modcp.deleted', compact('entries'));
    }

    public function restore(Entry $entry)
    {
        $entry->restore();
        RestoreXenForoCommentsThread::dispatch($entry->comments_thread_id);
        $entry->update(['state' => 'draft']);
        return back()->with('success', "Entry restored");
    }

    public function destroy(Entry $entry)
    {
        $entry->forceDelete();
        return back()->with('success', "Entry permanently deleted");
    }

    public function logs()
    {
        return view('modcp.logs');
    }
}
