<?php
/* upload-attachments.php */
?>

<div class="gateway-card" style="position:sticky;top:1.5rem">

  <!-- Success banner (shown via JS) -->
  <div id="afbUploadSuccess" style="display:none;background:#f0fdf4;border:1px solid #bbf7d0;color:#15803d;padding:.75rem 1rem;border-radius:.625rem;margin-bottom:1rem;font-size:.875rem;align-items:center;gap:.5rem">
    <svg xmlns="http://www.w3.org/2000/svg" style="width:1rem;height:1rem;flex-shrink:0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
      <path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
    </svg>
    <span id="afbUploadSuccessMsg">File uploaded successfully.</span>
  </div>

  <!-- Error banner (shown via JS) -->
  <div id="afbUploadError" style="display:none;background:#fef2f2;border:1px solid #fecaca;color:#dc2626;padding:.75rem 1rem;border-radius:.625rem;margin-bottom:1rem;font-size:.875rem;align-items:center;gap:.5rem">
    <svg xmlns="http://www.w3.org/2000/svg" style="width:1rem;height:1rem;flex-shrink:0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
      <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126z"/>
    </svg>
    <span id="afbUploadErrorMsg">Upload failed. Please try again.</span>
  </div>

  <p class="gateway-label" style="margin-bottom:1rem">Upload a File</p>

  <form id="afbUploadForm" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="dashboard_upload_token" value="<?= esc_attr($asana_comms_token) ?>">
    <input type="hidden" name="_afb_ajax" value="1">

    <label for="uploadField" class="gateway-dropzone" id="dropLabel">
      <div style="width:3rem;height:3rem;background:#f1f5f9;border-radius:9999px;display:flex;align-items:center;justify-content:center">
        <svg xmlns="http://www.w3.org/2000/svg" style="width:1.5rem;height:1.5rem;color:#94a3b8" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
          <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5"/>
        </svg>
      </div>
      <p style="font-size:.875rem;color:#475569;margin:0">
        <span style="color:#4f46e5;font-weight:600;text-decoration:underline">Browse</span> or drop a file here
      </p>
      <p style="font-size:.75rem;color:#94a3b8;margin:0">Any file type accepted</p>

      <input
        id="uploadField"
        type="file"
        name="upload_file"
        required
        style="display:none"
        onchange="
          var fn = document.getElementById('fileName');
          var nameSpan = fn ? fn.querySelector('span') : null;
          var f = this.files?.[0];
          if (fn && nameSpan) {
            nameSpan.textContent = f ? f.name : '';
            fn.style.display = f ? 'flex' : 'none';
          }
          document.getElementById('afbUploadSuccess').style.display = 'none';
          document.getElementById('afbUploadError').style.display = 'none';
        "
      >
    </label>

    <!-- Chosen file preview -->
    <div id="fileName" style="display:none;align-items:center;gap:.5rem;background:#f8fafc;border:1px solid #f1f5f9;border-radius:.625rem;padding:.5rem .75rem;font-size:.8125rem;color:#1e293b;margin-top:.75rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
      <svg xmlns="http://www.w3.org/2000/svg" style="width:.875rem;height:.875rem;color:#4f46e5;flex-shrink:0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
        <path stroke-linecap="round" stroke-linejoin="round" d="M18.375 12.739l-7.693 7.693a4.5 4.5 0 01-6.364-6.364l10.94-10.94A3 3 0 1119.5 7.372L8.552 18.32"/>
      </svg>
      <span></span>
    </div>

    <!-- Progress bar (hidden until upload starts) -->
    <div id="afbProgressWrap" style="display:none;margin-top:.875rem">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.35rem">
        <span style="font-size:.75rem;font-weight:600;color:#475569" id="afbProgressLabel">Uploading…</span>
        <span style="font-size:.75rem;font-weight:700;color:#4f46e5" id="afbProgressPct">0%</span>
      </div>
      <div style="height:.5rem;background:#e0e7ff;border-radius:9999px;overflow:hidden">
        <div id="afbProgressBar"
             style="height:100%;width:0%;background:linear-gradient(90deg,#4f46e5,#7c3aed);border-radius:9999px;transition:width .15s ease"></div>
      </div>
    </div>

    <div style="margin-top:.875rem">
      <button type="submit" id="afbUploadBtn" class="gateway-btn-primary">
        <svg xmlns="http://www.w3.org/2000/svg" style="width:1rem;height:1rem;flex-shrink:0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
          <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5"/>
        </svg>
        <span id="afbUploadBtnLabel">Upload File</span>
      </button>
    </div>
  </form>
</div>

