<?php

namespace App\Models;

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

class TicketCenter extends Model
{
    protected $primaryKey = 'center_id';
    public $incrementing = true;
    public $timestamps = true;

    protected $fillable = [
        'name',
        'location',
        'staff_user_id',
    ];

    /**
     * Get the staff member assigned to this ticket center
     */
    public function staff(): BelongsTo
    {
        return $this->belongsTo(User::class, 'staff_user_id', 'id');
    }

    /**
     * Get all users with staff role for dropdown
     */
    public static function getStaffUsers()
    {
        return User::where('role', 'staff')->get();
    }

    /**
     * Get ticket centers with their assigned staff
     */
    public static function getCentersWithStaff()
    {
        return self::with('staff')->get();
    }

    /**
     * Check if a user is already assigned to a ticket center
     */
    public static function isUserAssigned($userId, $excludeCenterId = null)
    {
        $query = self::where('staff_user_id', $userId);

        if ($excludeCenterId) {
            $query->where('center_id', '!=', $excludeCenterId);
        }

        return $query->exists();
    }

    /**
     * Get available staff (not assigned to any center)
     */
    public static function getAvailableStaff($excludeCenterId = null)
    {
        $assignedUserIds = self::when($excludeCenterId, function ($query) use ($excludeCenterId) {
            return $query->where('center_id', '!=', $excludeCenterId);
        })->pluck('staff_user_id');

        return User::where('role', 'staff')
            ->whereNotIn('id', $assignedUserIds)
            ->get();
    }
}
