<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Siswa extends Model
{
    protected $fillable = [
        'id_siswa', 
        'user_id', 
        'jurusan_id', 
        'nama_lengkap', 
        'nisn', 
        'kelas', 
        'peminatan', 
        'minat_bakat', 
        'ekonomi'
    ];

    protected static function boot()
    {
        parent::boot();

        // Logika otomatisasi ID Siswa (SW01, SW02, dst)
        static::creating(function ($model) {
            $latestSiswa = static::orderBy('id', 'desc')->first();
            
            if (!$latestSiswa) {
                $model->id_siswa = 'SW01';
            } else {
                // Mengambil angka di belakang 'SW' dan menambahkannya 1
                $number = intval(substr($latestSiswa->id_siswa, 2)) + 1;
                $model->id_siswa = 'SW' . str_pad($number, 2, '0', STR_PAD_LEFT);
            }
        });
    }

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

    public function jurusan() {
        return $this->belongsTo(Jurusan::class);
    }
}