<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Video;
use App\Models\Workshop;

class DashboardController extends Controller
{
    public function index()
    {
        $user = auth()->user();

        if (!$user) {
            return response()->json([
                'message' => 'Utilizador não autenticado',
                'data' => null,
                'errors' => null,
            ], 404);
        }

        $userId = $user->id;
        $role = $user->role_id;
        $userSector = $user->sector_id;

        $videos = Video::select('id', 'title', 'thumbnail', 'is_active', 'order')
            ->where('is_active', true)
            ->whereDoesntHave('views', function ($q) use ($user) {
                $q->where('user_id', $user->id);
            })
            ->when($role !== 1, fn($q) => $q->whereHas('sectors', function ($s) use ($userSector) {
                $s->where('sectors.id', $userSector)
                  ->orWhere('sectors.slug', "global");
            }))
            ->orderBy('order', 'asc')
            ->limit(3)
            ->get()
            ->map(function ($video) {
                return [
                    'id' => $video->id,
                    'title' => $video->title,
                    'thumbnail' => $video->thumbnail,
                    'is_active' => $video->is_active,
                    'watched' => false,
                ];
            });

            if ($role !== 1) {
                $stats = Video::query()
                    ->where('is_active', true)
                    ->whereHas('sectors', function ($s) use ($userSector) {
                        $s->where('sectors.id', $userSector)
                          ->orWhere('sectors.slug', "global");
                    })
                    ->selectRaw('
                        COUNT(*) as active_count,
                        COUNT(CASE WHEN EXISTS (
                            SELECT 1 FROM video_views
                            WHERE video_views.video_id = videos.id
                            AND video_views.user_id = ?
                        ) THEN 1 END) as watched_count
                    ', [$userId])
                    ->first();
            } else {
                $stats = Video::selectRaw('
                    COUNT(CASE WHEN is_active = 1 THEN 1 END) as active_count,
                    COUNT(CASE WHEN is_active = 1 AND EXISTS (
                        SELECT 1 FROM video_views
                        WHERE video_views.video_id = videos.id
                        AND video_views.user_id = ?
                    ) THEN 1 END) as watched_count
                ', [$userId])
                    ->first();
            }

        $workshops = Workshop::select(['id', 'title', 'image', 'date', 'time_start', 'time_end', 'status'])
            ->with(['users:id'])
            ->where('status', 'pending')
            ->orderBy('date', 'asc')
            ->orderBy('time_start', 'asc')
            ->limit(3)
            ->get()
            ->map(function ($workshop) {
                return [
                    'id' => $workshop->id,
                    'title' => $workshop->title,
                    'image' => $workshop->image,
                    'date' => $workshop->date,
                    'time_start' => $workshop->time_start,
                    'time_end' => $workshop->time_end,
                    'status' => $workshop->status,
                    'users' => $workshop->users->pluck('id'),
                ];
            });

        if ($role === 1) {
            $workshopsCount = Workshop::selectRaw('COUNT(CASE WHEN status = \'pending\' THEN 1 END) as workshops_count')->first();
        } else {
            $workshopsCount = Workshop::selectRaw('
                COUNT(CASE WHEN status = \'pending\' THEN 1 END) as workshops_count,
                COUNT(CASE WHEN status = \'pending\' AND EXISTS (
                    SELECT 1 FROM user_workshop
                    WHERE user_workshop.workshop_id = workshops.id
                    AND user_workshop.user_id = ?
                ) THEN 1 END) as workshops_inscribed
            ', [$userId])
                ->first();
        }

        return response()->json([
            'videos' => $videos,
            'videosWatched' => $stats->watched_count ?? 0,
            'videosCount' => $stats->active_count ?? 0,
            'workshops' => $workshops,
            'workshopsCount' => $workshopsCount->workshops_count ?? 0,
            'workshopsInscribed' => $workshopsCount->workshops_inscribed ?? 0,
            'userId' => $userId,
            'role' => $role,
        ], 200);
    }
}
