<?php

namespace App\Notifications;

use App\Models\PropertyRequest;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

/** Firmaya özel "Sizin için bulalım" talebi geldiğinde firma sahibine e-posta + panel bildirimi. */
class PropertyRequestReceivedNotification extends Notification
{
    use Queueable;

    public function __construct(
        public PropertyRequest $request
    ) {
        //
    }

    public function via(object $notifiable): array
    {
        return ['mail', 'database'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        $r = $this->request;
        $budget = $this->budgetLine();

        $mail = (new MailMessage)
            ->subject('Yeni müşteri talebi: '.($r->category_name ?: 'Mülk').' · '.($r->location ?: '—'))
            ->greeting('Merhaba '.$notifiable->name.',')
            ->line('Firmanıza yeni bir "Sizin için bulalım" talebi geldi.')
            ->line('Kategori: '.($r->category_name ?: 'Belirtilmedi'))
            ->line('Konum: '.($r->location ?: 'Belirtilmedi'));

        if ($budget) {
            $mail->line('Bütçe: '.$budget);
        }

        return $mail
            ->line('Açıklama: '.$r->description)
            ->line('İletişim: '.$r->name.' · '.$r->phone.' · '.$r->email)
            ->action('Talebi Panelde Aç', rtrim(config('app.frontend_url'), '/').'/agency/requests');
    }

    public function toArray(object $notifiable): array
    {
        return [
            'type' => 'property_request_received',
            'property_request_id' => $this->request->id,
            'category_name' => $this->request->category_name,
            'location' => $this->request->location,
        ];
    }

    private function budgetLine(): ?string
    {
        $r = $this->request;
        $fmt = fn ($v) => number_format((float) $v, 0, ',', '.');

        if ($r->price_min && $r->price_max) {
            return $fmt($r->price_min).' – '.$fmt($r->price_max).' '.$r->currency;
        }
        if ($r->price_max) {
            return '≤ '.$fmt($r->price_max).' '.$r->currency;
        }
        if ($r->price_min) {
            return '≥ '.$fmt($r->price_min).' '.$r->currency;
        }

        return null;
    }
}
