<?php

namespace App\Models;

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

class Siswa extends Model
{
    use HasFactory;

    /**
     * Nama tabel
     */
    protected $table = 'siswa';

    /**
     * Primary key
     */
    protected $primaryKey = 'id';

    /**
     * Tipe primary key
     */
    protected $keyType = 'int';

    /**
     * Auto increment
     */
    public $incrementing = true;

    /**
     * Kolom yang boleh diisi (mass assignment)
     */
    protected $fillable = [
        'nis',
        'nama',
        'kelas',
        'alamat',
        'no_hp',
    ];

    /**
     * Casting tipe data
     */
    protected $casts = [
        'id'    => 'integer',
        'no_hp' => 'string', // agar nomor HP tidak hilang angka 0 di depan
    ];

    /**
     * Accessor: format nomor HP (opsional)
     * Contoh: 08123456789
     */
    public function getNoHpAttribute($value)
    {
        return (string) $value;
    }

    /**
     * Scope pencarian siswa
     * Contoh: Siswa::search('Asep')->get();
     */
    public function scopeSearch($query, $keyword)
    {
        return $query->where('nama', 'like', "%{$keyword}%")
                     ->orWhere('nis', 'like', "%{$keyword}%")
                     ->orWhere('kelas', 'like', "%{$keyword}%");
    }
    public function anggota()
{
    return $this->hasOne(AnggotaPerpustakaan::class);
}
public function aktifkan($id)
{
    $siswa = Siswa::findOrFail($id);

    if (!$siswa->anggota) {
        return redirect()->back()->with('error', 'Siswa belum terdaftar');
    }

    $siswa->anggota->update([
        'status' => 'aktif'
    ]);

    return redirect()->back()
        ->with('success', 'Anggota berhasil diaktifkan kembali');
}

}
