<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Booking;
use App\Models\Lapangan;
use App\Models\TimeSlot;
use Illuminate\Http\Request;

class LapanganController extends Controller
{
    /** Helper format paginasi */
    private function paginateResponse($paginator, string $message)
    {
        return response()->json([
            'success' => true,
            'message' => $message,
            'data'    => [
                'items'        => $paginator->items(),
                'current_page' => $paginator->currentPage(),
                'last_page'    => $paginator->lastPage(),
                'per_page'     => $paginator->perPage(),
                'total'        => $paginator->total(),
            ],
        ]);
    }

    /** List semua lapangan aktif dengan filter */
    public function index(Request $request)
    {
        $query = Lapangan::with('owner:id,name,phone')
            ->where('is_active', true);

        if ($request->filled('keyword')) {
            $query->where(function ($q) use ($request) {
                $q->where('nama', 'LIKE', "%{$request->keyword}%")
                  ->orWhere('lokasi', 'LIKE', "%{$request->keyword}%");
            });
        }
        if ($request->filled('jenis_olahraga')) {
            $query->where('jenis_olahraga', $request->jenis_olahraga);
        }
        if ($request->filled('min_harga')) {
            $query->where('harga_per_jam', '>=', $request->min_harga);
        }
        if ($request->filled('max_harga')) {
            $query->where('harga_per_jam', '<=', $request->max_harga);
        }
        if ($request->filled('lokasi')) {
            $query->where('lokasi', 'LIKE', "%{$request->lokasi}%");
        }

        $sortBy    = in_array($request->sort_by, ['rating', 'harga_per_jam', 'nama', 'created_at'])
            ? $request->sort_by : 'created_at';
        $sortOrder = $request->sort_order === 'asc' ? 'asc' : 'desc';
        $query->orderBy($sortBy, $sortOrder);

        $perPage = min((int) $request->get('per_page', 15), 50);
        return $this->paginateResponse($query->paginate($perPage), 'Data lapangan berhasil diambil.');
    }

    /** 6 Lapangan paling populer (rating tertinggi) */
    public function popular()
    {
        $lapangan = Lapangan::with('owner:id,name')
            ->where('is_active', true)
            ->orderByDesc('rating')
            ->limit(6)
            ->get();

        return response()->json([
            'success' => true,
            'message' => 'Lapangan populer berhasil diambil.',
            'data'    => $lapangan,
        ]);
    }

    /** Cari lapangan */
    public function search(Request $request)
    {
        return $this->index($request);
    }

    /** Detail lapangan */
    public function show($id)
    {
        $lapangan = Lapangan::with('owner:id,name,phone')->find($id);

        if (!$lapangan) {
            return response()->json(['success' => false, 'message' => 'Lapangan tidak ditemukan.'], 404);
        }

        return response()->json([
            'success' => true,
            'message' => 'Detail lapangan berhasil diambil.',
            'data'    => $lapangan,
        ]);
    }

    /** Slot tersedia untuk tanggal tertentu */
    public function getAvailableSlots(Request $request, $id)
    {
        $request->validate(['tanggal' => 'required|date|after_or_equal:today']);

        $lapangan = Lapangan::find($id);
        if (!$lapangan) {
            return response()->json(['success' => false, 'message' => 'Lapangan tidak ditemukan.'], 404);
        }

        // Ambil semua slot lapangan
        $slots = TimeSlot::where('lapangan_id', $id)->where('is_available', true)->get();

        // Cek booking yang sudah ada di tanggal tersebut
        $bookingsTanggalIni = Booking::where('lapangan_id', $id)
            ->where('tanggal', $request->tanggal)
            ->whereIn('status', ['pending', 'confirmed'])
            ->get(['jam_mulai', 'jam_selesai']);

        $result = $slots->map(function ($slot) use ($bookingsTanggalIni, $request) {
            $isBooked = $bookingsTanggalIni->contains(function ($booking) use ($slot) {
                return $slot->jam_mulai >= $booking->jam_mulai &&
                       $slot->jam_mulai <  $booking->jam_selesai;
            });

            return array_merge($slot->toArray(), [
                'is_booked' => $isBooked,
                'tanggal'   => $request->tanggal,
            ]);
        });

        return response()->json([
            'success' => true,
            'message' => 'Slot waktu berhasil diambil.',
            'data'    => $result,
        ]);
    }

