<?php

namespace App\Mail;

use App\Models\Consultation;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class BookingRejectedEmail extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    public function __construct(
        public Consultation $consultation,
        public ?string $reason = null
    ) {
        $this->locale = $consultation->user->preferred_language ?? 'ar';
    }

    public function envelope(): Envelope
    {
        $locale = $this->consultation->user->preferred_language ?? 'ar';

        return new Envelope(
            subject: $locale === 'ar'
                ? 'تعذر الموافقة على طلب الاستشارة'
                : 'Your Consultation Request Could Not Be Approved',
        );
    }

    public function content(): Content
    {
        $locale = $this->consultation->user->preferred_language ?? 'ar';

        return new Content(
            markdown: 'emails.booking.rejected.'.$locale,
            with: [
                'consultation' => $this->consultation,
                'user' => $this->consultation->user,
                'reason' => $this->reason,
                'hasReason' => ! empty($this->reason),
                'formattedDate' => $this->getFormattedDate($locale),
                'formattedTime' => $this->getFormattedTime(),
            ],
        );
    }

    public function getFormattedDate(string $locale): string
    {
        $date = $this->consultation->booking_date;

        return $locale === 'ar'
            ? $date->format('d/m/Y')
            : $date->format('m/d/Y');
    }

    public function getFormattedTime(): string
    {
        $time = $this->consultation->booking_time;

        return Carbon::parse($time)->format('h:i A');
    }
}
