<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class Santri extends Model
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'nama',
        'nis',
        'kelas_id',
        'alamat',
        'tanggal_lahir',
        'jenis_kelamin',
        'tempat_lahir',
        'user_id',
        'foto',
        'status',
        'no_telp',
    ];

    protected $appends = ['foto_url'];

    public function getFotoUrlAttribute()
    {
        if ($this->foto) {
            return asset('storage/' . $this->foto);
        }
        return null;
    }

    public static function generateNis()
    {
        $lastSantri = self::orderBy('id', 'desc')->first();

        if ($lastSantri) {
            $lastNis = intval($lastSantri->nis);
            return str_pad($lastNis + 1, 6, '0', STR_PAD_LEFT);
        }

        return '000001';
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function kelas()
    {
        return $this->belongsTo(Kelas::class);
    }

    public function prestasis()
    {
        return $this->hasMany(Prestasi::class);
    }

    public function scopeActive($query)
    {
        return $query->where('status', 'aktif');
    }

}
