<?php

namespace App\Http\Controllers\User;

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

class TopAuthorsController extends Controller
{
    public function index(Request $request)
    {
        $perPage = 20;
        $metric = strtolower($request->query('metric', 'views'));

        if (! in_array($metric, ['views', 'downloads'])) {
            $metric = 'views';
        }

        $sub = Artwork::query()
            ->join('artwork_stats', 'artwork_stats.artwork_id', '=', 'artworks.id')
            ->where('artworks.is_public', true)
            ->where('artworks.is_approved', true)
            ->whereNotNull('artworks.published_at')
            ->where('artworks.published_at', '<=', now())
            ->whereNull('artworks.deleted_at')
            ->selectRaw('artworks.user_id, SUM(artwork_stats.' . $metric . ') as total_metric, MAX(artworks.published_at) as latest_published')
            ->groupBy('artworks.user_id');

        $query = DB::table(DB::raw('(' . $sub->toSql() . ') as t'))
            ->mergeBindings($sub->getQuery())
            ->join('users as u', 'u.id', '=', 't.user_id')
            ->leftJoin('user_profiles as up', 'up.user_id', '=', 'u.id')
            ->select('u.id as user_id', 'u.name as uname', 'u.username', 'up.avatar_hash', 't.total_metric', 't.latest_published')
            ->orderByDesc('t.total_metric')
            ->orderByDesc('t.latest_published');

        $authors = $query->paginate($perPage)->withQueryString();

        $authors->getCollection()->transform(function ($row) use ($metric) {
            return (object) [
                'user_id' => $row->user_id,
                'uname' => $row->uname,
                'username' => $row->username,
                'avatar_hash' => $row->avatar_hash,
                'total' => (int) $row->total_metric,
                'metric' => $metric,
            ];
        });

        $page_title = 'Top Creators';

        return view('web.authors.top', compact('page_title', 'authors', 'metric'));
    }
}
