// Файл: product_page_agreements.js
$(() => {
  // Проверяем, что мы на нужной странице
  if (!checkTruePage({ 
    notMode: 1, 
    strict: 0, 
    pages: [
      '/sales/control/userProduct/update/id'
    ]
  })) {
    
    // Получаем ID пользователя
    let userId = getUserId();
    
    if (!userId) {
      console.log('Не удалось получить ID пользователя');
      return;
    }
    
    // Находим все ссылки на сделки (заказы)
    $('.panel-default tr td:has(a[href*="deal"]) a').each((i, ord) => {
      let orderId = $(ord).attr('href').split('/').pop();
      
      if (!orderId) return;
      
      // Получаем информацию о подтверждениях для этого заказа
      $.get(`/chtm/checkPurposal~check-confirmations?userId=${encodeURIComponent(userId)}&orderId=${encodeURIComponent(orderId)}`, function(confirmations) {
        
        if (confirmations && confirmations.id) {
          // Получаем настройки предложения, чтобы узнать названия соглашений
          $.get(`/chtm/checkPurposal~get-by-offer-id?offerId=${encodeURIComponent(confirmations.offer_id)}`, function(offerSettings) {
            
            const formatDate = (dateString) => {
              const date = new Date(dateString);
              return date.toLocaleTimeString('ru-RU', { 
                hour: '2-digit', 
                minute: '2-digit' 
              }) + ' ' + date.toLocaleDateString('ru-RU', {
                day: '2-digit',
                month: '2-digit',
                year: 'numeric'
              }).replace(/\//g, '.');
            };
            
            let html = '';
            
            // Создаем массив с соглашениями для удобства
            let agreements = [
              {
                title: offerSettings?.agreement1_title || 'Соглашение 1',
                confirmed: confirmations.agreement1_confirmed === 'true',
                html: confirmations.agreement1_html || '',
                exists: offerSettings?.agreement1_title || offerSettings?.agreement1_text
              },
              {
                title: offerSettings?.agreement2_title || 'Соглашение 2',
                confirmed: confirmations.agreement2_confirmed === 'true',
                html: confirmations.agreement2_html || '',
                exists: offerSettings?.agreement2_title || offerSettings?.agreement2_text
              },
              {
                title: offerSettings?.agreement3_title || 'Соглашение 3',
                confirmed: confirmations.agreement3_confirmed === 'true',
                html: confirmations.agreement3_html || '',
                exists: offerSettings?.agreement3_title || offerSettings?.agreement3_text
              }
            ];
            
            // Фильтруем только существующие соглашения
            agreements = agreements.filter(a => a.exists);
            
            // Если есть настройки предложения, используем названия из них
            if (offerSettings) {
              agreements.forEach((agreement, index) => {
                let confirmedText = agreement.confirmed ? 'Да' : 'Нет';
                let valueHtml = `${confirmedText} (${formatDate(confirmations.confirmed_at)})`;
                
                // Если есть HTML, добавляем знак вопроса рядом со значением
                if (agreement.html && agreement.html.trim() !== '') {
                  // Экранируем HTML для безопасного хранения в data-атрибуте
                  let escapedHtml = agreement.html
                    .replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;')
                    .replace(/"/g, '&quot;')
                    .replace(/'/g, '&#039;');
                  
                  valueHtml += ` <a href="#" class="agreement-view-link" data-title="${agreement.title}" data-html="${escapedHtml}" title="Посмотреть текст соглашения"><span class="glyphicon glyphicon-question-sign" style="color: #337ab7; text-decoration: none; font-size: 16px; margin-left: 5px;"></span></a>`;
                }
                
                html += `
                  <tr>
                    <td class="key">${agreement.title}</td>
                    <td class="value">${valueHtml}</td>
                  </tr>
                `;
              });
            } else {
              // Если настроек нет, используем стандартные названия
              let defaultAgreements = [
                {
                  title: 'Согласие с офертой',
                  confirmed: confirmations.agreement1_confirmed === 'true',
                  html: confirmations.agreement1_html || ''
                },
                {
                  title: 'Согласие с обработкой данных',
                  confirmed: confirmations.agreement2_confirmed === 'true',
                  html: confirmations.agreement2_html || ''
                },
                {
                  title: 'Согласие с политикой конфиденциальности',
                  confirmed: confirmations.agreement3_confirmed === 'true',
                  html: confirmations.agreement3_html || ''
                }
              ];
              
              defaultAgreements.forEach(agreement => {
                let confirmedText = agreement.confirmed ? 'Да' : 'Нет';
                let valueHtml = `${confirmedText} (${formatDate(confirmations.confirmed_at)})`;
                
                // Если есть HTML, добавляем знак вопроса рядом со значением
                if (agreement.html && agreement.html.trim() !== '') {
                  // Экранируем HTML для безопасного хранения в data-атрибуте
                  let escapedHtml = agreement.html
                    .replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;')
                    .replace(/"/g, '&quot;')
                    .replace(/'/g, '&#039;');
                  
                  valueHtml += ` <a href="#" class="agreement-view-link" data-title="${agreement.title}" data-html="${escapedHtml}" title="Посмотреть текст соглашения"><span class="glyphicon glyphicon-question-sign" style="color: #337ab7; text-decoration: none; font-size: 16px; margin-left: 5px;"></span></a>`;
                }
                
                html += `
                  <tr>
                    <td class="key">${agreement.title}</td>
                    <td class="value">${valueHtml}</td>
                  </tr>
                `;
              });
            }
            
            // Добавляем информацию в таблицу
            if (html) {
              $('.key-value-table tbody').append(html);
            }
            
          }).fail(function() {
            // Если не удалось загрузить настройки, показываем стандартные названия
            const formatDate = (dateString) => {
              const date = new Date(dateString);
              return date.toLocaleTimeString('ru-RU', { 
                hour: '2-digit', 
                minute: '2-digit' 
              }) + ' ' + date.toLocaleDateString('ru-RU', {
                day: '2-digit',
                month: '2-digit',
                year: 'numeric'
              }).replace(/\//g, '.');
            };
            
            let defaultAgreements = [
              {
                title: 'Согласие с офертой',
                confirmed: confirmations.agreement1_confirmed === 'true',
                html: confirmations.agreement1_html || ''
              },
              {
                title: 'Согласие с обработкой данных',
                confirmed: confirmations.agreement2_confirmed === 'true',
                html: confirmations.agreement2_html || ''
              },
              {
                title: 'Согласие с политикой конфиденциальности',
                confirmed: confirmations.agreement3_confirmed === 'true',
                html: confirmations.agreement3_html || ''
              }
            ];
            
            let html = '';
            defaultAgreements.forEach(agreement => {
              let confirmedText = agreement.confirmed ? 'Да' : 'Нет';
              let valueHtml = `${confirmedText} (${formatDate(confirmations.confirmed_at)})`;
              
              // Если есть HTML, добавляем знак вопроса рядом со значением
              if (agreement.html && agreement.html.trim() !== '') {
                // Экранируем HTML для безопасного хранения в data-атрибуте
                let escapedHtml = agreement.html
                  .replace(/&/g, '&amp;')
                  .replace(/</g, '&lt;')
                  .replace(/>/g, '&gt;')
                  .replace(/"/g, '&quot;')
                  .replace(/'/g, '&#039;');
                
                valueHtml += ` <a href="#" class="agreement-view-link" data-title="${agreement.title}" data-html="${escapedHtml}" title="Посмотреть текст соглашения"><span class="glyphicon glyphicon-question-sign" style="color: #337ab7; text-decoration: none; font-size: 16px; margin-left: 5px;"></span></a>`;
              }
              
              html += `
                <tr>
                  <td class="key">${agreement.title}</td>
                  <td class="value">${valueHtml}</td>
                </tr>
              `;
            });
            
            $('.key-value-table tbody').append(html);
          });
          
        } else {
          // Если подтверждений нет, показываем сообщение
          $('.key-value-table tbody').append(`
            <tr>
              <td class="key">Согласия</td>
              <td class="value">Нет информации о согласиях</td>
            </tr>
          `);
        }
      }).fail(function() {
        // В случае ошибки тоже показываем сообщение
        $('.key-value-table tbody').append(`
          <tr>
            <td class="key">Согласия</td>
            <td class="value">Не удалось загрузить информацию</td>
          </tr>
        `);
      });
    });
    
    // Обработчик клика на знак вопроса
    $(document).on('click', '.agreement-view-link', function(e) {
      e.preventDefault();
      
      let title = $(this).data('title');
      let html = $(this).data('html');
      
      if (html) {
        showAgreementHtml(title, html);
      }
    });
  }
  
  // Функция получения ID пользователя
  function getUserId() {
    if (typeof accountUserId !== 'undefined') {
      return accountUserId;
    }
    if (typeof window.accountUserId !== 'undefined') {
      return window.accountUserId;
    }
    if (typeof user_id !== 'undefined') {
      return user_id;
    }
    
    let userIdElement = $('input[name="user_id"], .user-id, [data-user-id]');
    if (userIdElement.length) {
      return userIdElement.val() || userIdElement.data('user-id') || userIdElement.text();
    }
    
    return null;
  }
  
  // Функция проверки страницы
  function checkTruePage(opt) {
    let i = false; 
    opt.pages.forEach(el => {
      if (opt.strict) {
        if (window.location.href == el) i = true;
      } else if (window.location.href.indexOf(el) > -1) i = true;
    });
    return opt.notMode ? !i : i;
  }
  
  // Функция для создания модального окна с HTML соглашения
  function showAgreementHtml(title, html) {
    // Создаем уникальный ID для модального окна
    let modalId = 'agreementModal_' + Date.now();
    
    // Декодируем HTML обратно
    let decodedHtml = html
      .replace(/&amp;/g, '&')
      .replace(/&lt;/g, '<')
      .replace(/&gt;/g, '>')
      .replace(/&quot;/g, '"')
      .replace(/&#039;/g, "'");
    
    // Создаем HTML модального окна с фиксированным заголовком
    let modalHtml = `
      <div class="modal fade" id="${modalId}" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 class="modal-title">Текст соглашения</h4>
            </div>
            <div class="modal-body" style="max-height: 70vh; overflow-y: auto;">
              ${decodedHtml}
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Закрыть</button>
            </div>
          </div>
        </div>
      </div>
    `;
    
    // Добавляем модальное окно в DOM
    $('body').append(modalHtml);
    
    // Показываем модальное окно
    $(`#${modalId}`).modal('show');
    
    // Удаляем из DOM после закрытия
    $(`#${modalId}`).on('hidden.bs.modal', function() {
      $(this).remove();
    });
  }
});