<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Announcement;
use App\Models\Book;
use App\Models\Loan;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    public function index()
    {
        $allBooks = Book::count();
        $allUsers = User::count();
        $bukuDipinjam = Loan::whereIn('status', ['Dipinjam', 'Terlambat'])->count();
        
        $stats = [
            ['label' => 'Total Buku', 'value' => $allBooks, 'icon' => 'bi-journal-bookmark-fill', 'color' => 'primary'],
            ['label' => 'Total Anggota', 'value' => $allUsers, 'icon' => 'bi-people-fill', 'color' => 'success'],
            ['label' => 'Buku Dipinjam', 'value' => $bukuDipinjam, 'icon' => 'bi-arrow-up-right-circle-fill', 'color' => 'warning'],
            ['label' => 'Total Denda', 'value' => 'Rp ' . number_format(Loan::where('status', 'Terlambat')->sum('fine_overdue'), 0, ',', '.'), 'icon' => 'bi-cash-coin', 'color' => 'danger'],
        ];

        // Monthly stats (last 7 months)
        $labels = [];
        $data = [];
        for ($i = 6; $i >= 0; $i--) {
            $month = Carbon::now()->subMonths($i);
            $labels[] = $month->translatedFormat('M');
            $data[] = Loan::whereMonth('borrowed_at', $month->month)
                ->whereYear('borrowed_at', $month->year)
                ->count();
        }

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

        $komposisiBuku = [
            'tersedia' => Book::where('status', 'Tersedia')->count(),
            'dipinjam' => Book::where('status', 'Dipinjam')->count(),
        ];

        $pengumuman = Announcement::latest()->take(5)->get();

        $aktivitasTerakhir = Loan::with(['user', 'book'])
            ->latest()
            ->take(4)
            ->get()
            ->map(fn($loan) => [
                'nama' => $loan->user->nama_lengkap ?? 'Unknown',
                'judul_buku' => $loan->book->judul ?? 'Unknown',
                'tipe' => $loan->status === 'Dikembalikan' ? 'Pengembalian' : 'Peminjaman',
                'waktu' => $loan->created_at->diffForHumans(),
                'status' => $loan->status,
            ]);

        $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('admin.dashboard', [
            'pageTitle' => 'Beranda',
            'user' => Auth::user(),
            'greeting' => $greeting,
            'stats' => $stats,
            'statistikBulanan' => $statistikBulanan,
            'komposisiBuku' => $komposisiBuku,
            'pengumuman' => $pengumuman,
            'aktivitasTerakhir' => $aktivitasTerakhir,
        ]);
    }
}
