<?php
/*
 * @copyright Copyright (c) 2018 Ubiquiti Networks, Inc.
 * @see https://www.ubnt.com/
 */


declare(strict_types=1);


namespace SmsNotifier\Service;

use SmsNotifier\Data\NotificationData;
use Ubnt\UcrmPluginSdk\Service\PluginLogManager;

class SmsNumberProvider
{
    /*
     * go through client's contacts and find an applicable one, if any
     */
    public function getUcrmClientNumber(NotificationData $notificationData): ?string
    {
        $contacts = $notificationData->clientData['contacts'] ?? [];
        foreach ($contacts as $contact) {
            if ($this->isContactApplicable($notificationData->entity, $contact)) {

                return $contact['phone'];
            }
        }
        return null;
    }

    /*
     * go through client's contacts and find an applicable one, if any
     */
    public function getUcrmClientNumbers(NotificationData $notificationData = null, $arrayClientCRM = null)
{
    $log = PluginLogManager::create(); //Initialize Logger
    $arrayPhones = [];

    if ($arrayClientCRM != null) {
        foreach ($arrayClientCRM['contacts'] as $contact) {
            if (!empty($contact['phone'])) {
                if (isset($contact['types']) && is_array($contact['types'])) {
                    foreach ($contact['types'] as $type) {
                        $typeNameLower = trim(strtolower($type['name']));
                        if (in_array($typeNameLower, ['whatsapp', 'whatsnotifica'])) {
                            // Almacena varios números bajo el mismo tipo normalizado
                            $arrayPhones[$type['name']][] = $contact['phone'];
                        }
                    }
                }
            }
        }

    } else {
        foreach ($notificationData->clientData['contacts'] as $contact) {
            if (!empty($contact['phone'])) {
                if (isset($contact['types']) && is_array($contact['types'])) {
                    foreach ($contact['types'] as $type) {
                        $typeNameLower = trim(strtolower($type['name']));
                        if (in_array($typeNameLower, ['whatsapp', 'whatsnotifica', 'whatsactualiza'])) {
                            // Almacena varios números bajo el mismo tipo normalizado
                            $arrayPhones[$type['name']][] = $contact['phone'];
                        }
                    }
                }
            }
        }
    }

    return $arrayPhones;  // Devolver el arreglo de teléfonos por tipo
}


    /*
     * go through client's contacts and find an applicable one, if any
     */
    public function getAllUcrmClientNumbers($arrayClientCRM = null)
    {
        $log = PluginLogManager::create(); //Initialize Logger
        //$log->appendLog("Ejecutando metodo getUcrmClientNumbers: " . json_encode($arrayClientCRM) . PHP_EOL);
        // Array asociativo donde almacenarás los números de teléfono con sus tipos correspondientes
        $arrayPhones = [];


        //$log->appendLog("Entrando al if del método getUcrmClientNumbers: " . $arrayClientCRM . PHP_EOL);
        //$jsonNotificationData = json_decode($jsonNotificationData, true);
        // Recorrer los contactos del cliente para encontrar los teléfonos con sus tipos
        foreach ($arrayClientCRM['contacts'] as $contact) {

            if (!empty($contact['phone'])) {  // Verificar que el teléfono no esté vacío
                // agregamos al array asociativo
                $arrayPhones[] = $contact['phone'];
            }
        }



        return $arrayPhones;  // Devolver el arreglo de teléfonos por tipo
    }


    /*
     * not every contact has a phone; also check if the type of notification is applicable to contact
     */
    protected function isContactApplicable(string $entity, array $contact = null): bool
    {
        $log = PluginLogManager::create(); //Initialize Logger
        //$log->appendLog("Ejecutando metodo isContactApplicable: " . json_encode($contact) . PHP_EOL);
        //$entity_export = var_export($entity, true);
        //$log->appendLog("Valor de Entity: " . $entity_export . PHP_EOL);
        if (!$contact || empty($contact['phone'])) {
            $log->appendLog("contac vacio");
            return false;
        }
        //$log->appendLog("Entrando al switch del método isContactApplicable : " . json_encode($entity));
        switch ($entity) {
            case 'invoice':
                return false;
            case 'payment': {

                $types = $contact['types'] ?? [];
                foreach ($types as $type) {
                    //$log->appendLog("Entrando al case client del switch: " . json_encode($type));
                    if (trim(strtolower($type['name'])) == 'whatsapp') {
                        return true;
                    }
                }
                return false;
            }
            //return $contact['isBilling'] ?? false;
            case 'client': {

                $types = $contact['types'] ?? [];
                foreach ($types as $type) {
                    //$log->appendLog("Entrando al case client del switch: " . json_encode($type));
                    if (trim(strtolower($type['name'])) == 'whatsapp') {
                        return true;
                    }
                }
                return false;
            }
            case 'service': {

                $types = $contact['types'] ?? [];
                foreach ($types as $type) {
                    //$log->appendLog("Entrando al case client del switch: " . json_encode($type));
                    if (trim(strtolower($type['name'])) == 'whatsapp') {
                        return true;
                    }
                }
                return false;
            }
            default:
                return $contact['isContact'] ?? false;
        }
    }
}
