<?php

namespace App\Jobs;

use App\Models\Budget;
use App\Mail\BudgetCreated;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

class SendBudgetEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $budget;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Budget $budget)
    {
        $this->budget = $budget;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // Recargar el modelo con sus relaciones
        $this->budget->load(['patient', 'items.medicalService', 'creator']);

        if ($this->budget->patient->email) {
            Mail::to($this->budget->patient->email)
                ->send(new BudgetCreated($this->budget));

            // Actualizar el estado del presupuesto
            $this->budget->status = 'sent';
            $this->budget->save();
        }
    }
} 