<?php

namespace App\Services;

use App\Models\ProfileFieldGroup;
use App\Models\AssociationProfileFieldSetting;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;

class ProfileFieldService
{
    /**
     * Get all active profile field groups and their visible fields for a specific association.
     * Merges Global and Local definitions.
     */
    public function getGroupsWithFields(int $associationId): Collection
    {
        // 1. Fetch Groups (Global OR Local) that are Active
        $groups = ProfileFieldGroup::query()
            ->where('is_active', true)
            ->where(function (Builder $query) use ($associationId) {
                $query->whereNull('association_id') // Global
                      ->orWhere('association_id', $associationId); // Local
            })
            ->orderBy('order')
            ->get();

        // 2. Hydrate fields for each group
        return $groups->map(function ($group) use ($associationId) {
            
            $fields = $group->fields()
                ->where(function (Builder $query) use ($associationId) {
                    $query->whereNull('association_id') // Global fields
                          ->orWhere('association_id', $associationId); // Local fields
                })
                ->orderBy('order')
                ->get();

            // 3. Process fields (Overlay settings)
            $processedFields = $fields->map(function ($field) use ($associationId) {
                // Determine effective settings
                $setting = $field->settings->where('association_id', $associationId)->first();

                // If it's a Global field (no association_id), it MUST have a setting to be visible/configured
                // UNLESS we decide Global fields are visible by default? 
                // Usually Global fields need an explicit "turn on" via settings, OR they are on by default.
                // Based on previous logic, Onboarding required settings to exist.
                // Let's adopt a safe production rule:
                // - Global Field: Use Setting if exists. If not, default to field's own prop IF intended to be auto-global?
                //   Actually, let's look at the Setting model. `is_enabled` default is true.
                
                // Effective Properties
                $isVisible = $field->is_visible; // Local default
                $isRequired = $field->is_required; // Local default
                
                if (!$field->association_id) {
                    // It is a Global Field
                    if ($setting) {
                        // Use the override
                        $isVisible = $setting->is_visible && $setting->is_enabled;
                        $isRequired = $setting->is_required;
                    } else {
                        // Global field with NO setting
                        // Logic: Global fields require explicit opt-in by association admin
                        // This prevents new system fields from appearing in all associations
                        $isVisible = false;
                        $isRequired = false;
                    }
                } else {
                    // It is a Local Field (belongs to association)
                    // It uses its own properties. Settings are ignored/redundant.
                }

                // Attach effective properties to the object for easy access
                $field->effective_is_visible = $isVisible;
                $field->effective_is_required = $isRequired;

                return $field;
            })->filter(function ($field) {
                return $field->effective_is_visible; // Filter out hidden ones
            });

            $group->setRelation('fields', $processedFields);
            
            return $group;

        })->filter(function ($group) {
            return $group->fields->isNotEmpty(); // Only return groups that have at least one visible field
        });
    }
}
