<?php

include_once "admin.inc.php";

$UI_CONFIG = new $uiconfig_name('admin', 'export_netcat_users');

$module_object = new DashaMail($module_login, $module_password);

$connection_test = $module_object->test_connection();

if (!$connection_test) {
  header("Location: admin.php");
  die();
}

$bases_list = $module_object->get_bases_list();

//
//  Получаем список пользователей
//

$users_list = $db->get_results("SELECT * FROM User WHERE Email is not NULL AND Email != ''");

$user_table_fields_list_db = $db->get_results("SELECT Field_Name, Description FROM Field WHERE System_Table_ID = 3");

$user_table_fields_list_excludes = array(
  "Email"
);
$user_table_fields_list = array();

if (count($user_table_fields_list_db))
  foreach ($user_table_fields_list_db as $user_table_fields_list_db_row) {
    if (!in_array($user_table_fields_list_db_row->Field_Name, $user_table_fields_list_excludes))
      $user_table_fields_list[$user_table_fields_list_db_row->Field_Name] = $user_table_fields_list_db_row->Description;
  }

//
//  Получаем список групп пользователей
//

$permission_groups_list = $db->get_results("SELECT `PermissionGroup_ID`, `PermissionGroup_Name` FROM `PermissionGroup`");

//
//  Получаем список сайтов
//

$catalogues_list = $db->get_results("SELECT Catalogue_Name, Catalogue_ID FROM Catalogue");

//
//  Экспорт данных при отправки формы
//

if ($_POST) {
  if ($_POST['next_step']) {
    $base = (array) $module_object->get_bases_list($_POST["export_to_base_id"]);
    $base = (array) $base[0];

    $fields = [];
    foreach ($base as $field_name => $field) {
      if (strripos($field_name, 'merge_') !== false) {
        if (is_string($field)) {
          $field = unserialize($field);
          if ($field) $fields[] = $field;
        }
      }
    }

    $step = $_POST['next_step'];
  }

  if ($step == 'submit') {
    $export_data = array();

    if (count($users_list))
      foreach ($users_list as $users_list_row) {
        if (!$_POST["permission_group_id"] || ($_POST["permission_group_id"] == $users_list_row->PermissionGroup_ID))
          if (!$_POST["catalogue_id"] || ($_POST["catalogue_id"] == $users_list_row->Catalogue_ID))
            if (!$_POST["from_date"] || ($_POST["from_date"] <= date("Y-m-d", strtotime($users_list_row->Created))))
              if (!$_POST["to_date"] || ($_POST["to_date"] >= date("Y-m-d", strtotime($users_list_row->Created)))) {
                $export_row = array("email" => $users_list_row->Email);

                for ($counter = 1; $counter <= 5; $counter++) {
                  if ($_POST["additional_field_" . $counter]) {
                    $export_row["merge_" . $counter] = $users_list_row->{$_POST["additional_field_" . $counter]};
                  }
                }

                $export_data[] = $export_row;

              }
      }

    $base_id = $_POST["export_to_base_id"];
    $update_if_exists = (bool) $_POST["update_if_exists"];

    $result_text = array($module_object->export_data($export_data, $base_id, $update_if_exists));

    unset($step);
  }

}

