<?php

namespace App\Models;

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

class PsajParticipant extends Model
{
    use HasFactory;

    protected $fillable = [
        'nama',
        'nik',
        'nisn',
        'nis',
        'kelas',
        'tempat_lahir',
        'tanggal_lahir',
        'nama_ibu',
        'photo',
        'disability_type_id',
        'school_id',
        'jenjang',
        'no_peserta',
        'status',
        'is_locked',
        'submitted_at',
    ];

    protected $casts = [
        'tanggal_lahir' => 'date',
        'submitted_at' => 'datetime',
        'is_locked' => 'boolean',
    ];

    /**
     * Get the school that owns the participant
     */
    public function school()
    {
        return $this->belongsTo(School::class);
    }

    /**
     * Get the disability type
     */
    public function disabilityType()
    {
        return $this->belongsTo(DisabilityType::class);
    }

    /**
     * Get age from tanggal_lahir
     */
    public function getAgeAttribute()
    {
        return $this->tanggal_lahir->age;
    }

    /**
     * Auto-assign kelas based on jenjang
     */
    public static function getDefaultKelas($jenjang)
    {
        return match($jenjang) {
            'SDLB' => 'VI',
            'SMPLB' => 'IX',
            'SMALB' => 'XII',
            default => null,
        };
    }

    /**
     * Get jenjang options based on school type
     */
    public static function getJenjangOptions($schoolJenisSekolah)
    {
        // Only SLB schools can have PSAJ participants
        if (!str_contains(strtoupper($schoolJenisSekolah), 'SLB')) {
            return [];
        }

        $options = [];
        if (str_contains(strtoupper($schoolJenisSekolah), 'SDLB')) {
            $options['SDLB'] = 'SDLB (Kelas VI)';
        }
        if (str_contains(strtoupper($schoolJenisSekolah), 'SMPLB')) {
            $options['SMPLB'] = 'SMPLB (Kelas IX)';
        }
        if (str_contains(strtoupper($schoolJenisSekolah), 'SMALB')) {
            $options['SMALB'] = 'SMALB (Kelas XII)';
        }

        return $options;
    }

    /**
     * Generate unique no_peserta
     * Format: Ktunaan-VI-NPSN-Tahun-NoUrut
     * Contoh: A-VI-20301234-2026-0001
     */
    public static function generateNoPeserta($jenjang, $schoolId)
    {
        $year = date('Y');
        $kelas = self::getDefaultKelas($jenjang);
        
        // Get school NPSN
        $school = \App\Models\School::find($schoolId);
        $npsn = $school ? $school->npsn : '00000000';
        
        // Get last number for this jenjang and year
        $lastParticipant = self::where('jenjang', $jenjang)
            ->where('school_id', $schoolId)
            ->whereYear('created_at', $year)
            ->orderBy('no_peserta', 'desc')
            ->first();

        if ($lastParticipant && $lastParticipant->no_peserta) {
            // Extract number from last no_peserta
            $parts = explode('-', $lastParticipant->no_peserta);
            $lastNumber = (int) end($parts);
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }

        // Will be updated with disability type when participant is created
        return sprintf('TMP-%s-%s-%s-%04d', $kelas, $npsn, $year, $newNumber);
    }
    
    /**
     * Update no_peserta with disability type code
     */
    public function updateNoPesertaWithDisability()
    {
        if (!$this->disability_type_id) {
            return;
        }
        
        $disabilityType = $this->disabilityType;
        if (!$disabilityType) {
            return;
        }
        
        // Get disability code (A, B, C, D, E, dll)
        $disabilityCode = $disabilityType->code;
        
        // Parse current no_peserta
        $parts = explode('-', $this->no_peserta);
        if (count($parts) >= 5) {
            // Replace TMP with disability code
            $parts[0] = $disabilityCode;
            $newNoPeserta = implode('-', $parts);
            
            $this->no_peserta = $newNoPeserta;
            $this->saveQuietly(); // Save without firing events
        }
    }
}
