<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class MexcoSupportTicket extends Model
{
    public const STATUS_NEW = 'new';

    public const STATUS_ASSIGNED = 'assigned';

    public const STATUS_IN_PROGRESS = 'in_progress';

    public const STATUS_WAITING_CUSTOMER = 'waiting_customer';

    public const STATUS_RESOLVED = 'resolved';

    public const STATUS_CLOSED = 'closed';

    protected $table = 'mexco_support_tickets';

    protected $fillable = [
        'ticket_number',
        'organisation_id',
        'event_id',
        'organisation_user_id',
        'contact_name',
        'contact_email',
        'subject',
        'description',
        'priority',
        'status',
        'assigned_admin_id',
    ];

    public function organisation(): BelongsTo
    {
        return $this->belongsTo(MexcoOrganisation::class, 'organisation_id');
    }

    public function event(): BelongsTo
    {
        return $this->belongsTo(MeetupEvent::class, 'event_id');
    }

    public function organisationUser(): BelongsTo
    {
        return $this->belongsTo(MexcoOrganisationUser::class, 'organisation_user_id');
    }

    public function assignee(): BelongsTo
    {
        return $this->belongsTo(MeetupSuperAdmin::class, 'assigned_admin_id');
    }

    public function messages(): HasMany
    {
        return $this->hasMany(MexcoSupportTicketMessage::class, 'ticket_id')->orderBy('created_at');
    }

    public static function statuses(): array
    {
        return [
            self::STATUS_NEW => 'New',
            self::STATUS_ASSIGNED => 'Assigned',
            self::STATUS_IN_PROGRESS => 'In progress',
            self::STATUS_WAITING_CUSTOMER => 'Waiting on customer',
            self::STATUS_RESOLVED => 'Resolved',
            self::STATUS_CLOSED => 'Closed',
        ];
    }

    public static function priorities(): array
    {
        return [
            'low' => 'Low',
            'normal' => 'Normal',
            'high' => 'High',
            'urgent' => 'Urgent',
        ];
    }

    public function statusLabel(): string
    {
        return self::statuses()[$this->status] ?? ucfirst(str_replace('_', ' ', $this->status));
    }
}
