<?php

namespace App\Http\Controllers;

use App\Models\Room;
use App\Models\RoomBooking;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage; // Import Storage untuk hapus foto

class RoomController extends Controller
{
    /**
     * Menampilkan daftar ruangan (User & Admin).
     */
    public function index()
    {
        $rooms = Room::all();
        $scheduleStart = now()->startOfDay();
        $scheduleEnd = now()->copy()->addDays(30)->endOfDay();
        $roomSchedules = RoomBooking::query()
            ->whereIn('status', ['pending', 'staff_approved', 'sekretariat_approved', 'approved', 'final_approved'])
            ->where(function ($query) use ($scheduleStart, $scheduleEnd) {
                $query->whereBetween('start_time', [$scheduleStart, $scheduleEnd])
                    ->orWhereBetween('end_time', [$scheduleStart, $scheduleEnd])
                    ->orWhere(function ($nested) use ($scheduleStart, $scheduleEnd) {
                        $nested->where('start_time', '<', $scheduleStart)
                            ->where('end_time', '>', $scheduleEnd);
                    });
            })
            ->orderBy('start_time')
            ->get(['room_id', 'start_time', 'end_time', 'status', 'title'])
            ->groupBy('room_id')
            ->map(function ($bookings) {
                return $bookings->map(function ($booking) {
                    return [
                        'title' => $booking->title,
                        'status' => $booking->status,
                        'start_time' => Carbon::parse($booking->start_time)->format('Y-m-d H:i:s'),
                        'end_time' => Carbon::parse($booking->end_time)->format('Y-m-d H:i:s'),
                    ];
                })->values();
            });

        // LOGIKA CEK KETERSEDIAAN REAL-TIME
        foreach ($rooms as $room) {
            
            // 1. Cek Booking AKTIF (Sedang berlangsung & Sudah Disetujui)
            $activeBooking = RoomBooking::where('room_id', $room->id)
                ->whereIn('status', ['approved', 'final_approved'])
                ->where(function($q) {
                    $now = now(); 
                    $q->where('start_time', '<=', $now)
                      ->where('end_time', '>=', $now);
                })
                ->exists();

            // 2. Cek Booking PENDING
            $pendingBooking = RoomBooking::where('room_id', $room->id)
                ->whereIn('status', ['pending', 'staff_approved', 'sekretariat_approved'])
                ->where(function($q) {
                    $now = now();
                    $q->where('start_time', '<=', $now)
                      ->where('end_time', '>=', $now);
                })
                ->exists();

            $room->is_available = !$activeBooking && !in_array($room->manual_status, ['maintenance', 'closed'], true);
            $room->has_pending = $pendingBooking;
            $room->chair_limit = $this->maxChairCountForRoom($room);
        }

        return view('rooms.index', [
            'rooms' => $rooms,
            'roomSchedules' => $roomSchedules,
            'scheduleDateStart' => now()->toDateString(),
        ]);
    }

    /**
     * Menyimpan Booking Ruangan (User).
     */
    public function storeBooking(Request $request)
    {
        // 1. Validasi Input Dasar
        $request->validate([
            'room_id' => 'required|exists:rooms,id',
            'title' => 'required|string|max:255',
            'chair_count' => 'required|integer|min:1',
            'start_time' => 'required|date', 
            'end_time' => 'required|date|after:start_time',
        ]);

        $start = Carbon::parse($request->start_time);
        $end = Carbon::parse($request->end_time);
        $now = now();
        $room = Room::findOrFail($request->room_id);
        $chairLimit = $this->maxChairCountForRoom($room);

        if ($chairLimit !== null && (int) $request->chair_count > $chairLimit) {
            return back()
                ->withErrors(['chair_count' => "Kebutuhan kursi untuk {$room->name} maksimal {$chairLimit} kursi."])
                ->withInput();
        }

        // 2. Validasi Waktu Manual
        if ($start->lte($now)) {
            return back()->withErrors(['start_time' => 'Slot jam yang sudah berjalan tidak bisa dipilih. Pilih slot jam berikutnya.']);
        }

        if (!$start->isSameDay($end)) {
            return back()->withErrors(['end_time' => 'Booking ruangan hanya boleh dalam 1 hari yang sama.']);
        }

        if ((int) $start->format('i') !== 0 || (int) $end->format('i') !== 0) {
            return back()->withErrors(['start_time' => 'Booking ruangan harus mengikuti slot per jam.']);
        }

        if ((int) $start->format('H') < 7 || (int) $end->format('H') > 18) {
            return back()->withErrors(['start_time' => 'Booking ruangan hanya tersedia dari jam 07:00 sampai 18:00.']);
        }

        if (in_array($room->manual_status, ['maintenance', 'closed'], true)) {
            return back()->with('error', 'Ruangan sedang tidak tersedia untuk dibooking.');
        }

        // 3. CEK TABRAKAN JADWAL
        $conflicting = RoomBooking::where('room_id', $request->room_id)
            ->whereIn('status', ['pending', 'staff_approved', 'sekretariat_approved', 'approved', 'final_approved'])
            ->where('start_time', '<', $end)
            ->where('end_time', '>', $start)
            ->exists();

        if ($conflicting) {
            return back()->with('error', 'Ruangan sudah dibooking pada jam tersebut.');
        }

        RoomBooking::create([
            'user_id' => auth()->id(),
            'room_id' => $request->room_id,
            'title' => $request->title,
            'chair_count' => $request->chair_count,
            'start_time' => $start,
            'end_time' => $end,
            'status' => 'pending', 
        ]);

        return back()->with('success', 'Booking berhasil dibuat, menunggu persetujuan.');
    }

