<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

class LegacyController extends Controller
{
    public function index(Request $request)
    {
        $page_title = 'Skinbase - Photography, Skins & Wallpapers';
        $page_meta_description = 'Skinbase legacy home, rendered via Laravel.';
        $page_meta_keywords = 'wallpapers, skins, photography, community';

        [$featured, $memberFeatured] = $this->featured();
        $latestUploads = $this->latestUploads();
        $forumNews = $this->forumNews();
        $ourNews = $this->ourNews();
        $latestForumActivity = $this->latestForumActivity();

        return view('legacy::home', compact(
            'page_title',
            'page_meta_description',
            'page_meta_keywords',
            'featured',
            'memberFeatured',
            'latestUploads',
            'forumNews',
            'ourNews',
            'latestForumActivity'
        ));
    }

    public function browse(Request $request)
    {
        $page_title = 'Browse Uploaded Artworks - Photography, Wallpapers and Skins at SkinBase';
        $page_meta_description = "Browse Uploaded Photography, Wallpapers and Skins to one of the world's oldest online social community for artists and art enthusiastse.";
        $page_meta_keywords = 'photography, wallpapers, skins, stock, browse, social, community, artist, picture, photo';

        $perPage = 50;

        try {
            $artworks = DB::table('wallz as w')
                ->leftJoin('categories as c', 'w.category', '=', 'c.id')
                ->leftJoin('users as u', 'w.user_id', '=', 'u.user_id')
                ->select('w.id', 'w.name', 'w.picture', 'w.category', 'w.datum', DB::raw('c.name as category_name'), 'u.uname')
                ->where('w.approved', 1)
                ->where('w.public', 'Y')
                ->orderByDesc('w.datum')
                ->paginate($perPage)
                ->withQueryString();
        } catch (\Throwable $e) {
            $placeholder = collect([
                (object) [
                    'id' => 0,
                    'name' => 'Sample Artwork',
                    'picture' => 'https://files.skinbase.org/default/missing_md.webp',
                    'category' => null,
                    'datum' => now(),
                    'category_name' => 'Photography',
                    'uname' => 'Skinbase',
                ],
            ]);

            $artworks = new LengthAwarePaginator(
                $placeholder,
                $placeholder->count(),
                $perPage,
                1,
                ['path' => $request->url(), 'query' => $request->query()]
            );
        }

        return view('legacy::browse', compact('page_title', 'page_meta_description', 'page_meta_keywords', 'artworks'));
    }

    public function category(Request $request, string $group, ?string $slug = null, ?int $id = null)
    {
        $group = Str::title($group);
        $defaults = [
            'Skins' => 1,
            'Wallpapers' => 2,
            'Photography' => 3,
            'Other' => 4,
        ];

        if (!$id && $slug && ctype_digit($slug)) {
            $id = (int) $slug;
        }

        $id = $id ?: ($defaults[$group] ?? null);
        if (!$id || $id < 1) {
            return redirect('/');
        }

        $page_title = $group;
        $page_meta_description = $group . ' artworks on Skinbase';
        $page_meta_keywords = strtolower($group) . ', skinbase, artworks, wallpapers, photography, skins';

            try {
            $category = DB::table('categories')
                ->select(DB::raw('id as category_id'), DB::raw('name as category_name'), 'description', DB::raw('parent_id as rootid'), DB::raw('content_type_id as section_id'))
                ->where('id', $id)
                ->first();
        } catch (\Throwable $e) {
            $category = null;
        }

        if (!$category) {
            return redirect('/');
        }

        $perPage = 40;

        try {
            $base = DB::table('wallz as t1')
                ->select('t1.id', 't1.name', 't1.picture', 't3.uname', 't1.category', DB::raw('t2.name as category_name'))
                ->join('categories as t2', 't1.category', '=', 't2.id')
                ->leftJoin('users as t3', 't1.user_id', '=', 't3.user_id')
                ->where('t1.approved', 1)
                ->where(function ($q) use ($id, $category) {
                    $q->where('t1.category', (int) $id);
                    if ($category->rootid > 0) {
                        $q->orWhere('t1.rootid', (int) $id);
                    }
                })
                ->orderByDesc('t1.datum');

            $artworks = $base->paginate($perPage)->withQueryString();
        } catch (\Throwable $e) {
            $artworks = new LengthAwarePaginator([], 0, $perPage, 1, [
                'path' => $request->url(),
                'query' => $request->query(),
            ]);
        }

        try {
            $subcategories = DB::table('categories')
                ->select(DB::raw('id as category_id'), DB::raw('name as category_name'))
                ->where('parent_id', $id)
                ->orderBy('category_name')
                ->get();

            if ($subcategories->isEmpty() && $category->rootid) {
                $subcategories = DB::table('categories')
                    ->select(DB::raw('id as category_id'), DB::raw('name as category_name'))
                    ->where('parent_id', $category->rootid)
                    ->orderBy('category_name')
                    ->get();
            }

            if ($subcategories->isEmpty()) {
                $subcategories = DB::table('skupine')
                    ->select('category_id', 'category_name')
                    ->where('rootid', $id)
                    ->orderBy('category_name')
                    ->get();
            }
        } catch (\Throwable $e) {
            try {
                $subcategories = DB::table('skupine')
                    ->select('category_id', 'category_name')
                    ->where('rootid', $id)
                    ->orderBy('category_name')
                    ->get();
            } catch (\Throwable $e2) {
                $subcategories = collect();
            }
        }

        return view('legacy::category', compact(
            'group',
            'category',
            'artworks',
            'subcategories',
            'page_title',
            'page_meta_description',
            'page_meta_keywords'
        ));
    }

