<?php

namespace App\Models\Game\Player;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * The connection name for the model.
     *
     * @var string|null
     */
    protected $connection = 'player';

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'item';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'owner_id',
        'window',
        'pos',
        'count',
        'vnum',
	'value0',
	'value1',
	'value2',
	'value3',
	'value4',
	'value5',
        'socket0',
	'socket1',
	'socket2',
	'socket3',
	'socket4',
	'socket5',
    ];

    /**
     * Find the next available slot in a specific window for a player
     *
     * @param int $ownerId
     * @param string $window
     * @param int $maxSlots
     * @return int|false Returns slot number or false if no slots available
     */
    public static function getNextAvailableSlot(int $ownerId, string $window = 'MALL', int $maxSlots = 45)
    {
        $usedSlots = self::where('owner_id', $ownerId)
            ->where('window', $window)
            ->pluck('pos')
            ->toArray();

        // Find the first available slot starting from 0
        $slot = 0;
        while ($slot < $maxSlots) {
            if (!in_array($slot, $usedSlots)) {
                return $slot;
            }
            $slot++;
        }

        // No available slots
        return false;
    }

    /**
     * Check if player has available slots in a window
     *
     * @param int $ownerId
     * @param string $window
     * @param int $maxSlots
     * @return bool
     */
    public static function hasAvailableSlots(int $ownerId, string $window = 'MALL', int $maxSlots = 45): bool
    {
        $usedSlotCount = self::where('owner_id', $ownerId)
            ->where('window', $window)
            ->count();

        return $usedSlotCount < $maxSlots;
    }
}