<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Invoice;
use App\Models\News; // Pastikan ini ada

class HomeController extends Controller
{
    public function index()
{
    $user = Auth::user();

    // 1. Ambil data tagihan (Kode Anda tetap)
    $currentInvoice = Invoice::where('user_id', $user->id)
                             ->where('status', 'unpaid')
                             ->whereNotNull('published_at')
                             ->orderBy('due_date', 'asc')
                             ->first();
    
    $tagihan = null;
    if ($currentInvoice) {
        $tagihan = [
            'id'          => $currentInvoice->id,
            'total'       => number_format($currentInvoice->total_amount, 0, ',', '.'),
            'jatuh_tempo' => $currentInvoice->due_date->translatedFormat('d F Y')
        ];
    }

    
    $news = News::latest()->take(5)->get();

   
    $words = explode(" ", $user->name);
    $initial_user = "";
    foreach ($words as $w) { $initial_user .= mb_substr($w, 0, 1); }
    
  
    $notifications = $user->notifications; 
   
    $unreadCount = $user->unreadNotifications->count();

    return view('home', [
        'nama_user'     => $user->name,
        'initial_user'  => strtoupper($initial_user),
        'tagihan'       => $tagihan,
        'news'          => $news,
        'notifications' => $notifications, 
        'unreadCount'   => $unreadCount    
    ]);
}
}