    public function browseCategories()
    {
        $page_title = 'Browse Categories';
        $page_meta_description = 'Browse categories across Photography, Wallpapers, Skins and more on Skinbase.';
        $page_meta_keywords = 'categories, photography, wallpapers, skins, browse';

        // Load top-level categories (section_id = 0 AND rootid = 0) like the legacy page
        try {
            $categories = DB::table('categories')
                ->select(DB::raw('id as category_id'), DB::raw('name as category_name'), 'description')
                ->where('content_type_id', 0)
                ->where(DB::raw('parent_id'), 0)
                ->orderBy('id')
                ->get();

            // Fallback to legacy table name if empty
            if ($categories->isEmpty()) {
                $categories = DB::table('skupine')
                    ->select('category_id', 'category_name', 'description')
                    ->where('section_id', 0)
                    ->where('rootid', 0)
                    ->orderBy('category_id')
                    ->get();
            }
        } catch (\Throwable $e) {
            try {
                $categories = DB::table('skupine')
                    ->select('category_id', 'category_name', 'description')
                    ->where('section_id', 0)
                    ->where('rootid', 0)
                    ->orderBy('category_id')
                    ->get();
            } catch (\Throwable $e2) {
                $categories = collect();
            }
        }

        // Fetch all subcategories in one query to avoid N+1 and group them by parent (section_id)
        $subgroups = collect();
        if ($categories->isNotEmpty()) {
            $ids = $categories->pluck('category_id')->unique()->values()->all();
            try {
                $subs = DB::table('categories')
                    ->select(DB::raw('id as category_id'), DB::raw('name as category_name'), 'image as picture', DB::raw('content_type_id as section_id'))
                    ->whereIn('content_type_id', $ids)
                    ->orderBy('category_name')
                    ->get();

                if ($subs->isEmpty()) {
                    // fallback to skupine table naming
                    $subs = DB::table('skupine')
                        ->select('category_id', 'category_name', 'picture', 'section_id')
                        ->whereIn('section_id', $ids)
                        ->orderBy('category_name')
                        ->get();
                }

                $subgroups = $subs->groupBy('section_id');
            } catch (\Throwable $e) {
                $subgroups = collect();
            }
        }

        return view('legacy::categories', compact(
            'categories',
            'subgroups',
            'page_title',
            'page_meta_description',
            'page_meta_keywords'
        ));
    }

    /**
     * Fetch featured artworks with graceful fallbacks.
     */
    private function featured(): array
    {
        $featured = null;
        $memberFeatured = null;

        try {
            $featured = DB::table('featured_works as fw')
                ->leftJoin('wallz as w', 'fw.artwork_id', '=', 'w.id')
                ->leftJoin('users as u', 'w.user_id', '=', 'u.user_id')
                ->select('w.id', 'w.name', 'w.picture', 'u.uname', 'fw.post_date')
                ->orderByDesc('fw.post_date')
                ->first();

            $memberFeatured = DB::table('users_opinions as o')
                ->leftJoin('wallz as w', 'o.artwork_id', '=', 'w.id')
                ->leftJoin('users as u', 'w.user_id', '=', 'u.user_id')
                ->select(DB::raw('COUNT(*) AS votes'), 'w.id', 'w.name', 'w.picture', 'u.uname')
                ->whereRaw('o.post_date > SUBDATE(CURRENT_DATE(), INTERVAL 30 DAY)')
                ->where('o.score', 4)
                ->groupBy('o.artwork_id', 'w.id', 'w.name', 'w.picture', 'u.uname')
                ->orderByDesc('votes')
                ->limit(1)
                ->first();
        } catch (\Throwable $e) {
            // Fail soft; render placeholders
        }

        if (!$featured) {
            $featured = (object) [
                'id' => 0,
                'name' => 'Featured Artwork',
                'picture' => 'https://files.skinbase.org/default/missing_md.webp',
                'uname' => 'Skinbase',
            ];
        }

        if (!$memberFeatured) {
            $memberFeatured = (object) [
                'id' => 0,
                'name' => 'Members Pick',
                'picture' => 'https://files.skinbase.org/default/missing_md.webp',
                'uname' => 'Skinbase',
                'votes' => 0,
            ];
        }

        return [$featured, $memberFeatured];
    }