<script>
(function () {
  var form     = document.getElementById('afbUploadForm');
  var btn      = document.getElementById('afbUploadBtn');
  var btnLabel = document.getElementById('afbUploadBtnLabel');
  var wrap     = document.getElementById('afbProgressWrap');
  var bar      = document.getElementById('afbProgressBar');
  var pct      = document.getElementById('afbProgressPct');
  var lbl      = document.getElementById('afbProgressLabel');
  var success  = document.getElementById('afbUploadSuccess');
  var successMsg = document.getElementById('afbUploadSuccessMsg');
  var error    = document.getElementById('afbUploadError');
  var errorMsg = document.getElementById('afbUploadErrorMsg');

  if (!form) return;

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

    var fileInput = document.getElementById('uploadField');
    if (!fileInput || !fileInput.files.length) return;

    var fd = new FormData(form);

    // Reset UI
    success.style.display = 'none';
    error.style.display   = 'none';
    wrap.style.display    = 'block';
    bar.style.width       = '0%';
    pct.textContent       = '0%';
    lbl.textContent       = 'Uploading…';
    btn.disabled          = true;
    btnLabel.textContent  = 'Uploading…';

    var xhr = new XMLHttpRequest();

    // Progress tracking
    xhr.upload.addEventListener('progress', function (ev) {
      if (ev.lengthComputable) {
        var p = Math.round(ev.loaded / ev.total * 100);
        bar.style.width  = p + '%';
        pct.textContent  = p + '%';
        if (p === 100) lbl.textContent = 'Processing…';
      }
    });

    xhr.addEventListener('load', function () {
      bar.style.width = '100%';
      pct.textContent = '100%';

      var payload = null;
      try {
        payload = JSON.parse(xhr.responseText || '{}');
      } catch (e) {
        payload = null;
      }

      if (xhr.status >= 200 && xhr.status < 300) {
        if (payload && payload.success) {
          lbl.textContent          = 'Complete';
          lbl.style.color          = '#16a34a';
          bar.style.background     = 'linear-gradient(90deg,#16a34a,#22c55e)';
          success.style.display    = 'flex';
          successMsg.textContent   = payload.message || (fileInput.files[0].name + ' uploaded successfully.');

          // Refresh attachments panel without full page reload
          var panel = document.getElementById('afb-attachments-panel');
          if (panel) {
            var refreshUrl = window.location.href.split('#')[0];
            refreshUrl += (refreshUrl.indexOf('?') === -1 ? '?' : '&') + '_afb_ts=' + Date.now();
            fetch(refreshUrl, { credentials: 'same-origin', cache: 'no-store' })
              .then(function(r) { return r.text(); })
              .then(function(html) {
                var tmp = document.createElement('div');
                tmp.innerHTML = html;
                var fresh = tmp.querySelector('#afb-attachments-panel');
                if (fresh) {
                  panel.innerHTML = fresh.innerHTML;
                }
              })
              .catch(function() {});
          }

          // Reset form after short delay
          setTimeout(function () {
            form.reset();
            document.getElementById('fileName').style.display = 'none';
            wrap.style.display   = 'none';
            bar.style.width      = '0%';
            bar.style.background = 'linear-gradient(90deg,#4f46e5,#7c3aed)';
            lbl.style.color      = '';
            btn.disabled         = false;
            btnLabel.textContent = 'Upload File';
          }, 2500);
        } else {
          lbl.textContent        = 'Upload failed';
          lbl.style.color        = '#dc2626';
          bar.style.background   = '#fca5a5';
          error.style.display    = 'flex';
          errorMsg.textContent   = (payload && payload.message) ? payload.message : 'Upload failed while saving to Asana.';
          btn.disabled         = false;
          btnLabel.textContent = 'Upload File';
        }
      } else {
        lbl.textContent        = 'Upload failed';
        lbl.style.color        = '#dc2626';
        bar.style.background   = '#fca5a5';
        error.style.display    = 'flex';
        errorMsg.textContent   = 'Server returned an error (HTTP ' + xhr.status + '). Please try again.';
        btn.disabled           = false;
        btnLabel.textContent   = 'Upload File';
      }
    });

    xhr.addEventListener('error', function () {
      lbl.textContent      = 'Network error';
      lbl.style.color      = '#dc2626';
      bar.style.background = '#fca5a5';
      error.style.display  = 'flex';
      errorMsg.textContent = 'Network error. Please check your connection and try again.';
      btn.disabled         = false;
      btnLabel.textContent = 'Upload File';
    });

    xhr.open('POST', window.location.href);
    xhr.send(fd);
  });
})();
</script>
