<?php

namespace App\Http\Controllers\Customer;

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

class DashboardController extends Controller
{
    public function index()
    {
        $user = auth()->user();

        // Mengambil statistik
        $stats = [
            'active_rentals' => Sewa::where('user_id', $user->id)
                ->whereIn('status', ['menunggu', 'diproses'])
                ->count(),
            'total_rentals' => Sewa::where('user_id', $user->id)->count(),
            'total_spent' => Sewa::where('user_id', $user->id)
                ->where('status', 'selesai')
                ->sum('total_harga')
        ];

        // Mengambil riwayat sewa terakhir
        $recent_rentals = $this->getRecentRentals($user->id);

        return view('customer.dashboard', compact('stats', 'recent_rentals'));
    }

    private function getRecentRentals($userId)
    {
        $rentals = Sewa::with('paket')
            ->where('user_id', $userId)
            ->latest()
            ->take(5)
            ->get();

        return $rentals->map(function ($rental) {
            $statusColors = [
                'menunggu' => 'yellow',
                'diproses' => 'blue',
                'selesai' => 'green',
                'dibatalkan' => 'red'
            ];

            $statusIcons = [
                'menunggu' => 'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z',
                'diproses' => 'M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15',
                'selesai' => 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z',
                'dibatalkan' => 'M6 18L18 6M6 6l12 12'
            ];

            return [
                'package_name' => $rental->paket->nama_paket,
                'status' => ucfirst($rental->status),
                'status_color' => $statusColors[$rental->status] ?? 'gray',
                'icon' => $statusIcons[$rental->status] ?? '',
                'description' => "Sewa pada " . Carbon::parse($rental->created_at)->format('d M Y'),
                'date' => Carbon::parse($rental->created_at)->diffForHumans()
            ];
        });
    }
} 