<?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', '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)
                ->where('status', 'pending')
                ->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;
        }

        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',
            '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);

        // 2. Validasi Waktu Manual (Dengan Toleransi 5 Menit)
        if ($start->lt($now->copy()->subMinutes(5))) {
            return back()->withErrors(['start_time' => 'Waktu mulai tidak boleh di masa lalu.']);
        }

        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', 'approved', 'final_approved'])
            ->where(function ($query) use ($start, $end) {
                $query->whereBetween('start_time', [$start, $end])
                      ->orWhereBetween('end_time', [$start, $end])
                      ->orWhere(function ($q) use ($start, $end) {
                          $q->where('start_time', '<', $start)
                            ->where('end_time', '>', $end);
                      });
            })
            ->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,
            'start_time' => $start,
            'end_time' => $end,
            'status' => 'pending', 
        ]);

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

    // =========================================================================
    // 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', '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.');
    }
}
