<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\ArtworkDownload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class TodayDownloadsController extends Controller
{
    public function index(Request $request)
    {
        $hits = 30;

        $today = Carbon::now()->toDateString();
        $artworkVisibilityScope = function ($q) {
            $q->public()->published()->whereNull('deleted_at');
        };
        $hasTodayDownloads = ArtworkDownload::query()
            ->whereHas('artwork', $artworkVisibilityScope)
            ->whereDate('created_at', $today)
            ->exists();

        $query = ArtworkDownload::with([
            'artwork.user:id,name,username',
            'artwork.user.profile:user_id,avatar_hash',
            'artwork.categories:id,name,slug',
        ])
            ->whereHas('artwork', $artworkVisibilityScope)
            ->selectRaw('artwork_id, COUNT(*) as num_downloads')
            ->groupBy('artwork_id')
            ->orderByDesc('num_downloads');

        if ($hasTodayDownloads) {
            $query->whereDate('created_at', $today);
        } else {
            $fallbackDownloadIds = ArtworkDownload::query()
                ->whereHas('artwork', $artworkVisibilityScope)
                ->orderByDesc('created_at')
                ->limit(1000)
                ->pluck('id');

            if ($fallbackDownloadIds->isEmpty()) {
                $query->whereRaw('1 = 0');
            } else {
                $query->whereIn('id', $fallbackDownloadIds->all());
            }
        }

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

        $paginator->getCollection()->transform(function ($row) {
            $art = $row->artwork ?? null;
            if (! $art && isset($row->artwork_id)) {
                $art = \App\Models\Artwork::find($row->artwork_id);
            }

            if (! $art) {
                return (object) [
                    'id' => null,
                    'name' => 'Artwork',
                    'slug' => 'artwork',
                    'thumb' => 'https://files.skinbase.org/default/missing_md.webp',
                    'thumb_url' => 'https://files.skinbase.org/default/missing_md.webp',
                    'thumb_srcset' => 'https://files.skinbase.org/default/missing_md.webp',
                    'category_name' => '',
                    'category_slug' => '',
                    'num_downloads' => $row->num_downloads ?? 0,
                ];
            }

            $name = $art->title ?? null;
            $picture = $art->file_name ?? null;
            $ext = pathinfo($picture ?? '', PATHINFO_EXTENSION) ?: 'jpg';
            $encoded = null;
            $present = $art ? \App\Services\ThumbnailPresenter::present($art, 'md') : null;
            $thumb = $present ? $present['url'] : 'https://files.skinbase.org/default/missing_md.webp';
            $primaryCategory = $art->categories->first();
            $categoryId = $primaryCategory->id ?? null;
            $categoryName = $primaryCategory->name ?? '';
            $categorySlug = $primaryCategory->slug ?? '';
            $avatarHash = $art->user?->profile?->avatar_hash;

            return (object) [
                'id' => $art->id ?? null,
                'name' => $name,
                'picture' => $picture,
                'slug' => $art->slug ?? Str::slug($name ?? ''),
                'ext' => $ext,
                'encoded' => $encoded,
                'thumb' => $thumb,
                'thumb_url' => $thumb,
                'thumb_srcset' => $thumb,
                'category' => $categoryId,
                'category_name' => $categoryName,
                'category_slug' => $categorySlug,
                'uname' => $art->user->name ?? 'Skinbase',
                'username' => $art->user->username ?? '',
                'avatar_url' => \App\Support\AvatarUrl::forUser((int) ($art->user->id ?? 0), $avatarHash, 64),
                'width' => $art->width,
                'height' => $art->height,
                'published_at' => $art->published_at,
                'num_downloads' => $row->num_downloads ?? 0,
                'gid_num' => $categoryId ? ((int) $categoryId % 5) * 5 : 0,
            ];
        });

        $page_title = $hasTodayDownloads
            ? 'Today Downloaded Artworks'
            : 'Most Downloaded from Latest 1000 Downloads';

        return view('web.downloads.today', [
            'page_title' => $page_title,
            'artworks' => $paginator,
            'display_date' => $today,
            'is_fallback_window' => ! $hasTodayDownloads,
        ]);
    }
}
