<?php

namespace App\Models;

use App\Traits\VisibleToAdmin;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Ticket extends Model
{
    use HasFactory;
    use VisibleToAdmin;

    // This tells the trait how to reach the user who controls visibility
    protected function adminVisibilityRelation(): string
    {
        return 'user';
    }
    const STATUS_OPEN = 'open';
    const STATUS_PENDING = 'pending';
    const STATUS_IN_PROGRESS = 'in_progress';
    const STATUS_RESOLVED = 'resolved';
    const STATUS_CLOSED = 'closed';

    protected $fillable = [
        'user_id',
        'subject',
        'priority',
        'status',
    ];
    protected $casts = [
        'user_id' => 'integer',
    ];
    // Relationships
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function messages()
    {
        return $this->hasMany(TicketMessages::class, 'ticket_id');
    }

    // Helper: get URLs of attachments
    public function attachmentUrls()
    {
        if (!$this->attachments) {
            return [];
        }

        return array_map(fn($path) => asset('storage/' . $path), $this->attachments);
    }

    // Helper: check if ticket has attachments
    public function hasAttachments(): bool
    {
        return !empty($this->attachments);
    }

    /** ================= SCOPES ================= */

    public function scopeOpen($query)
    {
        return $query->where('status', self::STATUS_OPEN);
    }

    public function scopePending($query)
    {
        return $query->where('status', self::STATUS_PENDING);
    }

    public function scopeInProgress($query)
    {
        return $query->where('status', self::STATUS_IN_PROGRESS);
    }

    public function scopeResolved($query)
    {
        return $query->where('status', self::STATUS_RESOLVED);
    }

    public function scopeClosed($query)
    {
        return $query->where('status', self::STATUS_CLOSED);
    }
}
