<?php

namespace App\Http\Controllers\Legacy;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use App\Models\UserFavorite;

class FavouritesController extends Controller
{
    public function index(Request $request, $userId = null, $username = null)
    {
        $userId = $userId ? (int)$userId : ($request->user()->id ?? null);

        $page = max(1, (int) $request->query('page', 1));
        $hits = 20;
        $start = ($page - 1) * $hits;

        $total = 0;
        $results = collect();

        // Prefer Eloquent model if table exists
        try {
            $schema = DB::getSchemaBuilder();
        } catch (\Throwable $e) {
            $schema = null;
        }

        // Detect user id and name columns for compatibility with legacy schema
        $userIdCol = Schema::hasColumn('users', 'user_id') ? 'user_id' : 'id';
        $userNameCol = null;
        foreach (['uname', 'username', 'name'] as $col) {
            if (Schema::hasColumn('users', $col)) {
                $userNameCol = $col;
                break;
            }
        }

        if ($schema && $schema->hasTable('user_favorites') && class_exists(UserFavorite::class)) {
            try {
                $query = UserFavorite::with(['artwork.user'])
                    ->where('user_id', $userId)
                    ->orderByDesc('created_at')
                    ->orderByDesc('artwork_id');

                $total = (int) $query->count();

                $favorites = $query->skip($start)->take($hits)->get();

                $results = $favorites->map(function ($fav) use ($userNameCol) {
                    $art = $fav->artwork;
                    if (! $art) {
                        return null;
                    }
                    $item = (object) $art->toArray();
                    $item->uname = ($userNameCol && isset($art->user)) ? ($art->user->{$userNameCol} ?? null) : null;
                    $item->datum = $fav->created_at;
                    return $item;
                })->filter();
            } catch (\Throwable $e) {
                $total = 0;
                $results = collect();
            }
        } else {
            // Fallback to legacy tables
            try {
                if ($schema && $schema->hasTable('artworks_favourites')) {
                    $favTable = 'artworks_favourites';
                } elseif ($schema && $schema->hasTable('favourites')) {
                    $favTable = 'favourites';
                } else {
                    $favTable = null;
                }

                if ($schema && $schema->hasTable('artworks')) {
                    $artTable = 'artworks';
                } elseif ($schema && $schema->hasTable('wallz')) {
                    $artTable = 'wallz';
                } else {
                    $artTable = null;
                }
            } catch (\Throwable $e) {
                $favTable = null;
                $artTable = null;
            }

            if ($favTable && $artTable) {
                try {
                    $total = (int) DB::table($favTable)->where('user_id', $userId)->count();

                    $t2JoinCol = 't2.' . $userIdCol;
                    $t2NameSelect = $userNameCol ? DB::raw("t2.{$userNameCol} as uname") : DB::raw("'' as uname");

                    $results = DB::table($favTable . ' as t1')
                        ->rightJoin($artTable . ' as t3', 't1.artwork_id', '=', 't3.id')
                        ->leftJoin('users as t2', 't3.user_id', '=', $t2JoinCol)
                        ->where('t1.user_id', $userId)
                        ->select('t3.*', $t2NameSelect, 't1.datum')
                        ->orderByDesc('t1.datum')
                        ->orderByDesc('t1.artwork_id')
                        ->skip($start)
                        ->take($hits)
                        ->get();
                } catch (\Throwable $e) {
                    $total = 0;
                    $results = collect();
                }
            }
        }

        $results = collect($results)->filter()->values()->transform(function ($row) {
            $row->name = $row->name ?? '';
            $row->slug = $row->slug ?? Str::slug($row->name);
            $row->encoded = isset($row->id) ? app(\App\Helpers\Thumb::class)::encodeId((int)$row->id) : null;
            return $row;
        });

        $page_title = ($username ?: ($userNameCol ? DB::table('users')->where($userIdCol, $userId)->value($userNameCol) : '')) . ' Favourites';

        return view('legacy::favourites', [
            'results' => $results,
            'page_title' => $page_title,
            'user_id' => $userId,
            'page' => $page,
            'hits' => $hits,
            'total' => $total,
        ]);
    }

    public function destroy(Request $request, $userId, $artworkId)
    {
        $auth = $request->user();
        if (! $auth || $auth->id != (int)$userId) {
            abort(403);
        }

        $favTable = Schema::hasTable('user_favorites') ? 'user_favorites' : (Schema::hasTable('artworks_favourites') ? 'artworks_favourites' : 'favourites');

        DB::table($favTable)->where('user_id', (int)$userId)->where('artwork_id', (int)$artworkId)->delete();

        return redirect()->route('legacy.favourites', ['id' => $userId])->with('status', 'Removed from favourites');
    }
}
