<?php

namespace App\Models;

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

class Beneficiary extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'nik', 'address', 'village', 'district',
        'foster_parent_name', 'foster_parent_role',
        'latitude', 'longitude', 'status'
    ];

    public function horticultures()
    {
        return $this->hasMany(Horticulture::class);
    }

    public function livestocks()
    {
        return $this->hasMany(Livestock::class);
    }

    public function poultries()
    {
        return $this->hasMany(Poultry::class);
    }

    public function fish()
    {
        return $this->hasMany(Fish::class);
    }

    public function documentations()
    {
        return $this->hasMany(Documentation::class);
    }

    public function monitorings()
    {
        return $this->hasMany(Monitoring::class);
    }

    /**
     * Scope a query to only include beneficiaries accessible by the current user.
     */
    public function scopeAccessibleBy($query, $user)
    {
        if (!$user) {
            return $query;
        }

        // Admin, Pembina, Pengarah, Koordinator Kecamatan see everything
        if ($user->hasAnyRole(['Admin', 'Pembina', 'Pengarah', 'Koordinator Kecamatan', 'Petugas Lapangan'])) {
            return $query;
        }

        // Orang Tua Asuh and Koordinator Desa only see their village
        if ($user->hasAnyRole(['Orang Tua Asuh', 'Koordinator Desa'])) {
            if ($user->village) {
                return $query->where('village', $user->village);
            }
        }

        // Default: no access if no village specified for restricted roles
        return $query->whereRaw('1 = 0');
    }
}
