<?php

class DashaMail {

  const EVENT_PRODUCT_ADD_TO_CART = 'dashamailProductAddToCart';

  private $login;
  private $password;

  protected $api_id;
  protected $user_field_email;
  protected $user_fields;
  protected $nc_core;

  public $event_user_leave;
  public $event_cart_leave;
  public $time_cart_leave;
  public $order_class_id;
  public $user_id;

  public $last_error = false;

  //
  // API url
  //
  private $api_url = 'https://api.dashamail.com/';

  public function __construct ($login = null, $password = null) {

    global $AUTH_USER_ID;

    $this->nc_core = nc_Core::get_object();
    $this->nc_core->event->register_event(self::EVENT_PRODUCT_ADD_TO_CART, "Продукт добавлен в корзину");

    $this->nc_core->event->bind($this, array('addUser' => 'event_add_user'));
    $this->nc_core->event->bind($this, array('netshopOrderCreated' => 'event_purchase_finish'));
    $this->nc_core->event->bind($this, array('addMessage' => 'event_add_order'));
    // В событии не передается пользователь
    //$this->nc_core->event->bind($this, array('netshopCartChanged' => 'event_add_to_cart'));
    $this->nc_core->event->bind($this, array(self::EVENT_PRODUCT_ADD_TO_CART => 'event_product_add_to_cart'));


    $MODULE_VARS = $this->nc_core->modules->get_module_vars()['dashamail'];
    if (!$login) $login = $MODULE_VARS['LOGIN'];
    if (!$password) $password = $MODULE_VARS['PASSWORD'];
    $this->api_id = $MODULE_VARS['API_ID'];
    $this->user_field_email = $MODULE_VARS['USER_FIELD_EMAIL'];
    $this->order_class_id = $MODULE_VARS['COMPONENT_ORDER'];
    $this->event_user_leave = $MODULE_VARS['EVENT_USER_LEAVE'];
    $this->event_cart_leave = $MODULE_VARS['EVENT_CART_LEAVE'];
    $this->time_cart_leave = $MODULE_VARS['TIME_CART_LEAVE'];
    $this->user_id = $AUTH_USER_ID;

    $user_fields = nc_core()->db->get_results("SELECT * FROM `User`", ARRAY_A);

    $this->user_fields = array();
    foreach ($user_fields as $user_field) {
      $this->user_fields[] = $user_field['Field_Name'];
    }

    if (!$login || !$password)
      return $this->error("inner", "Не указан логин или пароль");

    $this->login = $login;
    $this->password = $password;


    return $this;
  }

  //
  //  Проверка соединения
  //
  public function test_connection () {
    $lists_list = $this->api_call("lists.get");

    if ($lists_list->success)
      $result = true;
    else
      $result = false;

    return $result;
  }

  //
  //  Получение списка баз данных
  //
  /**
   * Получение списка баз данных
   * @param int $list_id
   * @return bool|object
   */
  public function get_bases_list ($list_id = 0) {
    $lists_list = $this->api_call("lists.get", array('list_id' => $list_id));

    if ($lists_list->success) {
      if (isset($lists_list->data->row->id))
        return (object) array($lists_list->data->row);
      else {
        $result = $lists_list->data->row;

        usort($result, function ($a, $b) {
          return $a->id > $b->id;
        });

        return $result;
      }
    }else {
      return false;
    }
  }

  //
  //  Экспорт данных
  //

  public function export_data ($data, $base_id, $update = true) {
    global $DOMAIN_NAME, $SUB_FOLDER, $HTTP_ROOT_PATH;

    if (!count($data))
      return $this->error("inner", "Нет данных для экспорта");

    $temp_file_name = "tmp/" . md5(microtime()) . ".csv";

    $file_handler = fopen($temp_file_name, "w");

    foreach ($data as $data_row) {
      fputcsv($file_handler, $data_row, ",");
    }

    fclose($file_handler);

    $file_path = 'http://' . $DOMAIN_NAME . $SUB_FOLDER . $HTTP_ROOT_PATH . 'modules/dashamail/' . $temp_file_name;

    $params = array(
      'list_id' => $base_id,
      'file' => $file_path,
      'email' => 0,
      'merge_1' => 1,
      'merge_2' => 2,
      'merge_3' => 3,
      'merge_4' => 4,
      'merge_5' => 5,
      'type' => 'csv',
      'sheet_index' => 1
    );

    if ($update) {
      $params["update"] = "true";
    }

    $result = $this->api_call("lists.upload", $params);

    if ($result->success == false)
      return $this->error("inner", $result->error_text);
    else {
      if (count($data) < 3000)
        return $this->success($result->data->text);
      else
        return $this->success("Данные будут обработаны в течение 10 минут.");
    }
  }

