<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Reenviar Correo DTE</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
  
  <link href="https://cdn.jsdelivr.net/npm/tom-select@2.4.3/dist/css/tom-select.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/tom-select@2.4.3/dist/js/tom-select.complete.min.js"></script>
  <style>
    body {
      background: #f5f6fa;
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      font-family: 'Segoe UI', sans-serif;
    }
    .card {
      border: none;
      border-radius: 12px;
      box-shadow: 0 2px 16px rgba(0,0,0,.08);
      width: 100%;
      max-width: 520px;
    }
    .card-header {
      background: #fff;
      border-bottom: 1px solid #eee;
      border-radius: 12px 12px 0 0 !important;
      padding: 1.4rem 1.75rem .9rem;
    }
    .card-header h5 {
      font-size: .95rem;
      font-weight: 600;
      color: #333;
      margin: 0;
      letter-spacing: .01em;
    }
    .card-body { padding: 1.5rem 1.75rem; }
    .form-label {
      font-size: .8rem;
      font-weight: 600;
      color: #555;
      margin-bottom: .3rem;
      text-transform: uppercase;
      letter-spacing: .04em;
    }
    .form-control, .form-select {
      border-radius: 8px;
      border-color: #dde1e7;
      font-size: .9rem;
      padding: .5rem .75rem;
    }
    .form-control:focus, .form-select:focus {
      border-color: #6c8ebf;
      box-shadow: 0 0 0 3px rgba(108,142,191,.15);
    }
    .optional-badge {
      font-size: .7rem;
      color: #aaa;
      font-weight: 400;
      text-transform: none;
      margin-left: 4px;
    }
    .btn-send {
      background: #3b5bdb;
      border: none;
      border-radius: 8px;
      font-size: .9rem;
      font-weight: 600;
      letter-spacing: .02em;
      padding: .55rem 1.4rem;
      color: #fff;
      transition: background .18s;
    }
    .btn-send:hover { background: #2f4bbf; color: #fff; }
    .btn-send:disabled { background: #a0aec0; }
  </style>
</head>
<body>

<div class="card">
  <div class="card-header">
    <h5>Reenviar correo de DTE</h5>
  </div>
  <div class="card-body">
    <form id="resendForm" novalidate>
      <?= csrf_field() ?>

      <div class="mb-3">
        <label for="isc" class="form-label">Cliente</label>
        <select class="form-select" id="isc" name="isc" required>
          <option value="">Seleccione un cliente…</option>
          <?php foreach ($clients as $isc => $client): ?>
            <option value="<?= esc($isc) ?>"><?= $isc?> (<?=  esc($client['comercial']) ?> - <?= esc($client['nombre'])?>)</option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="mb-3">
        <label for="cod_generacion" class="form-label">Código de generación</label>
        <input type="text" class="form-control" id="cod_generacion" name="cod_generacion"
               placeholder="Ej. XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" required />
      </div>

      <div class="mb-3">
        <label for="correo" class="form-label">Correo electrónico</label>
        <input type="email" class="form-control" id="correo" name="correo"
               placeholder="destinatario@correo.com" required />
      </div>

      <div class="mb-3">
        <label for="asunto" class="form-label">
          Asunto <span class="optional-badge">(opcional)</span>
        </label>
        <input type="text" class="form-control" id="asunto" name="asunto"
               placeholder="Documento Tributario Electrónico" />
      </div>

      <div class="mb-4">
        <label for="mensaje" class="form-label">
          Mensaje <span class="optional-badge">(opcional)</span>
        </label>
        <textarea class="form-control" id="mensaje" name="mensaje" rows="3"
                  placeholder="Mensaje adicional para el destinatario…"></textarea>
      </div>

      <div class="d-flex justify-content-end">
        <button type="submit" class="btn btn-send" id="btnSend">Enviar correo</button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    new TomSelect("#isc",{
        maxItems: 1,
        create: false,
        sortField: {
            field: "text",
            direction: "asc"
        }
    });

  const form    = document.getElementById('resendForm');
  const btnSend = document.getElementById('btnSend');
  const postUrl = '<?= base_url('herramientas/reenviar-correo') ?>';

  form.addEventListener('submit', async function (e) {
    e.preventDefault();

    const isc    = document.getElementById('isc').value.trim();
    const codGen = document.getElementById('cod_generacion').value.trim();
    const correo = document.getElementById('correo').value.trim();

    if (!isc || !codGen || !correo) {
      Swal.fire({
        icon: 'warning',
        title: 'Campos requeridos',
        text: 'Cliente, código de generación y correo son obligatorios.',
        confirmButtonColor: '#3b5bdb',
      });
      return;
    }

    btnSend.disabled = true;
    btnSend.textContent = 'Enviando…';

    const formData = new FormData(form);

    try {
      const response = await fetch(postUrl, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: formData,
      });

      const result = await response.json();

      if (result.success) {
        Swal.fire({
          icon: 'success',
          title: '¡Listo!',
          text: 'El correo fue enviado correctamente.',
          confirmButtonColor: '#3b5bdb',
        });
        form.reset();
      } else {
        const errList = result.errors
          ? Object.values(result.errors).join('<br>')
          : 'Ocurrió un error inesperado.';
        Swal.fire({
          icon: 'error',
          title: 'Error de validación',
          html: errList,
          confirmButtonColor: '#3b5bdb',
        });
      }
    } catch (err) {
      Swal.fire({
        icon: 'error',
        title: 'Error de conexión',
        text: 'No se pudo contactar el servidor. Intente de nuevo.',
        confirmButtonColor: '#3b5bdb',
      });
    } finally {
      btnSend.disabled = false;
      btnSend.textContent = 'Enviar correo';
    }
  });
</script>
</body>
</html>
