<?php

namespace App\Http\Controllers\Legacy;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class NewsController extends Controller
{
    public function show(Request $request, $id, $slug = null)
    {
        $id = (int) $id;

        try {
            $news = DB::table('news as t1')
                ->leftJoin('users as t2', 't1.user_id', '=', 't2.user_id')
                ->where('t1.news_id', $id)
                ->select('t1.*', 't2.uname', 't2.user_type', 't2.signature', 't2.icon')
                ->first();
        } catch (\Throwable $e) {
            $news = null;
        }

        if (empty($news)) {
            return redirect('/');
        }

        try {
            $comments = DB::table('news_comment as c')
                ->leftJoin('users as u', 'c.user_id', '=', 'u.user_id')
                ->where('c.news_id', $id)
                ->select('c.posted', 'c.message', 'c.user_id', 'u.user_type', 'u.signature', 'u.icon', 'u.uname')
                ->orderBy('c.posted')
                ->get();
        } catch (\Throwable $e) {
            $comments = collect();
        }

        $page_title = ($news->headline ?? 'News') . ' - SkinBase News';

        return view('legacy::news', compact('news', 'comments', 'page_title'));
    }
}
