<?php
$account=is_array($email_account??null)?$email_account:array();$providers=is_array($email_providers??null)?$email_providers:array();$enabled=($account['status']??'')==='active';$providerId=(string)($account['provider_id']??'manual');$hasAccount=!empty($account);$manualVisible=$hasAccount&&$providerId==='manual';$providerJson=json_encode($providers,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);$transport=(string)($account['outbound_transport']??'auto');$e=static function($value){return htmlspecialchars((string)$value,ENT_QUOTES,'UTF-8');};
$savedDiagnostics=json_decode((string)($account['diagnostics_json']??''),true);if(!is_array($savedDiagnostics))$savedDiagnostics=array();
$health=array();foreach(array('inbound','outbound','deliverability') as $healthSection){
  $health[$healthSection]=is_array($savedDiagnostics[$healthSection]??null)?$savedDiagnostics[$healthSection]:array();
  $health[$healthSection]['status']=(string)($account[$healthSection.'_status']??($health[$healthSection]['status']??'not_checked'));
  $health[$healthSection]['code']=(string)($account[$healthSection.'_code']??($health[$healthSection]['code']??''));
  $health[$healthSection]['checked_at']=(string)($account[$healthSection.'_checked_at']??'');
}
?>
<form id="email-panel" class="tab-pane fade<?php echo $integration_tab_active('email')?' show active':''; ?> easychat-email" role="tabpanel" aria-labelledby="email-tab" data-email-form data-has-account="<?php echo $hasAccount?'1':'0'; ?>" data-original-address="<?php echo $e($account['email_address']??''); ?>" autocomplete="off">
  <header class="easychat-email__header"><img src="assets/channels/email.svg" width="44" height="44" alt="" aria-hidden="true"><div><h2 id="email-title" class="h5 fw-bold text-dark mb-1">Почта</h2><p class="text-muted small mb-0">Письма клиентов и ответы операторов — в общем окне EasyChat.</p></div></header>
  <div id="email-status" class="alert d-none" role="status" aria-live="polite" tabindex="-1"></div>
  <input type="hidden" name="nonce" value="<?php echo $e($email_nonce); ?>"><input type="hidden" name="provider_id" value="<?php echo $e($providerId); ?>"><input type="hidden" name="connection_check_id" value="">
  <script type="application/json" data-email-provider-catalog><?php echo str_replace('</','<\/',(string)$providerJson); ?></script>
  <script type="application/json" data-email-health><?php echo json_encode($health,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); ?></script>

  <section class="easychat-email__section" aria-labelledby="email-account-title">
    <div class="easychat-email__section-heading"><div><h3 id="email-account-title" class="h6 fw-semibold mb-1"><?php echo $hasAccount?'Почтовый ящик':'Подключите рабочий ящик'; ?></h3><p class="small text-muted mb-0">Введите адрес — известные настройки заполнятся автоматически.</p></div><div class="form-check form-switch easychat-email__enabled"><input class="form-check-input easychat-switch-lg" type="checkbox" role="switch" id="email-enabled" name="enabled" value="1" <?php echo $enabled?'checked':''; ?>><label class="form-check-label" for="email-enabled">Получать письма</label></div></div>
    <div class="easychat-email__address mt-3"><label class="form-label fw-semibold" for="email-address">Адрес почты</label><input class="form-control form-control-lg" id="email-address" name="email_address" type="email" autocomplete="email" required value="<?php echo $e($account['email_address']??''); ?>" placeholder="support@company.ru" aria-describedby="email-detection"></div>
    <p class="form-text mb-0" id="email-detection" data-email-detection aria-live="polite"><?php echo $hasAccount&&$providerId!=='manual'?'Настройки почтового сервиса заполнены автоматически.':''; ?></p>
  </section>

  <section class="easychat-email__section" aria-labelledby="email-access-title"><h3 id="email-access-title" class="h6 fw-semibold mb-1">Доступ к ящику</h3><p class="small text-muted mb-3">Используйте пароль приложения, если почтовый сервис требует его.</p><div class="row g-3 easychat-email__credentials"><div class="col-md-6"><label class="form-label fw-semibold" for="email-name">Имя отправителя</label><input class="form-control" id="email-name" name="display_name" value="<?php echo $e($account['display_name']??''); ?>" placeholder="Поддержка магазина"></div><div class="col-md-6"><label class="form-label fw-semibold" for="email-login">Логин</label><input class="form-control" id="email-login" name="username" autocomplete="username" placeholder="Обычно совпадает с адресом"></div><div class="col-md-6"><label class="form-label fw-semibold" for="email-password">Пароль приложения</label><input class="form-control" id="email-password" name="password" type="password" autocomplete="new-password" placeholder="<?php echo $email_secret_saved?'Сохранён защищённо':'Введите пароль приложения'; ?>"></div><div class="col-md-6 easychat-email__help"><a class="btn btn-light" href="#" target="_blank" rel="noopener noreferrer" data-email-help hidden>Как создать пароль приложения <span aria-hidden="true">↗</span></a></div></div></section>

  <section class="easychat-email__readiness" aria-labelledby="email-readiness-title" data-email-health-panel><div class="easychat-email__readiness-heading"><div><h3 id="email-readiness-title" class="h6 fw-semibold mb-1">Готовность почты</h3><p class="small text-muted mb-0" data-email-health-summary>EasyChat проверит получение и отправку отдельно.</p></div><button class="btn btn-sm btn-link d-none" type="button" data-email-health-toggle aria-expanded="false" aria-controls="email-health-details">Подробнее</button></div><div class="easychat-email__checks" id="email-health-details" data-email-checks>
      <div class="easychat-email__check" data-email-check="inbound"><span class="easychat-email__check-icon" aria-hidden="true">•</span><span><strong>Получение писем</strong><small data-email-check-message>Ещё не проверено</small></span><span class="easychat-email__check-status" data-email-check-status>Не проверено</span></div>
      <div class="easychat-email__check" data-email-check="outbound"><span class="easychat-email__check-icon" aria-hidden="true">•</span><span><strong>Отправка ответов</strong><small data-email-check-message>EasyChat выберет безопасный способ автоматически</small></span><span class="easychat-email__check-status" data-email-check-status>Не проверено</span></div>
      <div class="easychat-email__check" data-email-check="deliverability"><span class="easychat-email__check-icon" aria-hidden="true">•</span><span><strong>Доставляемость</strong><small data-email-check-message>Проверится по DNS и реальному письму</small></span><span class="easychat-email__check-status" data-email-check-status>Не проверено</span></div>
  </div><div class="easychat-email__delivery-advice d-none" data-email-delivery-advice role="region" aria-labelledby="email-delivery-advice-title">
      <div class="easychat-email__delivery-advice-heading"><div><h4 id="email-delivery-advice-title" class="h6 fw-semibold mb-1" data-email-delivery-title>Как улучшить доставляемость</h4><p class="small text-muted mb-1 d-none" data-email-delivery-context></p><p class="small mb-0" data-email-delivery-summary></p></div><button class="btn btn-sm btn-outline-primary d-none" type="button" data-email-delivery-action></button></div>
      <ul class="easychat-email__delivery-checks mb-0" data-email-delivery-checks></ul>
  </div></section>

  <details class="easychat-email__technical" data-email-technical <?php echo $manualVisible?'open':''; ?>><summary>Технические настройки</summary><div class="easychat-email__technical-body">
    <div class="row g-3"><div class="col-md-6"><label class="form-label fw-semibold" for="email-transport">Как отправлять ответы</label><select class="form-select" id="email-transport" name="outbound_transport"><option value="auto" <?php echo $transport==='auto'?'selected':''; ?>>Автоматически</option><option value="direct_smtp" <?php echo $transport==='direct_smtp'?'selected':''; ?>>Через SMTP ящика</option><option value="cms_mail" <?php echo $transport==='cms_mail'?'selected':''; ?>>Через почту сайта</option><option value="local_relay" <?php echo $transport==='local_relay'?'selected':''; ?>>Через почту хостинга</option><option value="smtp_bz_api" <?php echo $transport==='smtp_bz_api'?'selected':''; ?>>Через SMTP.BZ API</option></select><div class="form-text">В автоматическом режиме EasyChat использует первый проверенный способ.</div></div><div class="col-md-6"><label class="form-label fw-semibold" for="email-sender">Адрес отправителя</label><input class="form-control" id="email-sender" name="sender_email" type="email" required value="<?php echo $e($account['sender_email']??$account['email_address']??''); ?>" placeholder="support@company.ru"><div class="form-text">Если адрес отличается, ответы включатся только после его проверки.</div><div class="easychat-email__sender-recommendation d-none" data-email-sender-recommendation role="status"><span><strong data-email-sender-value></strong> <span data-email-sender-reason></span></span><button type="button" class="btn btn-sm btn-link" data-email-sender-apply>Использовать</button></div></div></div>
    <div class="easychat-email__api-key mt-3" data-email-smtp-bz <?php echo $transport==='smtp_bz_api'?'':'hidden'; ?>><label class="form-label fw-semibold" for="smtp-bz-key">API-ключ SMTP.BZ</label><input class="form-control" id="smtp-bz-key" name="smtp_bz_api_key" type="password" autocomplete="new-password" placeholder="<?php echo !empty($account)&&$transport==='smtp_bz_api'?'Сохранён защищённо':'Введите API-ключ'; ?>"><div class="form-text">Используется ваш аккаунт SMTP.BZ. EasyChat не передаёт письма через общий сервер.</div></div>
    <div class="easychat-email__manual<?php echo $manualVisible?'':' d-none'; ?> mt-3" data-email-manual aria-labelledby="email-servers-title"><h4 id="email-servers-title" class="h6 fw-semibold mb-1">Серверы почты</h4><p class="small text-muted mb-3">Для неизвестного домена укажите настройки провайдера.</p><div class="row g-3"><div class="col-md-8"><label class="form-label fw-semibold" for="imap-host">IMAP-сервер</label><input class="form-control" id="imap-host" name="imap_host" required value="<?php echo $e($account['imap_host']??''); ?>" placeholder="imap.example.ru"></div><div class="col-md-4"><label class="form-label fw-semibold" for="imap-port">Порт</label><select class="form-select" id="imap-port" name="imap_port"><option value="993">993 — TLS</option></select></div><div class="col-md-8" data-email-smtp-fields><label class="form-label fw-semibold" for="smtp-host">SMTP-сервер</label><input class="form-control" id="smtp-host" name="smtp_host" required value="<?php echo $e($account['smtp_host']??''); ?>" placeholder="smtp.example.ru"></div><div class="col-md-4" data-email-smtp-fields><label class="form-label fw-semibold" for="smtp-port">Порт</label><select class="form-select" id="smtp-port" name="smtp_port"><option value="465" <?php echo (int)($account['smtp_port']??465)===465?'selected':''; ?>>465 — TLS</option><option value="587" <?php echo (int)($account['smtp_port']??0)===587?'selected':''; ?>>587 — STARTTLS</option></select></div></div><div class="form-check mt-3"><input class="form-check-input" type="checkbox" id="allow-private" name="allow_private_server" value="1" <?php echo !empty($account['allow_private_server'])?'checked':''; ?>><label class="form-check-label" for="allow-private">Разрешить внутренний IMAP/SMTP-сервер</label><div class="form-text">Только для проверенной корпоративной сети. Локальный relay EasyChat настраивает отдельно.</div></div></div>
  </div></details>

  <div class="easychat-email__actions"><button class="btn btn-primary" type="button" data-email-test>Проверить почту</button><button class="btn btn-outline-secondary" type="submit" data-email-save <?php echo $enabled?'':'disabled'; ?>><?php echo $hasAccount?'Сохранить и подключить':'Подключить почту'; ?></button><span class="small text-muted" data-email-action-hint>Проверка не включает канал и не отправляет письма клиентам.</span></div>
</form>
