<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use App\Models\Scopes\TenantScope;

class JoinRequest extends Model
{
    use HasFactory;
    
    protected $fillable = [
        'uuid',
        'patient_id',
        'tenant_id',
        'status',
        'notes',
        'requested_at',
        'responded_at',
        'responded_by',
        'queue_entry_id'
    ];
    
    protected $casts = [
        'requested_at' => 'datetime',
        'responded_at' => 'datetime',
    ];
    
    protected static function boot()
    {
        parent::boot();
        
        static::creating(function ($model) {
            if (empty($model->uuid)) {
                $model->uuid = (string) Str::uuid();
            }
            if (empty($model->requested_at)) {
                $model->requested_at = now();
            }
        });
        
        // Apply TenantScope
        static::addGlobalScope(new TenantScope);
    }
    
    // Relationships
    public function patient()
    {
        return $this->belongsTo(Patient::class);
    }
    
    public function tenant()
    {
        return $this->belongsTo(Tenant::class);
    }
    
    public function respondedBy()
    {
        return $this->belongsTo(User::class, 'responded_by');
    }
    
    public function queueEntry()
    {
        return $this->belongsTo(WaitingQueue::class, 'queue_entry_id');
    }
    
    // Scopes
    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }
    
    public function scopeApproved($query)
    {
        return $query->where('status', 'approved');
    }
    
    public function scopeRejected($query)
    {
        return $query->where('status', 'rejected');
    }
    
    // Methods
    public function approve($user = null, $notes = null)
    {
        $this->update([
            'status' => 'approved',
            'responded_at' => now(),
            'responded_by' => $user?->id,
            'notes' => $notes
        ]);
        
        return $this;
    }
    
    public function reject($user = null, $notes = null)
    {
        $this->update([
            'status' => 'rejected',
            'responded_at' => now(),
            'responded_by' => $user?->id,
            'notes' => $notes
        ]);
        
        return $this;
    }
    
    public function isPending()
    {
        return $this->status === 'pending';
    }
    
    public function isApproved()
    {
        return $this->status === 'approved';
    }
    
    public function isRejected()
    {
        return $this->status === 'rejected';
    }
    
    /**
     * Get the route key for the model
     */
    public function getRouteKeyName()
    {
        return 'id';
    }
}