  //
  //  Возврат ошибки
  //
  private function error ($error_code, $error_text) {
    $this->last_error_text = $error_text;
    $this->last_error_code = (int) $error_code;

    return (object) array("success" => false, "error_code" => (int) $error_code, "error_text" => $error_text);
  }

  //
  //  Успешное выполнение запроса
  //
  private function success ($data) {
    return (object) array("success" => true, "data" => $data);
  }

  //
  //  Выполнение запроса к api
  //

  public function api_call ($method = null, $data = array()) {

    if (!is_string($method))
      return $this->error("inner", "Не указан метод API");

    $authorization_data = array('username' => $this->login, 'password' => $this->password);
    $query_data = http_build_query(array_merge($authorization_data, $data), '', '&');

    $url = $this->api_url . '?cms=netcat&method=' . $method . '&' . $query_data . '&format=xml';

    $api_result = file_get_contents($url);

    if (!$api_result) {
      return $this->error("inner", "Не удалось установить подключение к серверу");
    }else {
      $xml_parsed = json_decode(json_encode(simplexml_load_string($api_result)));

      if (!$xml_parsed)
        return $this->error("inner", "Не удалось установить подключение к серверу");
    }

    if ((int) $xml_parsed->msg->err_code == 0) {
      return $this->success($xml_parsed->data);
    }else {
      return $this->error($xml_parsed->msg->err_code, $xml_parsed->msg->text);
    }
  }


  /**
   *
   */
  public function get_event_register_url () {
    return nc_module_path('dashamail') . "actions/event_register.php";
  }

  /**
   *
   */
  public function get_add_to_cart_url () {
    return nc_module_path('dashamail') . "actions/cart.php";
  }


  /**
   * Отправить событие
   * @param null $event_name
   * @param null $user_id
   * @return DashaMail|object
   */
  public function event_send ($event_name = null, $user_id = null) {
    if (!$user_id) $user_id = $this->user_id;

    if (!$event_name) return $this->error("inner", "Не указано название события");
    if (!$user_id) return $this->error("inner", "Не указан пользователь");
    if (!$this->api_id) return $this->error("inner", "Не указано id приложения");
    if (!$this->user_field_email) return $this->error("inner", "Не указано поле Email пользователя");


    // Параметры приложения
    $init_params = array(
      'appId' => $this->api_id,
      'username' => $this->login
    );

    // Параметры пользователя
    $user = nc_core()->user->get_by_id($user_id);
    $user_params = array(
      'email' => $user[$this->user_field_email],
    );
    $fields = $this->user_fields;
    if (!empty($fields)) {
      foreach ($fields as $field) {
        $user_params[$field] = urlencode($user[$field]);
      }
    }

    // Параметры события
    $event_params = array(
      'name' => $event_name
    );


    $params = array(
      array('_init', $init_params),
      array('_user', $user_params),
      array('_event', $event_params)
    );


    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, 'http://gmforms.com/track.php?cms=netcat&params=' . json_encode($params));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_exec($curl);
    curl_close($curl);

    $this->success('Событие отправлено');
    return $this;
  }

  /**
   * Посетил сайт
   * @param $user_id
   * @return DashaMail
   */
  public function event_visit ($user_id = null) {
    if (!$user_id) $user_id = $this->user_id;
    $this->event_send('visit', $user_id);

    return $this;
  }

  /**
   * Начал оформление заказа
   * @param $user_id
   * @return DashaMail
   */
  public function event_purchase_start ($user_id = null) {
    if (!$user_id) $user_id = $this->user_id;
    $this->event_send('purchase_start', $user_id);

    return $this;
  }

  /**
   * Завершил оформление заказа
   * @param $order
   * @param $coupon_codes
   * @return DashaMail
   */
  public function event_purchase_finish ($order, $coupon_codes) {
    $user_id = $order['User_ID'];
    $this->event_send('purchase_finish', $user_id);

    return $this;
  }

  public function event_add_order ($site_id, $subdivision_id, $infoblock_id, $component_id, $object_id) {
    $order = $this->nc_core->message->get_by_id($component_id, $object_id);
    $user_id = $order['User_ID'];

    if ($component_id == $this->order_class_id and $user_id)
      $this->event_send('purchase_finish', $user_id);

    return $this;
  }

  /**
   * Регистрация
   * @param $user_id
   * @return DashaMail
   */
  public function event_add_user ($user_id = null) {
    if (!$user_id) $user_id = $this->user_id;
    $this->event_send('register', $user_id);

    return $this;
  }

  /**
   * Добавление продукта в корзину
   * @param $user_id
   * @return DashaMail
   */
  public function event_product_add_to_cart ($user_id = null) {
    if (!$user_id) $user_id = $this->user_id;
    $this->event_send('add_to_cart', $user_id);

    return $this;
  }

}
