<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Models;

use App\Core\Model;
use App\Core\App;

class Locker extends Model
{
    protected static string $table = 'sa_lockers';
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;
    protected static array $fillable = [
        'code', 'name_ar', 'name_en', 'facility_id', 'discipline_id',
        'locker_type', 'location_note', 'is_active',
    ];

    public static function getTypeOptions(): array
    {
        return [
            'standard' => 'عادي',
            'large'    => 'كبير',
            'vip'      => 'VIP',
        ];
    }

    public static function findByCode(string $code): ?self
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne("SELECT * FROM sa_lockers WHERE code = ? AND is_archived = 0", [$code]);
        return $row ? static::hydrate($row) : null;
    }

    public function getCurrentRental(): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne(
            "SELECT lr.*, p.full_name_ar as player_name
             FROM sa_locker_rentals lr
             LEFT JOIN sa_players p ON p.id = lr.player_id
             WHERE lr.locker_id = ? AND lr.status IN ('active','grace_period','pending_eviction') AND lr.is_archived = 0
             ORDER BY lr.start_date DESC LIMIT 1",
            [(int) $this->id]
        );
    }

    public function isOccupied(): bool
    {
        return $this->getCurrentRental() !== null;
    }
}
