<?php

namespace Simulador\Utils;

use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
use FacebookAds\Object\ServerSide\Event;
use FacebookAds\Object\ServerSide\EventRequest;
use FacebookAds\Object\ServerSide\UserData;

class Facebook
{

  /**
   * @param string[] $data
   * @return string[]
   */
  public static function pageView($data)
  {
    $access_token = 'EAACUb6dJAiUBADwJZCCzsUJAjRNOTk9LkzVB1buERslQoThbzyvqVom2n2kfj500dObxrgnufF4nAqnMLZBpLDtvr4IjQisQ5LXMQZAp3IAQ2pYeCMlWYoLoNMw81KYavMDErEmPUGfCbwAzgRWB6cVlFzB4yMXHQhpUjBntdRH1matfGGY';
    $pixel_id = '1719301591615148';

    $api = Api::init(null, null, $access_token, false);
    $api->setLogger(new CurlLogger(fopen('facebook.txt', 'wb')));

    $user_data = new UserData();
    $user_data->setEmail($data['email']);
    $user_data->setPhone($data['ddd'].$data['telefone']);
    $user_data->setClientIpAddress($_SERVER['REMOTE_ADDR']);
    $user_data->setClientUserAgent($_SERVER['HTTP_USER_AGENT']);
    if (isset($_COOKIE['_fbp'])) {
      $user_data->setFbp($_COOKIE['_fbp']);
    }

    $source_url = 'https://simulador.proteautobrasil.com.br/detalhes/';

    if ($data['valor_fipe'] > 100000) {
      $source_url .= 'acima100';
    } else {
      $source_url .= 'abaixo100';
    }

    $event = (new Event())
      ->setEventId($data['id'])
      ->setEventName('Lead')
      ->setEventTime(time())
      ->setEventSourceUrl($source_url)
      ->setUserData($user_data);

    $request = (new EventRequest($pixel_id))
//      ->setTestEventCode('TEST1297')
      ->setEvents([$event]);

    $response = $request->execute();

    return $response->getMessages();
  }
}
