<?php

namespace App\Livewire\Admin;

use App\Models\Booking;
use App\Models\Listing;
use App\Models\User;
use Livewire\Component;

class Dashboard extends Component
{
    public function approveBooking($bookingId)
    {
        $booking = Booking::findOrFail($bookingId);

        $booking->update([
            'status' => 'confirmed'
        ]);

        session()->flash('success', 'Booking #' . $bookingId . ' has been approved successfully.');
    }

    public function cancelBooking($bookingId)
    {
        $booking = Booking::findOrFail($bookingId);

        $booking->update([
            'status' => 'cancelled'
        ]);

        session()->flash('success', 'Booking #' . $bookingId . ' has been cancelled.');
    }

    public function render()
    {
        $stats = [
            'total_users' => User::count(),
            'total_hosts' => User::where('role', 'host')->count(),
            'total_listings' => Listing::count(),
            'total_bookings' => Booking::count(),
            'confirmed_bookings' => Booking::where('status', 'confirmed')->count(),
            'total_revenue' => Booking::whereIn('status', ['confirmed', 'completed'])->sum('total_price'),
        ];

        $recent_bookings = Booking::with(['listing.location', 'listing.rentalType', 'user', 'payment'])
            ->latest()
            ->take(10)
            ->get();

        return view('livewire.admin.dashboard', compact('stats', 'recent_bookings'))
            ->layout('layouts.app');
    }
}
