<?php

namespace App\Http\Controllers\Guru;

use App\Http\Controllers\Controller;
use App\Models\Book;
use App\Models\Category;
use App\Models\Loan;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LaporanController extends Controller
{
    public function index()
    {
        // 1. Laporan Minat Baca (Buku Terpopuler & Kategori Populer)
        $bukuTerpopuler = Book::withCount('loans')
            ->orderBy('loans_count', 'desc')
            ->take(3)
            ->get()
            ->map(fn($book) => [
                'judul' => $book->judul,
                'penulis' => $book->penulis,
                'total_pembaca' => $book->loans_count,
                'cover' => $book->cover,
            ]);

        $kategoriPopuler = Category::withCount(['books as total_pembaca' => function ($query) {
                $query->join('loans', 'books.id', '=', 'loans.book_id');
            }])
            ->orderBy('total_pembaca', 'desc')
            ->take(4)
            ->get()
            ->map(fn($cat) => [
                'nama' => $cat->name,
                'total_pembaca' => $cat->total_pembaca,
                'trend' => 'naik', // Placeholder
                'icon' => 'bi-arrow-up-right',
            ]);

        $laporan = [
            'buku_terpopuler' => $bukuTerpopuler,
            'kategori_populer' => $kategoriPopuler,
            'insight' => 'Siswa menunjukkan minat baca yang dinamis. Kategori ' . ($kategoriPopuler->first()['nama'] ?? 'Populer') . ' menjadi favorit saat ini.',
        ];

        // 2. Siswa Teraktif
        $siswaTeraktif = User::where('role', 'siswa')
            ->withCount('loans')
            ->orderBy('loans_count', 'desc')
            ->take(10)
            ->get()
            ->map(fn($user) => [
                'nama' => $user->nama_lengkap,
                'total_buku' => $user->loans_count,
                'kelas' => $user->kelas ?? 'N/A',
            ]);

        // 3. Aktivitas Mingguan (7 hari terakhir)
        $labels = [];
        $data = [];
        for ($i = 6; $i >= 0; $i--) {
            $date = Carbon::now()->subDays($i);
            $labels[] = $date->translatedFormat('l');
            $data[] = Loan::whereDate('borrowed_at', $date->toDateString())->count();
        }

        $aktivitasMingguan = [
            'labels' => $labels,
            'data' => $data,
        ];

        return view('guru.laporan.index', [
            'pageTitle' => 'Laporan Minat Baca Siswa',
            'laporan' => $laporan,
            'siswaTeraktif' => $siswaTeraktif,
            'aktivitasMingguan' => $aktivitasMingguan,
        ]);
    }
}
