<?php

namespace App\Http\Controllers\User;

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

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

        $base = DB::table('artwork_favourites as t1')
            ->join('artworks as t2', 't1.artwork_id', '=', 't2.id')
            ->whereNotNull('t2.published_at')
            ->select('t2.id', 't2.title as name', 't2.slug', DB::raw('NULL as picture'), DB::raw('NULL as category'), DB::raw('COUNT(*) as num'))
            ->groupBy('t2.id', 't2.title', 't2.slug');

        try {
            $paginator = (clone $base)->orderBy('num', 'desc')->paginate($hits)->withQueryString();
        } catch (\Throwable $e) {
            $paginator = collect();
        }

        if ($paginator && method_exists($paginator, 'getCollection')) {
            $artworkLookup = Artwork::query()
                ->with([
                    'user:id,name,username',
                    'categories' => function ($query) {
                        $query->select('categories.id', 'categories.name', 'categories.slug', 'categories.sort_order');
                    },
                ])
                ->whereIn('id', $paginator->getCollection()->pluck('id')->filter()->map(fn ($id) => (int) $id)->all())
                ->get()
                ->keyBy('id');

            $paginator->getCollection()->transform(function ($row) use ($artworkLookup) {
                $row->slug = $row->slug ?? Str::slug($row->name ?? '');
                $ext = pathinfo($row->picture ?? '', PATHINFO_EXTENSION) ?: 'jpg';
                $encoded = \App\Helpers\Thumb::encodeId((int) $row->id);
                $row->encoded = $encoded;
                $row->ext = $ext;

                /** @var \App\Models\Artwork|null $art */
                $art = $artworkLookup->get((int) $row->id);
                $primaryCategory = $art?->categories?->sortBy('sort_order')->first();
                $author = $art?->user;

                try {
                    $present = \App\Services\ThumbnailPresenter::present($art ?: (array) $row, 'md');
                    $row->thumb = $row->thumb ?? $present['url'];
                    $row->thumb_srcset = $row->thumb_srcset ?? ($present['srcset'] ?? $present['url']);
                } catch (\Throwable $e) {
                    $present = \App\Services\ThumbnailPresenter::present((array) $row, 'md');
                    $row->thumb = $row->thumb ?? $present['url'];
                    $row->thumb_srcset = $row->thumb_srcset ?? ($present['srcset'] ?? $present['url']);
                }

                $row->thumb_url = $row->thumb ?? null;
                $row->gid_num = ((int)($row->category ?? 0) % 5) * 5;
                $row->url = url('/art/' . (int) $row->id . '/' . ($row->slug ?: Str::slug($row->name ?? 'artwork')));
                $row->width = $art?->width;
                $row->height = $art?->height;
                $row->content_type_name = $primaryCategory?->contentType?->name ?? '';
                $row->content_type_slug = $primaryCategory?->contentType?->slug ?? '';
                $row->category_name = $primaryCategory->name ?? '';
                $row->category_slug = $primaryCategory->slug ?? '';
                $row->uname = $author->name ?? 'Skinbase';
                $row->username = $author->username ?? $author->name ?? '';
                $row->avatar_url = $author
                    ? AvatarUrl::forUser((int) $author->getKey(), null, 64)
                    : AvatarUrl::default();
                $row->favourites = (int) ($row->num ?? 0);

                return $row;
            });
        }

        $page_title = 'Top Favourites';

        return view('legacy::top-favourites', ['page_title' => $page_title, 'artworks' => $paginator]);
    }
}
