<?php

namespace App\Mail;

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

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

    public function __construct(
        public Consultation $consultation,
        public string $icsContent,
        public ?string $paymentInstructions = 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 Has Been Approved',
        );
    }

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

        return new Content(
            markdown: 'emails.booking.approved.'.$locale,
            with: [
                'consultation' => $this->consultation,
                'user' => $this->consultation->user,
                'paymentInstructions' => $this->paymentInstructions,
                'formattedDate' => $this->getFormattedDate($locale),
                'formattedTime' => $this->getFormattedTime(),
                'duration' => $this->consultation->duration ?? 45,
                'consultationType' => $this->getConsultationTypeLabel($locale),
                'isPaid' => $this->consultation->consultation_type?->value === 'paid',
                'paymentAmount' => $this->consultation->payment_amount,
            ],
        );
    }

    public function attachments(): array
    {
        return [
            Attachment::fromData(fn () => $this->icsContent, 'consultation.ics')
                ->withMime('text/calendar'),
        ];
    }

    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');
    }

    public function getConsultationTypeLabel(string $locale): string
    {
        $type = $this->consultation->consultation_type?->value ?? 'free';

        if ($locale === 'ar') {
            return $type === 'paid' ? 'مدفوعة' : 'مجانية';
        }

        return $type === 'paid' ? 'Paid' : 'Free';
    }
}