BeginHtml();
?>
  <link href="css/style.css" rel="stylesheet"/>
  <link href="libs/goodyear/css/jquery-goodyear.min.css" rel="stylesheet"/>
  <script src="script/jquery-1.11.2.min.js"></script>
  <script src="libs/goodyear/js/moment-with-langs.min.js"></script>
  <script src="libs/goodyear/js/jquery-mousewheel-3.1.11.min.js"></script>
  <script src="libs/goodyear/js/jquery-goodyear.min.js"></script>
  <script src="script/dashamail.js"></script>
  <div class="export">
    <?
    if (!$bases_list || !count($bases_list)) {
      ?>
      <div class="nc-alert nc--red">
        <i class="nc-icon-l nc--status-error"></i>
        Для экспорта подписчиков требуется создать хотя бы одну адресную базу.
      </div>
      <?
    }elseif (!count($users_list)) {
      ?>
      <div class="nc-alert nc--red">
        <i class="nc-icon-l nc--status-error"></i>
        Не найдено ни одного подписчика для экспорта.
      </div>
      <?
    }else {

      if ($result_text)
        foreach ($result_text as $result_text_row) {
          if ($result_text_row->success) {
            ?>
            <div class="connectionTestInformation-success nc-alert nc--green">
              <i class="nc-icon-l nc--status-success"></i>
              <? echo $result_text_row->data; ?>
            </div>
            <?
          }else {
            ?>
            <div class="connectionTestInformation-success nc-alert nc--red">
              <i class="nc-icon-l nc--status-error"></i>
              <? echo $result_text_row->error_text; ?>
            </div>
            <?
          }
        }

      ?>
      <form id="ExportUsers" method="post">
        <? if (!$step) { ?>
          <?php

          $UI_CONFIG->actionButtons[] = array(
            "id" => "submit",
            "caption" => "Далее",
            "action" => "mainView.submitIframeForm('ExportUsers')",
            "align" => "left"
          );

          ?>
          <input type="hidden" name="next_step" value="2">
          <div class="export-tableTitle">
            Настройки экспорта
          </div>
          <div class="export-table">
            <div class="export-table-field">
              <div class="export-table-field-label">
                В какую базу экспортировать
              </div>
              <div class="export-table-field-to">
              </div>
              <div class="export-table-field-value">
                <select name="export_to_base_id">
                  <?
                  foreach ($bases_list as $bases_list_row) {
                    ?>
                    <option value="<? echo $bases_list_row->id; ?>" <? echo(($_POST ? $_POST["export_to_base_id"] : $base_ids_list_row) == $bases_list_row->id ? "selected='selected'" : NULL); ?>><? echo $bases_list_row->name; ?></option>
                    <?
                  }
                  ?>
                </select>
              </div>
            </div>
            <div class="export-table-field">
              <div class="export-table-field-label">
                Обновлять данные, если подписчик уже в базе
              </div>
              <div class="export-table-field-to">
              </div>
              <div class="export-table-field-value">
                <input type="checkbox" <? echo($_POST["update_if_exists"] ? "checked='checked'" : NULL); ?> value="1" name="update_if_exists"/>
              </div>
            </div>
          </div>
        <? } ?>
        <? if ($step == 2) { ?>

          <?php

          $UI_CONFIG->actionButtons[] = array(
            "id" => "submit",
            "caption" => "Экспортировать пользователей",
            "action" => "mainView.submitIframeForm('ExportUsers')",
            "align" => "left"
          );

          ?>

          <input type="hidden" name="export_to_base_id" value="<?= $_POST['export_to_base_id'] ?>">
          <input type="hidden" name="next_step" value="submit">
          <div class="export-tableTitle">
            Фильтры пользователей
          </div>
          <div class="export-table">
            <div class="export-table-field">
              <div class="export-table-field-label">
                Группа пользователей
              </div>
              <div class="export-table-field-to">
              </div>
              <div class="export-table-field-value">
                <select name="permission_group_id">
                  <option value="0">Все группы</option>
                  <?
                  foreach ($permission_groups_list as $permission_groups_list_row) {
                    ?>
                    <option <? echo($_POST["permission_group_id"] == $permission_groups_list_row->PermissionGroup_ID ? "selected='selected'" : NULL); ?> value="<? echo $permission_groups_list_row->PermissionGroup_ID; ?>">
                      <? echo $permission_groups_list_row->PermissionGroup_Name; ?>
                    </option>
                    <?
                  }
                  ?>
                </select>
              </div>
            </div>
            <div class="export-table-field">
              <div class="export-table-field-label">
                ID сайта Netcat
              </div>
              <div class="export-table-field-to">
              </div>
              <div class="export-table-field-value">
                <select name="catalogue_id">
                  <option value="0">Все сайты</option>
                  <?
                  foreach ($catalogues_list as $catalogues_list_row) {
                    ?>
                    <option <? echo($_POST["catalogue_id"] == $catalogues_list_row->Catalogue_ID ? "selected='selected'" : NULL); ?> value="<? echo $catalogues_list_row->Catalogue_ID; ?>">
                      <? echo $catalogues_list_row->Catalogue_Name; ?>
                    </option>
                    <?
                  }
                  ?>
                </select>
              </div>
            </div>
            <div class="export-table-field">
              <div class="export-table-field-label">
                Дата добавления, от
              </div>
              <div class="export-table-field-to">
              </div>
              <div class="export-table-field-value">
                <input name="from_date" value="<? echo $_POST["from_date"]; ?>" data-goodyear-visible-format="DD MMMM YYYY" data-goodyear-format="YYYY-MM-DD" class="goodyear"/>
              </div>
            </div>
            <div class="export-table-field">
              <div class="export-table-field-label">
                Дата добавления, до
              </div>
              <div class="export-table-field-to">
              </div>
              <div class="export-table-field-value">
                <input name="to_date" value="<? echo $_POST["to_date"]; ?>" data-goodyear-visible-format="DD MMMM YYYY" data-goodyear-format="YYYY-MM-DD" class="goodyear"/>
              </div>
            </div>
          </div>
          <div class="export-tableTitle">
            Соответствие полей удаленной адресной базы полям пользователя Netcat
          </div>
          <div class="export-table">
            <? $counter = 1;
            foreach ($fields as $field) { ?>
              <div class="export-table-field">
                <div class="export-table-field-label">
                  <?= $field['title'] ?>
                </div>
                <div class="export-table-field-to">
                </div>
                <div class="export-table-field-value">
                  <select name="additional_field_<? echo $counter; ?>">
                    <option value="">Не использовать</option>
                    <?
                    foreach ($user_table_fields_list as $user_table_fields_list_key => $user_table_fields_list_description) {
                      ?>
                      <option <? echo($_POST["additional_field_" . $counter] == $user_table_fields_list_key ? "selected='selected'" : NULL); ?> value="<? echo $user_table_fields_list_key; ?>">
                        <? echo $user_table_fields_list_description; ?>
                      </option>
                      <?
                    }
                    ?>
                  </select>
                </div>
              </div>
              <? $counter++;
            } ?>
          </div>
        <? } ?>
      </form>
      <?
    }
    ?>
  </div>
<?
EndHtml();









