<?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\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;

class Family extends Model
{
    use BelongsToBranch;
    use HasAuditColumns;
    use SoftDeletes;
    use LogsActivity;

    protected $fillable = [
        'branch_id', 'family_code',
        'father_name', 'father_cnic', 'father_mobile', 'father_occupation',
        'mother_name', 'mother_cnic', 'mother_mobile',
        'guardian_name', 'guardian_cnic', 'guardian_relation',
        'email', 'address', 'emergency_contact', 'user_id',
    ];

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['family_code', 'father_name', 'father_mobile'])
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }

    public function students(): HasMany
    {
        return $this->hasMany(Student::class);
    }

    public function challans(): HasMany
    {
        return $this->hasMany(FeeChallan::class);
    }

    public function activeStudents(): HasMany
    {
        return $this->students()->where('status', 'active');
    }

    public function portalUser(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /** Primary guardian display name (guardian → father → mother). */
    public function getPrimaryContactNameAttribute(): string
    {
        return $this->guardian_name ?: ($this->father_name ?: ($this->mother_name ?: '—'));
    }

    public function getPrimaryMobileAttribute(): string
    {
        return $this->father_mobile ?: ($this->mother_mobile ?: ($this->emergency_contact ?: '—'));
    }

    /** Two-letter initials from the primary contact name (for avatars). */
    public function getInitialsAttribute(): string
    {
        $parts = preg_split('/\s+/', trim($this->primary_contact_name), -1, PREG_SPLIT_NO_EMPTY);
        if (empty($parts)) {
            return '?';
        }
        $first = mb_substr($parts[0], 0, 1);
        $second = count($parts) > 1 ? mb_substr($parts[count($parts) - 1], 0, 1) : '';

        return mb_strtoupper($first.$second) ?: '?';
    }

    /** Generate the next family code for a branch, e.g. FAM-0001. */
    public static function nextCode(int $branchId): string
    {
        $count = static::withoutGlobalScopes()->where('branch_id', $branchId)->withTrashed()->count();

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