<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Ticket extends Model
{
    protected $fillable = [
        'ticket_number','client_id','client_user_id','device_id',
        'assigned_to','created_by','division','subject','description',
        'priority','status','source','category','sla_config_id',
        'sla_response_deadline','sla_solve_deadline','sla_responded_at',
        'sla_solved_at','sla_status','resolution','resolved_at','closed_at'
    ];
    protected $casts = [
        'sla_response_deadline' => 'datetime',
        'sla_solve_deadline'    => 'datetime',
        'sla_responded_at'      => 'datetime',
        'sla_solved_at'         => 'datetime',
        'resolved_at'           => 'datetime',
        'closed_at'             => 'datetime',
    ];

    public function client()     { return $this->belongsTo(Client::class); }
    public function clientUser() { return $this->belongsTo(ClientUser::class); }
    public function device()     { return $this->belongsTo(Device::class); }
    public function assignedTo() { return $this->belongsTo(User::class, 'assigned_to'); }
    public function createdBy()  { return $this->belongsTo(User::class, 'created_by'); }
    public function comments()   { return $this->hasMany(TicketComment::class)->orderBy('created_at'); }
    public function attachments(){ return $this->hasMany(TicketAttachment::class); }
    public function visits()     { return $this->hasMany(Visit::class); }
    public function visitSchedules() { return $this->belongsToMany(Visit::class, 'ticket_visit', 'ticket_id', 'visit_id'); }
    public function csat()       { return $this->hasOne(CsatSurvey::class); }
    public function slaConfig()  { return $this->belongsTo(SlaConfig::class); }

    public function updateSlaStatus(): void
    {
        if (!$this->sla_solve_deadline) return;
        $now       = now();
        $deadline  = $this->sla_solve_deadline;
        $warningAt = $deadline->copy()->subMinutes(60);

        if ($now->gte($deadline)) {
            $this->sla_status = 'breach';
        } elseif ($now->gte($warningAt)) {
            $this->sla_status = 'warning';
        } else {
            $this->sla_status = 'ok';
        }
        $this->saveQuietly();
    }

    public static function generateNumber(): string
    {
        $year   = date('Y');
        $random = strtoupper(substr(uniqid(), -5));
        return "TKT-{$year}-{$random}";
    }

    public function getPriorityBadgeAttribute(): string
    {
        $map = ['critical'=>'danger','high'=>'warning','medium'=>'info','low'=>'secondary'];
        return isset($map[$this->priority]) ? $map[$this->priority] : 'secondary';
    }

    public function getStatusBadgeAttribute(): string
    {
        $map = ['open'=>'primary','in_progress'=>'warning','waiting_client'=>'info','resolved'=>'success','closed'=>'secondary'];
        return isset($map[$this->status]) ? $map[$this->status] : 'secondary';
    }
}
