<?php

namespace Simulador\Moskit;

use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\GuzzleException;
use Simulador\Tables\Vendedor;
use Throwable;

class Contact
{
  /**
   * @param array $dados
   * @param Vendedor $vendedor
   * @return array|bool
   */
  public static function post(array $dados, Vendedor $vendedor)
  {
    $contact = [
      'name' => $dados['nome'],
      'createdBy' => [
        'id' => (int) $vendedor->usuario,
      ],
      'responsible' => [
        'id' => (int) $vendedor->usuario,
      ],
      'emails' => [[
        'address' => $dados['email'],
      ]],
      'phones' => [[
        'number' => $dados['ddd'] . $dados['telefone'],
      ]],
    ];

    try {
      $client = MoskitAPI::getClient($vendedor->api_key);
      $response = $client->post('contacts/', [
        'json' => $contact,
      ]);
      $body = $response->getBody();
      $content = json_decode($body, true);

    } catch (ClientException $e) {
      error_log($e->getResponse()->getBody()->getContents());
      return false;
    } catch (Throwable $e) {
      error_log($e->getMessage());
      return false;
    }

    return $content;
  }

}
