<?php

namespace App\Http\Controllers;

use App\Services\DummyDataService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $bukuPinjam = DummyDataService::getBukuPinjamOffline($user);

        $isTelat = collect($bukuPinjam)->contains(function ($buku) {
            return $buku['sisa_hari'] < 0;
        });

        if ($isTelat && $user->role === 'siswa') {
            $user->is_banned = true;
        } 

        $stats = DummyDataService::getDashboardStats();
        $pengumuman = DummyDataService::getPengumuman();
        $pemberitahuan = DummyDataService::getPemberitahuan();
        $progressMembaca = DummyDataService::getProgressMembaca();
        $statistikBulanan = DummyDataService::getStatistikBulanan();
        $bukuPinjamOffline = $bukuPinjam;
        $bacaBukuOnline = DummyDataService::getBacaBukuOnline($user);
        $rekomendasiPembelajaran = DummyDataService::getRekomendasiPembelajaran();
        $personalNotif = DummyDataService::getNotifikasiForUser($user);

        // Cek apakah ada notifikasi denda aktif
        $dendaAlert = collect($personalNotif)->where('type', 'denda_active');

        // Menambahkan thumbnail YouTube ke setiap rekomendasi
        $rekomendasiPembelajaran = $rekomendasiPembelajaran->map(function ($item) {
            $videoId = $this->extractYouTubeId($item['youtube_link']);
            if ($videoId) {
                $item['thumbnail'] = "https://img.youtube.com/vi/{$videoId}/hqdefault.jpg";
            } else {
                $item['thumbnail'] = 'https://via.placeholder.com/150?text=No+Preview';
            }
            return $item;
        });

        $dendaAlert = collect($personalNotif)->where('type', 'denda_active');

        $hour = date('H');
        $greeting = "Selamat Pagi";
        if ($hour >= 12 && $hour < 15)
            $greeting = "Selamat Siang";
        elseif ($hour >= 15 && $hour < 18)
            $greeting = "Selamat Sore";
        elseif ($hour >= 18)
            $greeting = "Selamat Malam";

        return view('dashboard', compact(
            'user',
            'stats',
            'pengumuman',
            'pemberitahuan',
            'dendaAlert',
            'progressMembaca',
            'statistikBulanan',
            'bukuPinjamOffline',
            'bacaBukuOnline',
            'greeting',
            'rekomendasiPembelajaran'
        ))->with('notifikasi', $personalNotif);
    }
    
    /**
     * Helper function untuk mengekstrak ID video dari URL YouTube.
     */
    private function extractYouTubeId(string $url): ?string
    {
        preg_match('/(v=|vi=|youtu.be\/|embed\/|\/v\/|\?v=|\&v=)(.+?)\b/i', $url, $matches);
        return $matches[2] ?? null;
    }
}