<?php

include_once "admin.inc.php";

$UI_CONFIG = new $uiconfig_name('admin', 'export_netshop_module_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();

//
//  Наличие модуля рассылок
//

$module_exists = $db->get_var("SELECT Module_ID FROM `Module` WHERE `Keyword` = 'netshop'");

$module_table = $db->get_var("SELECT Value FROM `Settings` WHERE `Key` = 'OrderComponentID' AND `Module` = 'Netshop'");

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

$subscribers_list = 
$db->get_results("
SELECT
*
FROM
Message".$module_table."
WHERE
Email is not NULL AND
Email != ''
");

//
//  Статусы заказов
//

$statuses_list = 
$db->get_results("
SELECT
ShopOrderStatus_ID,
ShopOrderStatus_Name
FROM
Classificator_ShopOrderStatus
");

$statuses_list_tmp = array();

if (count($statuses_list))
foreach ($statuses_list as $statuses_list_row)
{
    $statuses_list_tmp[$statuses_list_row->ShopOrderStatus_ID] = $statuses_list_row->ShopOrderStatus_Name;
}

$statuses_list = $statuses_list_tmp;
unset($statuses_list_tmp);

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

if ($_POST)
{
    $export_data = array();
    
    if (count($subscribers_list))
    foreach ($subscribers_list as $subscribers_list_row)
    {
        if (!$_POST["from_date"] || ($_POST["from_date"] <= date("Y-m-d", strtotime($subscribers_list_row->Created))))
        if (!$_POST["to_date"] || ($_POST["to_date"] >= date("Y-m-d", strtotime($subscribers_list_row->Created))))
        {
            $export_row = array("email" => $subscribers_list_row->Email);
            
            for ($counter = 1; $counter <= 5; $counter++)
            {
                if ($_POST["additional_field_".$counter])
                {
                    $export_row["merge_".$counter] = $subscribers_list_row->{$_POST["additional_field_".$counter]};
                    
                    if ($_POST["additional_field_".$counter] == "Status")
                    $export_row["merge_".$counter] = $statuses_list[$subscribers_list_row->{$_POST["additional_field_".$counter]}];
                    
                    if ($_POST["additional_field_".$counter] == "Created")
                    $export_row["merge_".$counter] = date("d.m.Y", strtotime($export_row["merge_".$counter]));   
                       
                    if (!$export_row["merge_".$counter])
                    $export_row["merge_".$counter] = "&nbsp;";
                }
            }
            
            $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));
        
    
}

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 (!$module_exists)
    {
        ?>
        <div class="nc-alert nc--red">
             <i class="nc-icon-l nc--status-error"></i>
             Модуль "Netshop" не установлен.
        </div>
        <?
    } elseif (!$module_table){
        ?>
        <div class="nc-alert nc--red">
             <i class="nc-icon-l nc--status-error"></i>
             Модуль "Netshop" не используется.
        </div>
        <?
    } elseif (!$bases_list || !count($bases_list))
    {
        ?>
        <div class="nc-alert nc--red">
             <i class="nc-icon-l nc--status-error"></i>
             Для экспорта подписчиков требуется создать хотя бы одну адресную базу.
        </div>
        <?
    } elseif (!count($subscribers_list))
    {
        ?>
        <div class="nc-alert nc--red">
             <i class="nc-icon-l nc--status-error"></i>
             Не найдено ни одного подписчика для экспорта.
        </div>
        <?
    } else {
        $UI_CONFIG->actionButtons[] = array(
            "id"      => "submit",
            "caption" => "Экспортировать пользователей",
            "action"  => "mainView.submitIframeForm('ExportNetshopUsers')",
            "align"   => "left"
        );
        
        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="ExportNetshopUsers" method="post">
            <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>
            <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">
                        <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">
                <?
                for ($counter = 1; $counter <=5; $counter++)
                {
                    ?>
                    <div class="export-table-field">
                        <div class="export-table-field-label">
                            Дополнительное поле <? echo $counter; ?>
                        </div>   
                        <div class="export-table-field-to">
                        </div> 
                        <div class="export-table-field-value">
                            <select name="additional_field_<? echo $counter; ?>">
                                <option value="">Не использовать</option>
                                <option <? echo ($_POST["additional_field_".$counter] == "ContactName" ? "selected='selected'" : NULL); ?> value='ContactName'>Контактное имя</option>
                                <option <? echo ($_POST["additional_field_".$counter] == "Phone" ? "selected='selected'" : NULL); ?> value='Phone'>Телефон</option>
                                <option <? echo ($_POST["additional_field_".$counter] == "TotalPrice" ? "selected='selected'" : NULL); ?> value='TotalPrice'>Сумма заказа</option>
                                <option <? echo ($_POST["additional_field_".$counter] == "Comments" ? "selected='selected'" : NULL); ?> value='Comments'>Комментарий</option>
                                <option <? echo ($_POST["additional_field_".$counter] == "Status" ? "selected='selected'" : NULL); ?> value='Status'>Статус</option>
                                <option <? echo ($_POST["additional_field_".$counter] == "Zip" ? "selected='selected'" : NULL); ?> value='Zip'>Индекс</option>
                                <option <? echo ($_POST["additional_field_".$counter] == "Created" ? "selected='selected'" : NULL); ?> value='Created'>Дата регистрации заказа</option>
                            </select>
                        </div>    
                    </div>
                    <?
                }
                ?>
            </div>
        </form>
        <?
    }
    ?>
</div>
<?
EndHtml();









