<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Booking;
use App\Models\User;
use App\Models\Room;
use App\Models\PerpanjanganBooking;

class BookingController extends Controller
{
    /**
     * Menampilkan daftar booking.
     */
    public function index(Request $request)
    {
        $query = Booking::query();

        // Filter pencarian berdasarkan bulan dari tanggal_booking
    if ($request->has('search') && !empty($request->search)) {
        $query->whereMonth('tanggal_checkout', $request->search);
    }

    $bookings = $query->orderBy('tanggal_checkout', 'desc')->paginate(10);

        return view('admin.booking', compact('bookings'));
    }

    /**
     * Menampilkan form untuk menambahkan booking baru.
     */
    public function create()
    {
        $users = User::all();
        $rooms = Room::all();

        return view('admin.createbooking', compact('users', 'rooms'));
    }

    /**
     * Menyimpan data booking baru ke database.
     */
    public function store(Request $request)
    {
        $request->validate([
            'id_user'          => 'required|exists:users,id_user',
            'id_kamar'         => 'required|exists:rooms,id_kamar',
            'status_booking'   => 'required|in:Pending,Dikonfirmasi,Dibatalkan',
            'tanggal_booking'  => 'required|date',
            'tanggal_checkin'  => 'required|date|after_or_equal:tanggal_booking',
            'tanggal_checkout' => 'required|date|after:tanggal_checkin',
        ]);

        Booking::create([
            'id_user'          => $request->id_user,
            'id_kamar'         => $request->id_kamar,
            'status_booking'   => $request->status_booking,
            'tanggal_booking'  => $request->tanggal_booking,
            'tanggal_checkin'  => $request->tanggal_checkin,
            'tanggal_checkout' => $request->tanggal_checkout,
        ]);

        return redirect()->route('admin.booking')->with('success', 'Booking berhasil ditambahkan.');
    }

    /**
     * Menampilkan form untuk mengedit booking.
     */
    public function edit($id_booking)
    {
        $booking = Booking::findOrFail($id_booking);
        $users = User::all();
        $rooms = Room::all();

        return view('admin.editbooking', compact('booking', 'users', 'rooms'));
    }

    /**
     * Memperbarui data booking di database.
     */
    public function update(Request $request, $id_booking)
    {
        $request->validate([
            'id_user'          => 'required|exists:users,id_user',
            'id_kamar'         => 'required|exists:rooms,id_kamar',
            'status_booking'   => 'required|in:Pending,Dikonfirmasi,Dibatalkan',
            'tanggal_booking'  => 'required|date',
            'tanggal_checkin'  => 'required|date|after_or_equal:tanggal_booking',
            'tanggal_checkout' => 'required|date|after:tanggal_checkin',
        ]);

        $booking = Booking::findOrFail($id_booking);

        $booking->update([
            'id_user'          => $request->id_user,
            'id_kamar'         => $request->id_kamar,
            'status_booking'   => $request->status_booking,
            'tanggal_booking'  => $request->tanggal_booking,
            'tanggal_checkin'  => $request->tanggal_checkin,
            'tanggal_checkout' => $request->tanggal_checkout,
        ]);

        return redirect()->route('admin.booking')->with('success', 'Booking berhasil diperbarui.');
    }

    /**
     * Menghapus data booking dari database.
     */
    public function destroy($id_booking)
    {
        $booking = Booking::findOrFail($id_booking);
        $booking->delete();

        return redirect()->route('admin.booking')->with('success', 'Booking berhasil dihapus.');
    }

