<?php

namespace App\Mail;

use App\Models\Consultation;
use App\Services\CalendarService;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

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

    /**
     * Create a new message instance.
     */
    public function __construct(
        public Consultation $consultation,
        public string $emailLocale = 'en',
        public ?string $paymentInstructions = null
    ) {}

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: $this->emailLocale === 'ar'
                ? 'تأكيد الحجز - مكتب ليبرا للمحاماة'
                : 'Booking Confirmed - Libra Law Firm',
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            markdown: 'emails.booking.guest-approved.'.$this->emailLocale,
            with: [
                'consultation' => $this->consultation,
                'guestName' => $this->consultation->guest_name,
                'formattedDate' => $this->getFormattedDate(),
                'formattedTime' => $this->getFormattedTime(),
                'isPaid' => $this->consultation->consultation_type?->value === 'paid',
                'paymentAmount' => $this->consultation->payment_amount,
                'paymentInstructions' => $this->paymentInstructions,
            ],
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, \Illuminate\Mail\Mailables\Attachment>
     */
    public function attachments(): array
    {
        try {
            $calendarService = app(CalendarService::class);
            $icsContent = $calendarService->generateIcs($this->consultation);

            return [
                Attachment::fromData(fn () => $icsContent, 'consultation.ics')
                    ->withMime('text/calendar'),
            ];
        } catch (\Exception $e) {
            Log::error('Failed to generate calendar attachment for guest email', [
                'consultation_id' => $this->consultation->id,
                'error' => $e->getMessage(),
            ]);

            return [];
        }
    }

    /**
     * Get formatted date based on locale.
     */
    private function getFormattedDate(): string
    {
        $date = $this->consultation->booking_date;

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

    /**
     * Get formatted time.
     */
    private function getFormattedTime(): string
    {
        return Carbon::parse($this->consultation->booking_time)->format('h:i A');
    }
}
