<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
use App\Models\Rekening;
use PDF; // Tambahkan ini
use Illuminate\Support\Facades\View; // Tambahkan ini

class BookingReceiptNotification extends Notification
{
    use Queueable;

    public $booking;

    public function __construct($booking)
    {
        $this->booking = $booking;
    }

    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {
        $frontendUrl = env('FRONTEND_URL', 'https://midhouse.id');

        // Generate PDF
        $pdf = $this->generatePDF();

        $message = (new MailMessage)
            ->subject('Kwitansi Booking Kamu di MidHouse')
            ->greeting('Halo ' . $notifiable->name . ',')
            ->line('Booking kamu sudah berhasil dibuat nih! Ini detail pesanannya:')
            ->line('🧾 Invoice: ' . $this->booking->invoice_id)
            ->line('🗝 Check-in: ' . $this->booking->checkin)
            ->line('💸 Total Bayar: Rp ' . number_format($this->booking->total_price, 0, ',', '.'))
            ->action('Lihat Detail Booking', $frontendUrl . '/dashboard/booking')
            ->attachData($pdf, 'Kwitansi-Booking-' . $this->booking->invoice_id . '.pdf', [
                'mime' => 'application/pdf',
            ]);

        // Tambahkan daftar rekening
        $message->line('Silakan lakukan pembayaran ke salah satu rekening kami di bawah ini:');

        $rekenings = Rekening::where('status', 'on')->get();
        foreach ($rekenings as $rekening) {
            $message->line('- ' . $rekening->bank_name . ' a.n. ' . $rekening->atas_nama . ' (' . $rekening->norek . ')');
        }

        $message->line('Kalau sudah bayar, jangan lupa konfirmasi lewat menu pembayaran ya.')
                ->line('Terima kasih sudah memilih MidHouse!')
                ->salutation('Salam hangat, Tim MidHouse Universe');

        return $message;
    }

    // Fungsi baru untuk generate PDF
    protected function generatePDF()
    {
        // Pastikan relasi terload
        $this->booking->load(['room', 'user']);
        
        $data = [
            'booking' => $this->booking,
            'rekenings' => Rekening::where('status', 'on')->get() ?? []
        ];

        $pdf = PDF::loadView('emails.booking_receipt', $data);
        return $pdf->output();
    }
}