<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class KodeAksesKantor extends Model
{
    use HasFactory;

    protected $table = 'kode_akses_kantor';

    protected $fillable = [
        'unit_kerja_id',
        'created_by',
        'kode',
        'batas_penggunaan',
        'jumlah_digunakan',
        'kedaluwarsa_pada',
        'aktif',
    ];

    protected $casts = [
        'kedaluwarsa_pada' => 'datetime',
        'aktif' => 'boolean',
    ];

    public function unitKerja(): BelongsTo
    {
        return $this->belongsTo(UnitKerja::class, 'unit_kerja_id');
    }

    public function pembuat(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function scopeMasihBerlaku(Builder $query): Builder
    {
        return $query
            ->where('aktif', true)
            ->where('kedaluwarsa_pada', '>', now())
            ->whereColumn('jumlah_digunakan', '<', 'batas_penggunaan');
    }

    public function masihBisaDigunakan(): bool
    {
        return $this->aktif
            && $this->kedaluwarsa_pada->isFuture()
            && $this->jumlah_digunakan < $this->batas_penggunaan;
    }

    public function getSisaPenggunaanAttribute(): int
    {
        return max(0, $this->batas_penggunaan - $this->jumlah_digunakan);
    }

    public function getStatusLabelAttribute(): string
    {
        if (! $this->aktif) {
            return 'Dinonaktifkan';
        }

        if ($this->kedaluwarsa_pada->isPast()) {
            return 'Kedaluwarsa';
        }

        if ($this->jumlah_digunakan >= $this->batas_penggunaan) {
            return 'Kuota Habis';
        }

        return 'Aktif';
    }
}
