<?php

namespace App\Services\Auth;

use App\Services\PhoneFormatterService;

class RegistrationFormatterService
{
    public function __construct(private PhoneFormatterService $phoneFormatter)
    {
    }

    public function format(array $payload): array
    {
        $g = static function (string $key) use ($payload): string {
            return trim((string) ($payload[$key] ?? ''));
        };

        $data = [
            'firstname' => $this->formatName($g('firstname')),
            'lastname' => $this->formatName($g('lastname')),
            'email' => $this->formatEmail($g('email')),
            'gender' => $g('gender'),
            'city' => $this->formatName($g('city')),
            'cellphone' => $this->phoneFormatter->formatPhoneNumber($g('cellphone')),
            'address_street' => $this->formatAddress($g('address_street')),
            'apt' => strtoupper($g('apt')),
            'state' => strtoupper($g('state')),
            'zip' => $g('zip'),
            'accept_school_policy' => (int) ($payload['accept_school_policy'] ?? 0),
        ];

        $noSecondInfo = !empty($payload['no_second_parent_info']);

        $secondFirstname = $this->formatName($g('second_firstname'));
        $secondLastname = $this->formatName($g('second_lastname'));
        $secondGender = $g('second_gender');
        $secondEmail = $this->formatEmail($g('second_email'));
        $secondCellphone = $this->phoneFormatter->formatPhoneNumber($g('second_cellphone'));

        $secondProvided = !$noSecondInfo && (
            $secondFirstname !== '' ||
            $secondLastname !== '' ||
            $secondGender !== '' ||
            $secondEmail !== '' ||
            preg_replace('/\D/', '', (string) $secondCellphone) !== ''
        );

        if ($secondProvided) {
            $data['second_firstname'] = $secondFirstname;
            $data['second_lastname'] = $secondLastname;
            $data['second_gender'] = $secondGender;
            $data['second_email'] = $secondEmail;
            $data['second_cellphone'] = $secondCellphone;
        }

        return $data;
    }

    private function formatName(string $name): string
    {
        $name = trim($name);
        if ($name === '') {
            return '';
        }

        return ucwords(strtolower($name), " -");
    }

    private function formatEmail(string $email): string
    {
        return strtolower(trim($email));
    }

    private function formatAddress(string $address): string
    {
        $address = trim($address);
        if ($address === '') {
            return '';
        }

        return ucwords(strtolower($address));
    }
}
