<?php

namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Support\Facades\DB;

class FamilyStudent extends BaseModel
{
    protected $table = 'family_students';

    // CI model didn't specify timestamps
    public $timestamps = true;

    protected $fillable = [
        'family_id',
        'student_id',
        'is_primary_home',
        'notes',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'family_id'        => 'integer',
        'student_id'       => 'integer',
        'is_primary_home'  => 'boolean',
    ];

    /* Optional relationships */
    public function family()
    {
        return $this->belongsTo(Family::class, 'family_id');
    }

    public function student()
    {
        return $this->belongsTo(Student::class, 'student_id');
    }

    /**
     * Laravel equivalent of CI getFamiliesForStudent().
     * Returns array rows: families.* + is_primary_home
     */
    public static function getFamiliesForStudent(int $studentId): array
    {
        return DB::table('family_students as fs')
            ->join('families as f', 'f.id', '=', 'fs.family_id')
            ->where('fs.student_id', $studentId)
            ->where('f.is_active', 1)
            ->orderByDesc('fs.is_primary_home')
            ->orderBy('f.household_name')
            ->select('f.*', 'fs.is_primary_home')
            ->get()
            ->map(fn ($r) => (array) $r)
            ->all();
    }
}