<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use App\Models\Transaksi;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    public function showProfile()
    {
        return view('users.profile');
    }

    public function editProfile()
    {
        return view('users.edit-profile');
    }

    public function updateProfile(Request $request)
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();

        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255|unique:users,email,' . $user->id_user . ',id_user',
            'password' => 'nullable|string|min:6',
        ]);

        $user->name = $request->name;
        $user->email = $request->email;
        if ($request->password) {
            $user->password = Hash::make($request->password);
        }
        $user->save();

        return redirect()->route('users.profile')->with('success', 'Profil berhasil diperbarui.');
    }

    public function detailPesanan($id_booking)
    {
        // Ambil data booking beserta relasi room
        $booking = Booking::with('room')->findOrFail($id_booking);

        // Ambil transaksi pembayaran berdasarkan id_booking
        $pembayaran = Transaksi::where('id_booking', $booking->id_booking)
            ->orderBy('id_transaksi', 'desc') // Gunakan 'id_transaksi' sesuai struktur tabel
            ->first();

        return view('users.detail-pesanan', compact('booking', 'pembayaran'));
    }

    public function showDetailPesanan($id_booking)
    {
        $booking = Booking::with('room')->findOrFail($id_booking); // Pastikan ada relasi room jika dibutuhkan
        $pembayaran = Transaksi::where('id_booking', $id_booking)
            ->orderBy('id_transaksi', 'desc')
            ->first(); // Ambil data pembayaran terbaru

        return view('users.detail-pesanan', compact('booking', 'pembayaran'));
    }
}
