<?php

namespace App\Http\Controllers\User;

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

class MonthlyCommentatorsController extends Controller
{
    public function index(Request $request)
    {
        $hits = 30;
        $page = max(1, (int) $request->query('page', 1));

        $query = DB::table('artwork_comments as t1')
            ->leftJoin('users as t2', 't1.user_id', '=', 't2.id')
            ->where('t1.user_id', '>', 0)
            ->whereRaw('t1.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)')
            ->select(
                't2.id as user_id',
                't2.username as user_username',
                DB::raw('COALESCE(t2.username, t2.name, "User") as uname'),
                DB::raw('COUNT(*) as num_comments')
            )
            ->groupBy('t2.id')
            ->orderByDesc('num_comments');

        $rows = $query->paginate($hits)->withQueryString();

        $page_title = 'Monthly Top Commentators';

        return view('web.comments.monthly', compact('page_title', 'rows'));
    }
}
