<?php

namespace App\Observers;

use App\Enums\ConsultationStatus;
use App\Enums\ConsultationType;
use App\Mail\BookingApprovedMail;
use App\Models\Consultation;
use App\Services\CalendarService;
use Illuminate\Support\Facades\Mail;

class ConsultationObserver
{
    public function __construct(
        protected CalendarService $calendarService
    ) {}

    public function updated(Consultation $consultation): void
    {
        if ($consultation->wasChanged('status') && $consultation->status === ConsultationStatus::Approved) {
            $this->sendApprovalEmail($consultation);
        }
    }

    protected function sendApprovalEmail(Consultation $consultation): void
    {
        $consultation->loadMissing('user');

        $icsContent = $this->calendarService->generateIcs($consultation);

        $paymentInstructions = null;
        if ($consultation->consultation_type === ConsultationType::Paid) {
            $paymentInstructions = $this->getPaymentInstructions($consultation);
        }

        Mail::to($consultation->user)
            ->queue(new BookingApprovedMail($consultation, $icsContent, $paymentInstructions));
    }

    protected function getPaymentInstructions(Consultation $consultation): string
    {
        $locale = $consultation->user->preferred_language ?? 'ar';
        $amount = number_format($consultation->payment_amount ?? 0, 2);

        if ($locale === 'ar') {
            return "يرجى دفع مبلغ {$amount} شيكل قبل موعد الاستشارة.";
        }

        return "Please pay {$amount} ILS before your consultation.";
    }
}