    public function storeBooking(Request $request)
    {
        $validated = $request->validate([
            'id_user'          => 'required|exists:users,id_user',
            'id_kamar'         => 'required|exists:rooms,id_kamar',
            'tanggal_booking'  => 'required|date',
            'tanggal_checkin'  => 'required|date|after_or_equal:tanggal_booking',
            'tanggal_checkout' => 'required|date|after:tanggal_checkin',
        ]);

        // Tambahkan status_booking secara manual karena tidak berasal dari input
        $validated['status_booking'] = 'Pending';

        // Simpan booking
        $booking = Booking::create([
            'id_user' => $request->id_user,
            'id_kamar' => $request->id_kamar,
            'tanggal_booking' => $request->tanggal_booking,
            'tanggal_checkin' => $request->tanggal_checkin,
            'tanggal_checkout' => $request->tanggal_checkout,
            'status_booking' => 'Pending',
        ]);

        // Redirect ke halaman pembayaran
        return redirect()->route('users.pembayaran', ['id_booking' => $booking->id_booking])
            ->with('success', 'Booking berhasil, lanjut ke pembayaran');
    }

    public function confirm($id_booking)
    {
        // Ambil data booking berdasarkan ID
        $booking = Booking::findOrFail($id_booking);

        // Pastikan status booking belum dikonfirmasi
        if ($booking->status_booking !== 'Dikonfirmasi') {
            // Perbarui status booking menjadi 'Dikonfirmasi'
            $booking->update(['status_booking' => 'Dikonfirmasi']);

            // Ambil data kamar yang terkait dengan booking ini
            $room = $booking->room; // Asumsi sudah ada relasi antara Booking dan Room
            if ($room) {
                // Perbarui status kamar menjadi 'terisi'
                $room->update(['status' => 'terisi']);
            }
        }

        return redirect()->route('admin.booking')->with('success', 'Pemesanan berhasil dikonfirmasi.');
    }

    public function cancel($id_booking)
    {
        $booking = Booking::findOrFail($id_booking);

        // Pastikan status booking sudah dikonfirmasi sebelum bisa dibatalkan
        if ($booking->status_booking == 'Dikonfirmasi') {
            $booking->status_booking = 'Dibatalkan';
            $booking->save();

            // Perbarui status kamar menjadi 'tersedia' jika diperlukan
            $room = $booking->room;
            $room->status = 'tersedia';
            $room->save();
        }

        return redirect()->route('admin.booking')->with('success', 'Booking berhasil dibatalkan.');
    }

    public function approvePerpanjangan($id)
{
    // Ambil data perpanjangan
    $perpanjangan = PerpanjanganBooking::findOrFail($id);

    // Pastikan belum dikonfirmasi
    if ($perpanjangan->status !== 'Dikonfirmasi') {

        // Ambil data booking terkait
        $booking = Booking::findOrFail($perpanjangan->id_booking);

        // Update tanggal checkout pada tabel booking
        $booking->update([
            'tanggal_checkout' => $perpanjangan->tanggal_checkout_baru,
        ]);

        // Update status perpanjangan menjadi 'Dikonfirmasi'
        $perpanjangan->update([
            'status' => 'Dikonfirmasi',
        ]);

        // Update status booking jika belum dikonfirmasi
        if ($booking->status_booking !== 'Dikonfirmasi') {
            $booking->update([
                'status_booking' => 'Dikonfirmasi',
            ]);

            // Update status kamar juga jika belum terisi
            if ($booking->room && $booking->room->status !== 'terisi') {
                $booking->room->update([
                    'status' => 'terisi',
                ]);
            }
        }
    }

    return redirect()->route('admin.booking')->with('success', 'Perpanjangan berhasil dikonfirmasi.');
}

public function markAsCompleted($id_booking)
{
    $booking = Booking::findOrFail($id_booking);

    // Pastikan hanya booking yang dikonfirmasi bisa selesai
    if ($booking->status_booking === 'Dikonfirmasi') {
        $booking->update(['status_booking' => 'Selesai']);

        // Update status kamar menjadi tersedia
        $room = $booking->room;
        if ($room) {
            $room->update(['status' => 'tersedia']);
        }

        return redirect()->route('admin.booking')->with('success', 'Booking telah diselesaikan.');
    }

    return redirect()->route('admin.booking')->with('error', 'Booking belum dikonfirmasi.');
}

}