    private function forumNews(): array
    {
        try {
            return DB::table('forum_threads as t1')
                ->leftJoin('users as t2', 't1.user_id', '=', 't2.id')
                ->leftJoin('forum_categories as c', 't1.category_id', '=', 'c.id')
                ->selectRaw('t1.id as topic_id, t1.title as topic, t1.views, t1.created_at as post_date, t1.content as preview, COALESCE(t2.name, ?) as uname', ['Unknown'])
                ->whereNull('t1.deleted_at')
                ->where(function ($query) {
                    $query->where('t1.category_id', 2876)
                        ->orWhereIn('c.slug', ['news', 'forum-news']);
                })
                ->orderByDesc('t1.created_at')
                ->limit(8)
                ->get()
                ->toArray();
        } catch (\Throwable $e) {
            return [];
        }
    }

    private function ourNews(): array
    {
        try {
            return DB::table('news as t1')
                ->join('news_categories as t2', 't1.category_id', '=', 't2.category_id')
                ->join('users as t3', 't1.user_id', '=', 't3.user_id')
                ->select(
                    't1.news_id',
                    't1.headline',
                    't1.picture',
                    't1.preview',
                    't1.create_date',
                    't1.views',
                    't2.category_name',
                    't3.uname',
                    DB::raw('(SELECT COUNT(*) FROM news_comment WHERE news_id = t1.news_id) AS num_comments')
                )
                ->orderByDesc('t1.create_date')
                ->limit(5)
                ->get()
                ->toArray();
        } catch (\Throwable $e) {
            return [];
        }
    }

    private function latestForumActivity(): array
    {
        try {
            return DB::table('forum_threads as t1')
                ->leftJoin('forum_categories as c', 't1.category_id', '=', 'c.id')
                ->leftJoin('forum_posts as p', function ($join) {
                    $join->on('p.thread_id', '=', 't1.id')
                        ->whereNull('p.deleted_at');
                })
                ->selectRaw('t1.id as topic_id, t1.title as topic, COUNT(p.id) AS numPosts')
                ->whereNull('t1.deleted_at')
                ->where(function ($query) {
                    $query->where('t1.category_id', '<>', 2876)
                        ->orWhereNull('t1.category_id');
                })
                ->where(function ($query) {
                    $query->whereNull('c.slug')
                        ->orWhereNotIn('c.slug', ['news', 'forum-news']);
                })
                ->groupBy('t1.id', 't1.title')
                ->orderByDesc('t1.last_post_at')
                ->orderByDesc('t1.created_at')
                ->limit(10)
                ->get()
                ->toArray();
        } catch (\Throwable $e) {
            return [];
        }
    }

    /**
     * Load latest uploads either from cached JSON or DB.
     */
    private function latestUploads(): array
    {
        $uploads = [];

        // Try cache file first
        $cachePath = base_path('oldSite/www/cache/latest_uploads.json');
        if (File::exists($cachePath)) {
            $json = File::get($cachePath);
            $uploads = json_decode($json, true) ?: [];
        }

        // Fallback to DB if cache missing
        if (empty($uploads)) {
            try {
                $uploads = DB::table('wallz as w')
                    ->leftJoin('users as u', 'w.user_id', '=', 'u.user_id')
                    ->leftJoin('categories as c', 'w.category', '=', 'c.id')
                    ->where('w.approved', 1)
                    ->orderByDesc('w.datum')
                    ->limit(20)
                    ->get()
                    ->map(function ($row) {
                        return [
                            'id' => $row->id,
                            'name' => $row->name,
                            'picture' => $row->picture,
                            'uname' => $row->uname,
                            'category_name' => $row->category_name ?? $row->name ?? '',
                        ];
                    })
                    ->toArray();
            } catch (\Throwable $e) {
                // Soft fail
                $uploads = [];
            }
        }

        // Final fallback placeholders
        if (empty($uploads)) {
            $uploads = [
                [
                    'id' => 1,
                    'name' => 'Sample Artwork',
                    'picture' => 'https://files.skinbase.org/default/missing_md.webp',
                    'uname' => 'Skinbase',
                    'category_name' => 'Photography',
                ],
            ];
        }

        return $uploads;
    }
}
