<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Anggota; 
use App\Models\Koleksi;
use App\Models\BorrowTransaction;
use App\Models\Rating; 
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index()
    {
        

        $jumlahJudul = Koleksi::distinct('title')->count('title');

        $jumlahEksemplar = Koleksi::whereNotNull('kode_eksemplar')->count();

        $jumlahUser = User::count();

        $totalBuku = $jumlahJudul;
        $totalAnggota = $jumlahUser;

        $anggotaBulanIni = Anggota::whereMonth('created_at', date('m'))->count();

        
        $totalPeminjaman = BorrowTransaction::where('status', 'dipinjam')->count();

        $totalPengembalian = BorrowTransaction::where('status', 'dikembalikan')->count();

        
        $chartData = BorrowTransaction::selectRaw('MONTH(tanggal_pinjam) as bulan, COUNT(*) as total')
            ->whereYear('tanggal_pinjam', date('Y'))
            ->groupBy('bulan')
            ->orderBy('bulan')
            ->pluck('total', 'bulan')
            ->toArray();

        $chartDataFull = [];
        for ($i = 1; $i <= 12; $i++) {
            $chartDataFull[] = $chartData[$i] ?? 0;
        }

        $bulanLabel = ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'];

        
        $ratings = Rating::with('user', 'transaction.koleksi')->orderBy('created_at', 'desc')->get();

        $ratingCounts = [];
        $ratingComments = [];
        for ($i = 1; $i <= 5; $i++) {
            $ratingCounts[$i] = $ratings->where('rating', $i)->count();
            $ratingComments[$i] = $ratings->where('rating', $i)->pluck('feedback')->implode(', ');
        }

       
        $mostBorrowedBook = BorrowTransaction::select('koleksi_id')
            ->selectRaw('COUNT(*) as total')
            ->groupBy('koleksi_id')
            ->orderByDesc('total')
            ->with('koleksi')
            ->first();

        
        return view('admin.dashboard', compact(
            'jumlahJudul',
            'jumlahEksemplar',
            'jumlahUser',
            'totalBuku',
            'totalAnggota',
            'anggotaBulanIni', 
            'totalPeminjaman',
            'totalPengembalian',
            'chartDataFull',
            'bulanLabel',
            'ratings',
            'ratingCounts',
            'ratingComments',
            'mostBorrowedBook'
        ));
    }
}
