<?php

namespace App\Services\EmergencyContacts;

use App\Models\EmergencyContact;
use App\Models\Student;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class EmergencyContactDirectoryService
{
    public function groups(): array
    {
        $parentIds = EmergencyContact::query()
            ->distinct()
            ->pluck('parent_id')
            ->filter(static fn ($id) => (int) $id > 0)
            ->values()
            ->all();

        $groups = [];
        foreach ($parentIds as $parentId) {
            $parentId = (int) $parentId;
            $parent = User::query()->find($parentId);

            $parentName = $parent
                ? trim((string) $parent->firstname . ' ' . (string) $parent->lastname)
                : 'Unknown Parent';
            if ($parentName === '') {
                $parentName = 'Unknown Parent';
            }

            $parentPhone = $parent ? (string) ($parent->cellphone ?? '') : '';
            $secondPhone = $this->secondParentPhone($parentId);

            $students = Student::query()
                ->select(['id', 'firstname', 'lastname', 'school_id'])
                ->where('parent_id', $parentId)
                ->get()
                ->toArray();

            $contacts = EmergencyContact::query()
                ->where('parent_id', $parentId)
                ->orderBy('updated_at', 'DESC')
                ->get()
                ->toArray();

            $groups[] = [
                'parent_id' => $parentId,
                'parent_name' => $parentName,
                'parent_phones' => array_values(array_filter([
                    $parentPhone,
                    $secondPhone,
                ], static fn ($value) => (string) $value !== '')),
                'students' => $students,
                'contacts' => $contacts,
            ];
        }

        return $groups;
    }

    private function secondParentPhone(int $parentId): string
    {
        try {
            if (!Schema::hasTable('parents')) {
                return '';
            }

            if (!Schema::hasColumn('parents', 'secondparent_phone')) {
                return '';
            }

            $phone = DB::table('parents')
                ->where('firstparent_id', $parentId)
                ->orderByDesc('updated_at')
                ->value('secondparent_phone');

            return $phone ? (string) $phone : '';
        } catch (\Throwable $e) {
            Log::debug('EmergencyContactDirectoryService: could not load second parent phone: ' . $e->getMessage());
            return '';
        }
    }
}
