<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Paket;
use App\Models\Sewa;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function index()
    {
        // Mengambil statistik
        $stats = [
            'users' => User::where('role', 'customer')->count(),
            'packages' => Paket::count(),
            'rentals' => Sewa::count(),
            'revenue' => Sewa::where('status', 'selesai')->sum('total_harga')
        ];

        // Mengambil aktivitas terbaru
        $activities = $this->getRecentActivities();

        return view('admin.dashboard', compact('stats', 'activities'));
    }

    private function getRecentActivities()
    {
        $activities = [];

        // Aktivitas sewa terbaru
        $recentRentals = Sewa::with(['user', 'paket'])
            ->latest()
            ->take(5)
            ->get();

        foreach ($recentRentals as $rental) {
            $activities[] = [
                'title' => 'Sewa Baru',
                'description' => "{$rental->user->name} menyewa paket {$rental->paket->nama_paket}",
                'time' => Carbon::parse($rental->created_at)->diffForHumans(),
                'color' => 'blue',
                'icon' => 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2'
            ];
        }

        // Aktivitas pembayaran
        $recentPayments = Sewa::where('status', 'selesai')
            ->latest()
            ->take(5)
            ->get();

        foreach ($recentPayments as $payment) {
            $activities[] = [
                'title' => 'Pembayaran Selesai',
                'description' => "Pembayaran sewa paket {$payment->paket->nama_paket} oleh {$payment->user->name}",
                'time' => Carbon::parse($payment->updated_at)->diffForHumans(),
                'color' => 'green',
                'icon' => 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z'
            ];
        }

        // Urutkan berdasarkan waktu terbaru
        usort($activities, function($a, $b) {
            return strtotime($b['time']) - strtotime($a['time']);
        });

        return array_slice($activities, 0, 5);
    }
} 