<?php

namespace App\Http\Controllers;

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

class HomeController extends Controller
{
    public function dashboardCustomer()
    {
        // Ambil user yang sedang login, jika ada
        $user = Auth::user();
    
        // Ambil daftar booking berdasarkan customer_id
        // Jika user tidak ada (belum login), tidak masalah karena kita hanya akan menampilkan booking secara umum
        $bookings = Booking::when($user, function ($query) use ($user) {
            return $query->where('customer_id', $user->id);
        })
        ->orderBy('tanggal_pemotretan', 'desc')
        ->get();
    
        // Kirim data bookings ke view
        return view('dashboard.customer', compact('user', 'bookings'));
    }

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }

    public function contact()
    {
        return view('customer.contact');
    }

    public function update(Request $request)
    {
        $user = Auth::user();

        $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'address' => 'required|string',
            'password' => 'nullable|string|min:6',
        ]);

        $user->name = $request->name;
        $user->phone = $request->phone;
        $user->address = $request->address;

        if ($request->filled('password')) {
            $user->password = Hash::make($request->password);
        }

        $user->save();

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

}
