<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Booking;
use App\Models\TailorRating;
use App\Models\TailorService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class AdminDashboardController extends Controller
{
    public function index()
    {
        try {
            // Get counts
            $totalPenjahit = User::where('role', 'penjahit')->count();
            $totalPelanggan = User::where('role', 'pelanggan')->count();
            $totalBookings = Booking::count();
            $totalServices = TailorService::count();
            
            // Get average rating for all tailors
            $averageRating = TailorRating::avg('rating') ?? 0;
            
            // Get bookings statistics
            $bookingStats = Booking::select('status', DB::raw('count(*) as total'))
                ->groupBy('status')
                ->get()
                ->pluck('total', 'status')
                ->toArray();

            // Get recent bookings
            $recentBookings = Booking::with(['customer:id,name', 'tailor:id,name'])
                ->latest()
                ->take(5)
                ->get()
                ->map(function ($booking) {
                    return [
                        'id' => $booking->id,
                        'customer_name' => $booking->customer->name,
                        'tailor_name' => $booking->tailor->name,
                        'status' => $booking->status,
                        'created_at' => $booking->created_at
                    ];
                });

            // Get monthly booking statistics for the last 6 months
            $monthlyStats = Booking::select(
                DB::raw('DATE_FORMAT(created_at, "%Y-%m") as month'),
                DB::raw('count(*) as total_bookings'),
                DB::raw('SUM(CASE WHEN status = "completed" THEN 1 ELSE 0 END) as completed_bookings')
            )
                ->where('created_at', '>=', Carbon::now()->subMonths(6))
                ->groupBy('month')
                ->orderBy('month')
                ->get();

            // Get top rated tailors
            $topTailors = User::where('role', 'penjahit')
                ->withAvg('ratings as average_rating', 'rating')
                ->withCount('ratings')
                ->withCount('bookings')
                ->having('ratings_count', '>', 0)
                ->orderByDesc('average_rating')
                ->take(5)
                ->get()
                ->map(function ($tailor) {
                    return [
                        'id' => $tailor->id,
                        'name' => $tailor->name,
                        'average_rating' => round($tailor->average_rating, 1),
                        'total_ratings' => $tailor->ratings_count,
                        'total_bookings' => $tailor->bookings_count
                    ];
                });

            // Get latest registered users (both tailors and customers)
            $recentUsers = User::whereIn('role', ['penjahit', 'pelanggan'])
                ->latest()
                ->take(5)
                ->select('id', 'name', 'role', 'created_at')
                ->get();

            return response()->json([
                'status' => 'success',
                'data' => [
                    'summary' => [
                        'total_penjahit' => $totalPenjahit,
                        'total_pelanggan' => $totalPelanggan,
                        'total_bookings' => $totalBookings,
                        'total_services' => $totalServices,
                        'average_rating' => round($averageRating, 1)
                    ],
                    'booking_statistics' => [
                        'by_status' => $bookingStats,
                        'monthly' => $monthlyStats
                    ],
                    'recent_bookings' => $recentBookings,
                    'top_tailors' => $topTailors,
                    'recent_users' => $recentUsers
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to retrieve dashboard data',
                'error' => $e->getMessage()
            ], 500);
        }
    }
} 