<?php
$delivery=is_array($delivery_connection??null)?$delivery_connection:array();
$rp=(array)($delivery['russian_post']??array()); $cdek=(array)($delivery['cdek']??array());
$yandex=(array)($delivery['yandex_delivery']??array()); $apiship=(array)($delivery['apiship']??array());
$openCartMethods=is_array($opencart_delivery_methods??null)?$opencart_delivery_methods:array();
$openCartItems=(array)($openCartMethods['items']??array());
$openCartPending=array(); $openCartConfigured=array();
foreach($openCartItems as $item){
  if(($item['evidence']??'')==='admin_mapping'||($item['evidence']??'')==='admin_ignored') $openCartConfigured[]=$item;
  elseif(($item['evidence']??'')!=='shipping_code') $openCartPending[]=$item;
}
$carrierOptions=array('cdek'=>'СДЭК','russian_post'=>'Почта России','yandex_delivery'=>'Яндекс Доставка','apiship'=>'ApiShip','ignore'=>'Не отслеживать');
?>
<section class="tab-pane fade<?php echo $integration_tab_active('delivery')?' show active':''; ?> easychat-delivery" id="delivery-panel" role="tabpanel" aria-labelledby="delivery-tab" data-delivery-root>
  <header class="easychat-delivery__header">
    <span class="easychat-delivery__mark" aria-hidden="true"><i class="fa fa-truck"></i></span>
    <div><h2 class="h5 fw-bold mb-1">Доставка рядом с заказом</h2><p class="small text-muted mb-0">EasyChat уточняет статус отправления через официальные API и ничего не изменяет у перевозчика.</p></div>
  </header>
  <div class="alert d-none" role="status" aria-live="polite" tabindex="-1" data-delivery-status></div>
  <form autocomplete="off" data-delivery-form>
    <input type="hidden" name="nonce" value="<?php echo htmlspecialchars((string)($delivery_nonce??''),ENT_QUOTES,'UTF-8'); ?>">
    <div class="easychat-delivery__providers">
      <fieldset class="easychat-delivery__provider">
        <legend><img src="assets/channels/cdek.svg" alt="CDEK" width="88" height="32"></legend>
        <div class="form-check form-switch"><input class="form-check-input" type="checkbox" role="switch" name="cdek_enabled" id="cdek-enabled" value="1" <?php echo !empty($cdek['enabled'])?'checked':''; ?>><label for="cdek-enabled">Получать статусы CDEK</label></div>
        <div class="row g-3 mt-1"><div class="col-md-6"><label class="form-label" for="cdek-client-id">Client ID</label><input class="form-control" id="cdek-client-id" name="cdek_client_id" type="password" autocomplete="new-password" placeholder="<?php echo !empty($cdek['credentials_saved'])?'Сохранён: '.htmlspecialchars((string)$cdek['client_id_mask'],ENT_QUOTES,'UTF-8'):'Из кабинета CDEK'; ?>"></div><div class="col-md-6"><label class="form-label" for="cdek-client-secret">Client secret</label><input class="form-control" id="cdek-client-secret" name="cdek_client_secret" type="password" autocomplete="new-password" placeholder="<?php echo !empty($cdek['credentials_saved'])?'Сохранён защищённо':'Из кабинета CDEK'; ?>"></div></div>
        <p class="form-text mb-0">API показывает отправления, доступные этой учётной записи CDEK.</p>
      </fieldset>
      <fieldset class="easychat-delivery__provider">
        <legend><img src="assets/channels/russian-post.svg" alt="Почта России" width="142" height="32"></legend>
        <div class="form-check form-switch"><input class="form-check-input" type="checkbox" role="switch" name="russian_post_enabled" id="russian-post-enabled" value="1" <?php echo !empty($rp['enabled'])?'checked':''; ?>><label for="russian-post-enabled">Получать статусы Почты России</label></div>
        <div class="row g-3 mt-1"><div class="col-md-6"><label class="form-label" for="russian-post-login">Логин API</label><input class="form-control" id="russian-post-login" name="russian_post_login" type="password" autocomplete="new-password" placeholder="<?php echo !empty($rp['credentials_saved'])?'Сохранён: '.htmlspecialchars((string)$rp['login_mask'],ENT_QUOTES,'UTF-8'):'tracking.pochta.ru'; ?>"></div><div class="col-md-6"><label class="form-label" for="russian-post-password">Пароль API</label><input class="form-control" id="russian-post-password" name="russian_post_password" type="password" autocomplete="new-password" placeholder="<?php echo !empty($rp['credentials_saved'])?'Сохранён защищённо':'Пароль API'; ?>"></div></div>
      </fieldset>
      <fieldset class="easychat-delivery__provider">
        <legend><img src="assets/channels/yandex-delivery.svg" alt="Яндекс Доставка" width="150" height="32"></legend>
        <div class="form-check form-switch"><input class="form-check-input" type="checkbox" role="switch" name="yandex_delivery_enabled" id="yandex-delivery-enabled" value="1" <?php echo !empty($yandex['enabled'])?'checked':''; ?>><label for="yandex-delivery-enabled">Получать статусы Яндекс Доставки</label></div>
        <div class="mt-3"><label class="form-label" for="yandex-delivery-token">OAuth-токен</label><input class="form-control" id="yandex-delivery-token" name="yandex_delivery_token" type="password" autocomplete="new-password" placeholder="<?php echo !empty($yandex['credentials_saved'])?'Сохранён: '.htmlspecialchars((string)$yandex['token_mask'],ENT_QUOTES,'UTF-8'):'Из кабинета Яндекс Доставки'; ?>"></div>
        <p class="form-text mb-0">Для статуса используйте <code>claim_id</code> заявки, а не публичный трек-номер.</p>
      </fieldset>
      <fieldset class="easychat-delivery__provider">
        <legend><img src="assets/channels/apiship.svg" alt="ApiShip" width="112" height="32"></legend>
        <div class="form-check form-switch"><input class="form-check-input" type="checkbox" role="switch" name="apiship_enabled" id="apiship-enabled" value="1" <?php echo !empty($apiship['enabled'])?'checked':''; ?>><label for="apiship-enabled">Получать статусы ApiShip</label></div>
        <div class="mt-3"><label class="form-label" for="apiship-token">API token</label><input class="form-control" id="apiship-token" name="apiship_token" type="password" autocomplete="new-password" placeholder="<?php echo !empty($apiship['credentials_saved'])?'Сохранён: '.htmlspecialchars((string)$apiship['token_mask'],ENT_QUOTES,'UTF-8'):'Из кабинета ApiShip'; ?>"></div>
        <p class="form-text mb-0">Для статуса используйте <code>clientNumber</code> заказа ApiShip. Условия трекинга сторонних заказов зависят от тарифа ApiShip.</p>
      </fieldset>
    </div>
    <div class="easychat-delivery__test"><div><label class="form-label fw-semibold" for="delivery-tracking-number">Проверить на отправлении</label><p class="small text-muted mb-2" data-delivery-tracking-hint>Сначала сохраните доступы, затем укажите реальный трек-номер.</p></div><select class="form-select" name="test_provider" aria-label="Сервис доставки"><option value="cdek">CDEK</option><option value="russian_post">Почта России</option><option value="yandex_delivery">Яндекс Доставка</option><option value="apiship">ApiShip</option></select><input class="form-control" id="delivery-tracking-number" name="tracking_number" inputmode="latin" placeholder="Трек-номер"><button class="btn btn-outline-secondary" type="button" data-delivery-test>Проверить</button></div>
    <input type="hidden" name="opencart_shipping_mapping" value="<?php echo htmlspecialchars(json_encode((array)($delivery['opencart_shipping_mapping']??array()),JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),ENT_QUOTES,'UTF-8'); ?>">
    <?php if(!empty($openCartMethods['available']) && ($openCartPending || $openCartConfigured)): ?>
      <section class="easychat-delivery__mapping" aria-labelledby="opencart-delivery-heading" data-opencart-mapping>
        <div class="easychat-delivery__mapping-heading">
          <div><h3 class="h6 fw-semibold mb-1" id="opencart-delivery-heading">Способы доставки OpenCart</h3><p class="small text-muted mb-0">EasyChat уже нашёл способы с трек-номерами. Подтвердите только те, которые не удалось распознать.</p></div>
          <button class="btn btn-outline-secondary btn-sm" type="button" data-delivery-scan><i class="fa fa-refresh" aria-hidden="true"></i><span>Проверить ещё раз</span></button>
        </div>
        <?php if($openCartPending): ?>
          <div class="easychat-delivery__mapping-note"><i class="fa fa-lightbulb-o" aria-hidden="true"></i><span>EasyChat не будет обращаться к API перевозчика, пока вы не подтвердите способ доставки.</span></div>
          <div class="easychat-delivery__mapping-list">
            <?php foreach($openCartPending as $item): $suggested=(string)($item['suggested_provider']??''); ?>
              <div class="easychat-delivery__mapping-row" data-opencart-mapping-row data-opencart-mapping-key="<?php echo htmlspecialchars((string)$item['key'],ENT_QUOTES,'UTF-8'); ?>">
                <div class="easychat-delivery__mapping-copy"><strong><?php echo htmlspecialchars((string)$item['name'],ENT_QUOTES,'UTF-8'); ?></strong><small><?php echo !empty($item['code'])?'Код: '.htmlspecialchars((string)$item['code'],ENT_QUOTES,'UTF-8'):'Код не передан модулем'; ?><?php echo !empty($item['orders_count'])?' · в заказах: '.(int)$item['orders_count']:''; ?></small></div>
                <div class="easychat-delivery__mapping-control"><label class="visually-hidden" for="opencart-carrier-<?php echo md5((string)$item['key']); ?>">Выберите перевозчика для «<?php echo htmlspecialchars((string)$item['name'],ENT_QUOTES,'UTF-8'); ?>»</label><select class="form-select" id="opencart-carrier-<?php echo md5((string)$item['key']); ?>" data-opencart-carrier><option value="">Выберите перевозчика</option><?php foreach($carrierOptions as $value=>$label): ?><option value="<?php echo $value; ?>"<?php echo $suggested===$value?' selected':''; ?>><?php echo htmlspecialchars($label,ENT_QUOTES,'UTF-8'); ?></option><?php endforeach; ?></select><small class="easychat-delivery__mapping-feedback" data-opencart-mapping-feedback><?php echo $suggested!==''?'Похоже на '.$carrierOptions[$suggested].' — подтвердите выбор.':''; ?></small></div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
        <?php if($openCartConfigured): ?>
          <details class="easychat-delivery__configured"><summary>Настроено: <?php echo count($openCartConfigured); ?></summary><div class="easychat-delivery__mapping-list mt-2"><?php foreach($openCartConfigured as $item): $selected=(string)($item['provider']??''); if($selected==='')$selected='ignore'; ?><div class="easychat-delivery__mapping-row is-configured" data-opencart-mapping-row data-opencart-mapping-key="<?php echo htmlspecialchars((string)$item['key'],ENT_QUOTES,'UTF-8'); ?>"><div class="easychat-delivery__mapping-copy"><strong><?php echo htmlspecialchars((string)$item['name'],ENT_QUOTES,'UTF-8'); ?></strong><small>Код: <?php echo htmlspecialchars((string)$item['key'],ENT_QUOTES,'UTF-8'); ?></small></div><div class="easychat-delivery__mapping-control"><label class="visually-hidden" for="opencart-saved-carrier-<?php echo md5((string)$item['key']); ?>">Перевозчик для «<?php echo htmlspecialchars((string)$item['name'],ENT_QUOTES,'UTF-8'); ?>»</label><select class="form-select" id="opencart-saved-carrier-<?php echo md5((string)$item['key']); ?>" data-opencart-carrier><?php foreach($carrierOptions as $value=>$label): ?><option value="<?php echo $value; ?>"<?php echo $selected===$value?' selected':''; ?>><?php echo htmlspecialchars($label,ENT_QUOTES,'UTF-8'); ?></option><?php endforeach; ?></select><small class="easychat-delivery__mapping-feedback" data-opencart-mapping-feedback></small></div></div><?php endforeach; ?></div></details>
        <?php endif; ?>
      </section>
    <?php elseif(!empty($openCartMethods['available'])): ?>
      <p class="easychat-delivery__mapping-quiet mb-0"><i class="fa fa-check-circle" aria-hidden="true"></i> Способы доставки OpenCart определяются автоматически.</p>
    <?php endif; ?>
    <div class="easychat-delivery__actions"><button class="btn btn-primary" type="submit" data-delivery-save>Сохранить</button><a class="btn btn-link" href="https://docs.easychat24.ru/docs/integrations/delivery/" target="_blank" rel="noopener noreferrer">Как настроить <span aria-hidden="true">↗</span></a></div>
  </form>
</section>
