<?php

namespace App\Services\Parents;

use App\Models\EmergencyContact;
use App\Services\PhoneFormatterService;

class ParentEmergencyContactService
{
    public function __construct(
        private ParentConfigService $configService,
        private PhoneFormatterService $phoneFormatter
    ) {
    }

    public function list(int $parentId): array
    {
        return EmergencyContact::query()
            ->where('parent_id', $parentId)
            ->orderBy('emergency_contact_name')
            ->get()
            ->toArray();
    }

    public function store(int $parentId, array $payload): array
    {
        $context = $this->configService->context();
        $contact = EmergencyContact::query()->create([
            'parent_id' => $parentId,
            'emergency_contact_name' => $payload['name'],
            'cellphone' => $this->phoneFormatter->formatPhoneNumber($payload['cellphone']),
            'email' => $payload['email'] ?? null,
            'relation' => $payload['relation'] ?? null,
            'semester' => $context['semester'],
            'school_year' => $context['school_year'],
        ]);

        return $contact->toArray();
    }

    public function update(int $parentId, int $contactId, array $payload): array
    {
        $contact = EmergencyContact::query()
            ->where('id', $contactId)
            ->where('parent_id', $parentId)
            ->firstOrFail();

        $contact->update([
            'emergency_contact_name' => $payload['name'],
            'cellphone' => $this->phoneFormatter->formatPhoneNumber($payload['cellphone']),
            'email' => $payload['email'] ?? null,
            'relation' => $payload['relation'] ?? null,
        ]);

        return $contact->toArray();
    }
}
