<?php

namespace App\Models;

use App\Models\Concerns\BelongsToBranch;
use App\Models\Concerns\HasAuditColumns;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class AdmissionApplication extends Model
{
    use BelongsToBranch;
    use HasAuditColumns;
    use SoftDeletes;

    protected $fillable = [
        'branch_id', 'application_number', 'student_name', 'gender', 'date_of_birth',
        'parent_name', 'contact', 'email', 'class_id', 'inquiry_id', 'family_id',
        'test_date', 'test_marks', 'test_status', 'status', 'enrolled_student_id', 'notes',
    ];

    protected function casts(): array
    {
        return [
            'date_of_birth' => 'date',
            'test_date' => 'date',
            'test_marks' => 'decimal:2',
        ];
    }

    public const STATUSES = ['pending', 'approved', 'rejected', 'waiting', 'enrolled'];

    public function schoolClass(): BelongsTo
    {
        return $this->belongsTo(SchoolClass::class, 'class_id');
    }

    public function family(): BelongsTo
    {
        return $this->belongsTo(Family::class);
    }

    public function enrolledStudent(): BelongsTo
    {
        return $this->belongsTo(Student::class, 'enrolled_student_id');
    }

    public function getStatusColorAttribute(): string
    {
        return [
            'pending' => 'secondary', 'approved' => 'primary', 'rejected' => 'danger',
            'waiting' => 'warning', 'enrolled' => 'success',
        ][$this->status] ?? 'secondary';
    }

    public static function nextNumber(int $branchId): string
    {
        $count = static::withoutGlobalScopes()->where('branch_id', $branchId)->withTrashed()->count();

        return 'APP-'.date('Y').'-'.str_pad((string) ($count + 1), 4, '0', STR_PAD_LEFT);
    }
}
