<?php

use App\Models\ServiceContent;
use App\Models\SiteManagement;
use App\Models\SiteManagementContentField;
use App\Models\SiteManagementFieldType;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

function isActiveRoute($route, $output = 'active') {

	if ((is_array($route) && in_array(Route::currentRouteName(), $route)) || Route::currentRouteName() == $route) {
		return $output;
	}
}

function adminSession() {
	if (Auth::guard('admin')->check()) {
		// if (!Session::has('company')) {
		// 	$company = schoolInformation();
		// 	Session::put('company', $company);
		// }

		// if (!Session::has('configParameters')) {
		// 	$idUser = Auth::guard('admin')->user()->id;

		// 	Session::put('configParameters', getConfigParameters([
		// 		'idUser' => $idUser,
		// 	]));
		// }
	}
}

function getServiceContent($id) {
	$serviceContents = ServiceContent::where('service_id',$id)
		->with([
			'siteManagementComponentField',
            'siteManagementFieldType',
		])->whereHas('siteManagementFieldType', function($query) {
			$query->whereNull('site_management_field_type_id');
		})->get();

	if ($serviceContents->isEmpty()) {
		return [];
	}

	$components = [];

    // Itera pelos registros encontrados
    foreach ($serviceContents as $content) {
        $componentField = $content->siteManagementComponentField;
        $fieldType = $content->siteManagementFieldType;

        // Inicializa um novo objeto para o componente, se necessário
        if (!isset($components[$content->service_id])) {
            $components[$content->service_id] = new \stdClass();
        }
        // Cria um novo objeto para o campo do componente
        $components[$content->service_id]->{$componentField->value} = new \stdClass();
        
        // Se o tipo de campo for nulo, carrega todos os subcampos relacionados
        if (is_null($fieldType->site_management_field_type_id)) {
            $fields = SiteManagementFieldType::where('site_management_field_type_id', $fieldType->id)
                ->get(['id', 'label', 'value']);

            foreach ($fields as $field) {
                $components[$content->service_id]->{$componentField->value}->{$field->value} =
                    ServiceContent::where([
                        'service_id' => $id,
                        'site_management_component_field_id' => $componentField->id,
                        'site_management_field_type_id' => $field->id,
                    ])->first()->value ?? null;
            }
        } else {
            // Caso contrário, atribui o valor diretamente
            $components[$content->service_id]->{$componentField->value} = $content->value;
        }
    }

    return $components;

		
	$serviceCont = new \stdClass;

	return $serviceCont;
}

function getSiteManagement($route) {
	$siteManagement = SiteManagement::where('route',$route)->first();

	if(!$siteManagement){
		return[];
	}

	$contentFields = $siteManagement->siteManagementContentField()->with([
		'siteManagementComponentField',
		'siteManagementComponent',
		'siteManagementFieldType',
	])->whereHas('siteManagementFieldType', function($query) {
		$query->whereNull('site_management_field_type_id');
	})->get();	

	$components = [];

	foreach ($contentFields as $contentField) {
		$siteManagementComponentField = $contentField->siteManagementComponentField;
		$siteManagementComponent = $contentField->siteManagementComponent;
		
		if (!isset($components[$siteManagementComponent->value])) {
			$components[$siteManagementComponent->value] = new \stdClass();
		}
		
		$components[$siteManagementComponent->value]->{$siteManagementComponentField->value} = new \stdClass();
		
		if (is_null($contentField->siteManagementFieldType->site_management_field_type_id)) {
			$fields = SiteManagementFieldType::query()->where('site_management_field_type_id', $contentField->siteManagementFieldType->id)->get(['id', 'label', 'value']);
			
			foreach ($fields as $field) {
				// dd($siteManagementComponentField->id);
				$components[$siteManagementComponent->value]->{$siteManagementComponentField->value}->{$field->value} = SiteManagementContentField::query()->where([
					'site_management_id' => $siteManagement->id,
					'site_management_component_id' => $siteManagementComponent->id,
					'site_management_component_field_id' => $siteManagementComponentField->id,
					'site_management_field_type_id' => $field->id,
				])->first()->value ?? null;
			}
		}
	}
	return $components;
}

function getCompany() {
	// with cache
	$company = Cache::remember('company', 60 * 60, function() {
		return \App\Models\Company::query()->first();
	});

	$company->fullAddress = "{$company->address}, {$company->number} - {$company->neighborhood}, {$company->city} - {$company->uf}, {$company->zip_code}";


	return $company;
}

function getNavSiteManagement() {
	$navFields = SiteManagement::whereNull('deleted_at')
	->orderBy('id')
	->pluck('title', 'route');

	$titles = [];
	$routes = [];
	foreach ($navFields as $route => $title) {
		$titles[] = $title; 
		$routes[] = $route; 
	}

	// Cria uma única variável contendo os dois arrays
	$navData = [
		'title' => $titles,
		'route' => $routes,
	];

	return $navData;
}
