<?php

declare(strict_types=1);

namespace App\Models\Market;

use App\Models\Model;
use App\Models\User;

class Organization extends Model
{
    protected ?string $table = 'organizations';

    protected array $fillable = [
        'hashkey',
        'name',
        'type',
        'address',
        'registration_number',
        'cin',
        'tin',
        'cooperative_type',
        'cooperative_category',
        'registration_date',
        'contact_person',
        'contact_number',
        'contact_email',
        'compliance_status',
        'is_active',
        'created_by',
        'updated_by',
    ];

    protected array $casts = [
        'is_active' => 'boolean',
        'registration_date' => 'date',
    ];

    public function members()
    {
        return $this->hasMany(CooperativeMember::class, 'organization_id');
    }

    public function farmerProfiles()
    {
        return $this->hasMany(FarmerProfile::class, 'organization_id');
    }

    public function stores()
    {
        return $this->belongsToMany(Store::class, 'org_str', 'organization_id', 'store_id')
            ->withTimestamps();
    }

    public function mainAssignments()
    {
        return $this->hasMany(MainOrganization::class, 'organization_id');
    }

    public function isMain(?string $role = null): bool
    {
        $query = $this->mainAssignments()->where('is_active', true);
        if ($role !== null) {
            $query->where('role', $role);
        }
        return $query->exists();
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }
}
