<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class Visitor extends Model
{
    use HasFactory;

    protected $fillable = [
        'visit_id',
        'name',
        'email',
        'phone',
        'company_name',
        'id_front_image',
        'id_back_image',
        'is_main_visitor',
    ];

    protected $casts = [
        'is_main_visitor' => 'boolean',
    ];

    /**
     * Get the visit for this visitor
     */
    public function visit()
    {
        return $this->belongsTo(Visit::class);
    }

    /**
     * Get URL for front ID image
     */
    public function getIdFrontImageUrlAttribute(): ?string
    {
        return $this->id_front_image
            ? Storage::disk('public')->url($this->id_front_image)
            : null;
    }

    /**
     * Get URL for back ID image
     */
    public function getIdBackImageUrlAttribute(): ?string
    {
        return $this->id_back_image
            ? Storage::disk('public')->url($this->id_back_image)
            : null;
    }

    /**
     * Delete ID images when visitor is deleted
     */
    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($visitor) {
            if ($visitor->id_front_image) {
                Storage::disk('public')->delete($visitor->id_front_image);
            }
            if ($visitor->id_back_image) {
                Storage::disk('public')->delete($visitor->id_back_image);
            }
        });
    }
}
