<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Booking;
use App\Models\Lapangan;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Carbon\Carbon;

class DashboardController extends Controller
{
    // =============================================
    // FORMAT RESPONSE HELPER
    // =============================================

    private function successResponse(string $message, $data = null, int $code = 200): JsonResponse
    {
        return response()->json(['success' => true, 'message' => $message, 'data' => $data], $code);
    }

    private function errorResponse(string $message, $errors = null, int $code = 400): JsonResponse
    {
        $res = ['success' => false, 'message' => $message];
        if ($errors !== null) $res['errors'] = $errors;
        return response()->json($res, $code);
    }

    // =============================================
    // STATS - Statistik dashboard
    // =============================================

    /**
     * Ambil statistik utama untuk dashboard admin
     * - Total booking hari ini, bulan ini
     * - Total pendapatan hari ini, bulan ini
     * - Jumlah lapangan aktif
     * - Jumlah booking pending
     * - Total pelanggan
     *
     * @return JsonResponse
     */
    public function stats(): JsonResponse
    {
        try {
            $today = Carbon::today();
            $now   = Carbon::now();

            // ---- Booking ----
            $bookingHariIni  = Booking::whereDate('tanggal', $today)->count();
            $bookingBulanIni = Booking::whereMonth('tanggal', $now->month)
                ->whereYear('tanggal', $now->year)
                ->count();
            $bookingPending  = Booking::where('status', 'pending')->count();

            // ---- Pendapatan (dari booking confirmed/completed saja) ----
            $pendapatanHariIni = Booking::whereDate('tanggal', $today)
                ->whereIn('status', ['confirmed', 'completed'])
                ->sum('total_harga');

            $pendapatanBulanIni = Booking::whereMonth('tanggal', $now->month)
                ->whereYear('tanggal', $now->year)
                ->whereIn('status', ['confirmed', 'completed'])
                ->sum('total_harga');

            $pendapatanTotal = Booking::whereIn('status', ['confirmed', 'completed'])
                ->sum('total_harga');

            // ---- Lapangan ----
            $lapanganAktif = Lapangan::where('is_active', true)->count();
            $totalLapangan = Lapangan::count();

            // ---- User ----
            $totalPelanggan = User::where('role', 'customer')->where('is_active', true)->count();
            $totalAdmin     = User::where('role', 'admin')->where('is_active', true)->count();

            // ---- Booking per status ----
            $bookingByStatus = Booking::selectRaw('status, COUNT(*) as total')
                ->groupBy('status')
                ->pluck('total', 'status');

            return $this->successResponse('Statistik dashboard berhasil diambil.', [
                'booking' => [
                    'hari_ini'  => $bookingHariIni,
                    'bulan_ini' => $bookingBulanIni,
                    'pending'   => $bookingPending,
                    'per_status' => [
                        'pending'   => $bookingByStatus['pending']   ?? 0,
                        'confirmed' => $bookingByStatus['confirmed'] ?? 0,
                        'completed' => $bookingByStatus['completed'] ?? 0,
                        'cancelled' => $bookingByStatus['cancelled'] ?? 0,
                        'rejected'  => $bookingByStatus['rejected']  ?? 0,
                    ],
                ],
                'pendapatan' => [
                    'hari_ini'  => (int) $pendapatanHariIni,
                    'bulan_ini' => (int) $pendapatanBulanIni,
                    'total'     => (int) $pendapatanTotal,
                ],
                'lapangan' => [
                    'aktif' => $lapanganAktif,
                    'total' => $totalLapangan,
                ],
                'user' => [
                    'total_pelanggan' => $totalPelanggan,
                    'total_admin'     => $totalAdmin,
                ],
                'generated_at' => $now->toDateTimeString(),
            ]);
        } catch (\Exception $e) {
            return $this->errorResponse('Terjadi kesalahan server: ' . $e->getMessage(), null, 500);
        }
    }

    // =============================================
    // RECENT BOOKINGS - 5 booking terbaru
    // =============================================

    /**
     * Ambil 5 booking terbaru untuk ditampilkan di dashboard
     *
     * @return JsonResponse
     */
    public function recentBookings(): JsonResponse
    {
        try {
            $bookings = Booking::with([
                'user:id,name,email',
                'lapangan:id,nama,lokasi,foto,jenis_olahraga',
            ])
                ->orderByDesc('created_at')
                ->limit(5)
                ->get();

            $data = $bookings->map(fn($booking) => [
                'id'            => $booking->id,
                'kode_booking'  => $booking->kode_booking,
                'tanggal'       => $booking->tanggal?->toDateString(),
                'jam_mulai'     => $booking->jam_mulai,
                'jam_selesai'   => $booking->jam_selesai,
                'total_harga'   => $booking->total_harga,
                'status'        => $booking->status,
                'created_at'    => $booking->created_at?->toDateTimeString(),
                'user' => $booking->user ? [
                    'id'    => $booking->user->id,
                    'name'  => $booking->user->name,
                    'email' => $booking->user->email,
                ] : null,
                'lapangan' => $booking->lapangan ? [
                    'id'             => $booking->lapangan->id,
                    'nama'           => $booking->lapangan->nama,
                    'jenis_olahraga' => $booking->lapangan->jenis_olahraga,
                    'lokasi'         => $booking->lapangan->lokasi,
                ] : null,
            ]);

            return $this->successResponse('Booking terbaru berhasil diambil.', [
                'items' => $data,
            ]);
        } catch (\Exception $e) {
            return $this->errorResponse('Terjadi kesalahan server: ' . $e->getMessage(), null, 500);
        }
    }

    // =============================================
    // REVENUE - Pendapatan per bulan (12 bulan terakhir)
    // =============================================

    /**
     * Ambil data pendapatan per bulan untuk 12 bulan terakhir
     * Berguna untuk grafik pada dashboard admin
     *
     * @return JsonResponse
     */
    public function revenue(): JsonResponse
    {
        try {
            $months = [];

            // Iterasi 12 bulan ke belakang
            for ($i = 11; $i >= 0; $i--) {
                $date = Carbon::now()->subMonths($i);

                $pendapatan = Booking::whereMonth('tanggal', $date->month)
                    ->whereYear('tanggal', $date->year)
                    ->whereIn('status', ['confirmed', 'completed'])
                    ->sum('total_harga');

                $totalBooking = Booking::whereMonth('tanggal', $date->month)
                    ->whereYear('tanggal', $date->year)
                    ->count();

                $months[] = [
                    'bulan'         => $date->format('Y-m'),
                    'nama_bulan'    => $date->locale('id')->isoFormat('MMMM YYYY'),
                    'pendapatan'    => (int) $pendapatan,
                    'total_booking' => (int) $totalBooking,
                ];
            }

            // Hitung total keseluruhan
            $totalPendapatan = array_sum(array_column($months, 'pendapatan'));
            $totalBooking    = array_sum(array_column($months, 'total_booking'));

            return $this->successResponse('Data pendapatan berhasil diambil.', [
                'months'           => $months,
                'total_pendapatan' => $totalPendapatan,
                'total_booking'    => $totalBooking,
                'periode'          => '12 bulan terakhir',
            ]);
        } catch (\Exception $e) {
            return $this->errorResponse('Terjadi kesalahan server: ' . $e->getMessage(), null, 500);
        }
    }
}