    private function maxChairCountForRoom(Room $room): ?int
    {
        $roomName = strtolower($room->name);

        return match (true) {
            str_contains($roomName, 'konseling') => 15,
            str_contains($roomName, '2a') && str_contains($roomName, '2b') => 100,
            str_contains($roomName, 'hall of frame') => 100,
            str_contains($roomName, 'hall of fame') => 100,
            str_contains($roomName, '2a') => 60,
            str_contains($roomName, '2b') => 40,
            default => null,
        };
    }

    // =========================================================================
    // CRUD MASTER RUANGAN (KHUSUS SEKRETARIAT/ADMIN)
    // =========================================================================

    /**
     * Tampilkan form tambah ruangan.
     */
    public function create()
    {
        return view('rooms.create');
    }

    /**
     * Simpan ruangan baru ke database.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'building' => 'required|string|max:255', // Contoh: Gedung A
            'floor' => 'required|string|max:50',     // Contoh: Lantai 1
            'capacity' => 'required|integer|min:1',
            'type' => 'required|string|in:meeting,office,hall,other',
            'manual_status' => 'required|string|in:available,maintenance,closed',
            'description' => 'nullable|string',
            'image' => 'nullable|image|max:2048', // Max 2MB
        ]);

        // Upload Foto jika ada
        if ($request->hasFile('image')) {
            $validated['image'] = $request->file('image')->store('rooms', 'public');
        }

        Room::create($validated);

        return redirect()->route('rooms.index')->with('success', 'Ruangan baru berhasil ditambahkan.');
    }

    /**
     * Tampilkan form edit ruangan.
     */
    public function edit(Room $room)
    {
        return view('rooms.edit', compact('room'));
    }

    /**
     * Update data ruangan.
     */
    public function update(Request $request, Room $room)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'building' => 'required|string|max:255',
            'floor' => 'required|string|max:50',
            'capacity' => 'required|integer|min:1',
            'type' => 'required|string|in:meeting,office,hall,other',
            'manual_status' => 'required|string|in:available,maintenance,closed',
            'description' => 'nullable|string',
            'image' => 'nullable|image|max:2048',
        ]);

        // Cek jika ada foto baru diupload
        if ($request->hasFile('image')) {
            // Hapus foto lama jika ada
            if ($room->image) {
                Storage::disk('public')->delete($room->image);
            }
            $validated['image'] = $request->file('image')->store('rooms', 'public');
        }

        $room->update($validated);

        return redirect()->route('rooms.index')->with('success', 'Data ruangan berhasil diperbarui.');
    }

    /**
     * Hapus ruangan.
     */
    public function destroy(Room $room)
    {
        // Cek apakah ada booking aktif di masa depan, jika ya, mungkin sebaiknya dicegah
        $activeBookings = $room->bookings()
            ->where('end_time', '>=', now())
            ->whereIn('status', ['pending', 'staff_approved', 'sekretariat_approved', 'approved', 'final_approved'])
            ->exists();

        if ($activeBookings) {
            return back()->with('error', 'Tidak dapat menghapus ruangan karena masih ada jadwal booking aktif.');
        }

        // Hapus foto dari storage
        if ($room->image) {
            Storage::disk('public')->delete($room->image);
        }

        $room->delete();

        return redirect()->route('rooms.index')->with('success', 'Ruangan berhasil dihapus.');
    }
}
