<?php

namespace App\Http\Controllers\Legacy;

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

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

        // Filter downloads created today and join to artworks that are public, approved and published
        $today = Carbon::now()->toDateString();

        $query = ArtworkDownload::with(['artwork'])
            ->whereDate('created_at', $today)
            ->whereHas('artwork', function ($q) {
                $q->public()->published()->whereNull('deleted_at');
            })
            ->selectRaw('artwork_id, COUNT(*) as num_downloads')
            ->groupBy('artwork_id')
            ->orderByDesc('num_downloads');

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

        // Map to the legacy browse shape
        $paginator->getCollection()->transform(function ($row) {
            // $row is a stdClass with artwork_id and num_downloads
            $art = $row->artwork ?? null;
            // If Eloquent didn't eager load artwork (group queries sometimes don't), fetch it
            if (! $art && isset($row->artwork_id)) {
                $art = \App\Models\Artwork::find($row->artwork_id);
            }

            $name = $art->title ?? null;
            $picture = $art->file_name ?? null;
            $ext = pathinfo($picture ?? '', PATHINFO_EXTENSION) ?: 'jpg';
            $encoded = null; // legacy encoding unavailable; leave null
            $present = $art ? \App\Services\ThumbnailPresenter::present($art, 'md') : null;
            $thumb = $present ? $present['url'] : 'https://files.skinbase.org/default/missing_md.webp';
            $categoryId = $art->categories->first()->id ?? null;

            return (object) [
                'id' => $art->id ?? null,
                'name' => $name,
                'picture' => $picture,
                'slug' => $art->slug ?? Str::slug($name ?? ''),
                'ext' => $ext,
                'encoded' => $encoded,
                'thumb' => $thumb,
                'thumb_srcset' => $thumb,
                'category' => $categoryId,
                'num_downloads' => $row->num_downloads ?? 0,
                'gid_num' => $categoryId ? ((int) $categoryId % 5) * 5 : 0,
            ];
        });

        $page_title = 'Today Downloaded Artworks';

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