    /** Lapangan milik admin yang login */
    public function myLapangan(Request $request)
    {
        $lapangan = Lapangan::where('owner_id', $request->user()->id)
            ->orderByDesc('created_at')->get();

        return response()->json([
            'success' => true,
            'message' => 'Data lapangan Anda berhasil diambil.',
            'data'    => $lapangan,
        ]);
    }

    /** Tambah lapangan baru */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'nama'           => 'required|string|max:255',
            'deskripsi'      => 'required|string',
            'jenis_olahraga' => 'required|in:futsal,badminton,basket,voli,tenis,sepakbola,lainnya',
            'harga_per_jam'  => 'required|integer|min:1000',
            'lokasi'         => 'required|string',
            'alamat'         => 'nullable|string',
            'foto'           => 'nullable|array',
            'fasilitas'      => 'nullable|array',
            'jam_buka'       => 'required|date_format:H:i',
            'jam_tutup'      => 'required|date_format:H:i|after:jam_buka',
        ]);

        $lapangan = Lapangan::create(array_merge($validated, [
            'owner_id'  => $request->user()->id,
            'is_active' => true,
        ]));

        return response()->json([
            'success' => true,
            'message' => 'Lapangan berhasil ditambahkan.',
            'data'    => $lapangan,
        ], 201);
    }

    /** Update lapangan */
    public function update(Request $request, $id)
    {
        $lapangan = Lapangan::find($id);
        if (!$lapangan) {
            return response()->json(['success' => false, 'message' => 'Lapangan tidak ditemukan.'], 404);
        }
        if ($lapangan->owner_id !== $request->user()->id) {
            return response()->json(['success' => false, 'message' => 'Akses ditolak.'], 403);
        }

        $validated = $request->validate([
            'nama'           => 'sometimes|string|max:255',
            'deskripsi'      => 'sometimes|string',
            'jenis_olahraga' => 'sometimes|in:futsal,badminton,basket,voli,tenis,sepakbola,lainnya',
            'harga_per_jam'  => 'sometimes|integer|min:1000',
            'lokasi'         => 'sometimes|string',
            'alamat'         => 'nullable|string',
            'foto'           => 'nullable|array',
            'fasilitas'      => 'nullable|array',
            'jam_buka'       => 'sometimes|date_format:H:i',
            'jam_tutup'      => 'sometimes|date_format:H:i',
        ]);

        $lapangan->update($validated);

        return response()->json([
            'success' => true,
            'message' => 'Lapangan berhasil diperbarui.',
            'data'    => $lapangan->fresh(),
        ]);
    }

    /** Hapus lapangan */
    public function destroy(Request $request, $id)
    {
        $lapangan = Lapangan::find($id);
        if (!$lapangan) {
            return response()->json(['success' => false, 'message' => 'Lapangan tidak ditemukan.'], 404);
        }
        if ($lapangan->owner_id !== $request->user()->id) {
            return response()->json(['success' => false, 'message' => 'Akses ditolak.'], 403);
        }

        $lapangan->delete();

        return response()->json([
            'success' => true,
            'message' => 'Lapangan berhasil dihapus.',
        ]);
    }

    /** Toggle aktif/nonaktif lapangan */
    public function toggleStatus(Request $request, $id)
    {
        $lapangan = Lapangan::find($id);
        if (!$lapangan) {
            return response()->json(['success' => false, 'message' => 'Lapangan tidak ditemukan.'], 404);
        }
        if ($lapangan->owner_id !== $request->user()->id) {
            return response()->json(['success' => false, 'message' => 'Akses ditolak.'], 403);
        }

        $lapangan->update(['is_active' => !$lapangan->is_active]);

        return response()->json([
            'success' => true,
            'message' => 'Status lapangan berhasil diubah.',
            'data'    => $lapangan->fresh(),
        ]);
    }
}
