<?php
/**
 * Feedback form – shown after task completion but before feedback submission
 */
?>
<div class="w-full">
  <div class="gateway-card" style="background:linear-gradient(135deg,rgba(15,172,175,.06),rgba(99,102,241,.06));border:2px solid #6ee7b7">
    <div style="margin-bottom:2rem">
      <div style="display:flex;align-items:center;gap:1rem;margin-bottom:1rem">
        <div style="width:2.5rem;height:2.5rem;border-radius:9999px;background:#6ee7b7;display:flex;align-items:center;justify-content:center;flex-shrink:0">
          <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" style="color:#059669">
            <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>
          </svg>
        </div>
        <div>
          <p class="gateway-label" style="margin:0;font-size:1.125rem">Request Completed</p>
          <p style="font-size:.875rem;color:#64748b;margin:.25rem 0 0 0">Please share your feedback about this process</p>
          <div style="display:flex;flex-wrap:wrap;gap:.5rem;margin-top:.75rem">
            <?php if (!empty($job_number)): ?>
            <span style="display:inline-flex;align-items:center;gap:.375rem;background:#ffffff;border:1px solid #dbeafe;border-radius:9999px;padding:.25rem .625rem;font-size:.75rem;color:#1e3a8a;max-width:100%">
              <strong style="font-weight:600">Job:</strong>
              <span style="color:#334155;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:14rem"><?= esc_html($job_number) ?></span>
            </span>
            <?php endif; ?>
            <span style="display:inline-flex;align-items:center;gap:.375rem;background:#ffffff;border:1px solid #dbeafe;border-radius:9999px;padding:.25rem .625rem;font-size:.75rem;color:#1e3a8a;max-width:100%">
              <strong style="font-weight:600">Project:</strong>
              <span style="color:#334155;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:18rem"><?= esc_html($primary_project ?: 'N/A') ?></span>
            </span>
            <span style="display:inline-flex;align-items:center;gap:.375rem;background:#ffffff;border:1px solid #dbeafe;border-radius:9999px;padding:.25rem .625rem;font-size:.75rem;color:#1e3a8a;max-width:100%">
              <strong style="font-weight:600">Task:</strong>
              <span style="color:#334155;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:24rem"><?= esc_html($request_title ?: 'N/A') ?></span>
            </span>
            <span style="display:inline-flex;align-items:center;gap:.375rem;background:#ffffff;border:1px solid #dbeafe;border-radius:9999px;padding:.25rem .625rem;font-size:.75rem;color:#1e3a8a;max-width:100%">
              <strong style="font-weight:600">Assignee:</strong>
              <span style="color:#334155;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:16rem"><?= esc_html($assignee ?: 'Unassigned') ?></span>
            </span>
          </div>
        </div>
      </div>
    </div>

    <form id="feedback-form" style="position:relative"
          data-refresh-url="<?= esc_attr($refresh_url ?? '') ?>">
      <input type="hidden" name="task_gid" value="<?= esc_attr($task_gid) ?>" />
      <input type="hidden" name="gateway_token" value="<?= esc_attr($token) ?>" />

      <!-- Completion Decision -->
      <div style="margin-bottom:1.5rem">
        <label style="display:block;font-weight:600;margin-bottom:.5rem;color:#1e293b;font-size:.875rem">
          Is this request complete?
        </label>
        <div style="display:flex;flex-wrap:wrap;gap:.5rem">
          <label style="display:inline-flex;align-items:center;gap:.5rem;border:1px solid #d1fae5;background:#f0fdf4;color:#065f46;border-radius:.5rem;padding:.5rem .75rem;font-size:.8125rem;cursor:pointer">
            <input type="radio" name="completion_decision" value="complete" checked style="margin:0" />
            Yes, this job is complete
          </label>
          <label style="display:inline-flex;align-items:center;gap:.5rem;border:1px solid #fecaca;background:#fef2f2;color:#991b1b;border-radius:.5rem;padding:.5rem .75rem;font-size:.8125rem;cursor:pointer">
            <input type="radio" name="completion_decision" value="not_complete" style="margin:0" />
            No, this job is not complete
          </label>
        </div>
      </div>

      <div id="complete-feedback-fields">

      <!-- Rating -->
      <div style="margin-bottom:1.5rem">
        <label style="display:block;font-weight:600;margin-bottom:.5rem;color:#1e293b;font-size:.875rem">
          How would you rate this service?
        </label>
        <div id="rating-stars" style="display:flex;gap:.5rem;margin-bottom:.5rem">
          <?php for ($i = 1; $i <= 5; $i++): ?>
            <button type="button" 
                    class="rating-star"
                    data-rating="<?= $i ?>"
                    style="font-size:2rem;cursor:pointer;opacity:.4;transition:opacity .2s ease;background:none;border:none;padding:0">
              ★
            </button>
          <?php endfor; ?>
        </div>
        <input type="hidden" name="rating" id="rating-value" value="0" />
        <p style="font-size:.75rem;color:#94a3b8;margin:0">Click to select (optional)</p>
      </div>

      <!-- Reply -->
      <div style="margin-bottom:1.5rem">
        <label for="feedback-reply" style="display:block;font-weight:600;margin-bottom:.5rem;color:#1e293b;font-size:.875rem">
          Quick Reply
        </label>
        <input 
          type="text"
          id="feedback-reply"
          name="reply"
          placeholder="Thank you, or any quick comment…"
          style="width:100%;background:#f8fafc;border:1px solid #e2e8f0;border-radius:.5rem;padding:.75rem;font-size:.875rem;color:#1e293b;outline:none;box-sizing:border-box;transition:border-color .15s ease,box-shadow .15s ease"
          onfocus="this.style.borderColor='#818cf8';this.style.boxShadow='0 0 0 3px rgba(129,140,248,.15)'"
          onblur="this.style.borderColor='#e2e8f0';this.style.boxShadow='none'"
        />
        <p style="font-size:.75rem;color:#94a3b8;margin:.25rem 0 0 0">(optional)</p>
      </div>

      <!-- Feedback -->
      <div style="margin-bottom:1.5rem">
        <label for="feedback-text" style="display:block;font-weight:600;margin-bottom:.5rem;color:#1e293b;font-size:.875rem">
          Additional Feedback
        </label>
        <textarea
          id="feedback-text"
          name="feedback"
          rows="4"
          placeholder="What went well? What could be improved?…"
          style="width:100%;background:#f8fafc;border:1px solid #e2e8f0;border-radius:.5rem;padding:.75rem;font-size:.875rem;color:#1e293b;resize:none;outline:none;box-sizing:border-box;transition:border-color .15s ease,box-shadow .15s ease;line-height:1.5"
          onfocus="this.style.borderColor='#818cf8';this.style.boxShadow='0 0 0 3px rgba(129,140,248,.15)'"
          onblur="this.style.borderColor='#e2e8f0';this.style.boxShadow='none'"
        ></textarea>
        <p style="font-size:.75rem;color:#94a3b8;margin:.25rem 0 0 0">(optional)</p>
      </div>

      </div>

      <div id="not-complete-reason-wrap" style="display:none;margin-bottom:1.5rem">
        <label for="not-complete-reason" style="display:block;font-weight:600;margin-bottom:.5rem;color:#1e293b;font-size:.875rem">
          Tell us what is still outstanding
        </label>
        <textarea
          id="not-complete-reason"
          name="not_complete_reason"
          rows="4"
          placeholder="Please let us know what still needs to be completed..."
          style="width:100%;background:#fff1f2;border:1px solid #fecaca;border-radius:.5rem;padding:.75rem;font-size:.875rem;color:#1e293b;resize:none;outline:none;box-sizing:border-box;transition:border-color .15s ease,box-shadow .15s ease;line-height:1.5"
          onfocus="this.style.borderColor='#fb7185';this.style.boxShadow='0 0 0 3px rgba(251,113,133,.15)'"
          onblur="this.style.borderColor='#fecaca';this.style.boxShadow='none'"
        ></textarea>
        <p style="font-size:.75rem;color:#be123c;margin:.25rem 0 0 0">This reason is required when a job is not complete.</p>
      </div>

      <div style="display:flex;gap:1rem;margin-top:2rem">
        <button id="submit-feedback-btn" type="submit" class="gateway-btn-primary">
          <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5" style="flex-shrink:0">
            <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>
          </svg>
          <span id="submit-feedback-btn-label">Submit Feedback</span>
        </button>
      </div>

      <div id="feedback-spinner" class="hidden" style="display:none;align-items:center;gap:.5rem;font-size:.8125rem;color:#64748b;margin-top:1rem">
        <svg class="animate-spin" style="width:1rem;height:1rem;color:#6ee7b7" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path>
        </svg>
        Submitting…
      </div>

      <p id="feedback-message" style="font-size:.8125rem;margin-top:1rem;color:#64748b"></p>
    </form>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const form = document.getElementById('feedback-form');
  const spinner = document.getElementById('feedback-spinner');
  const message = document.getElementById('feedback-message');
  const submitBtn = document.getElementById('submit-feedback-btn');
  const submitBtnLabel = document.getElementById('submit-feedback-btn-label');
  const ratingStars = document.querySelectorAll('.rating-star');
  const ratingValue = document.getElementById('rating-value');
  const completionInputs = form.querySelectorAll('input[name="completion_decision"]');
  const completeFeedbackFields = document.getElementById('complete-feedback-fields');
  const notCompleteWrap = document.getElementById('not-complete-reason-wrap');
  const notCompleteReasonInput = document.getElementById('not-complete-reason');
  let selectedRating = 0;
  let inFlight = false;

  function getCompletionDecision() {
    const checked = form.querySelector('input[name="completion_decision"]:checked');
    return checked ? checked.value : 'complete';
  }

  function syncCompletionMode() {
    const isNotComplete = getCompletionDecision() === 'not_complete';

    if (completeFeedbackFields) {
      completeFeedbackFields.style.display = isNotComplete ? 'none' : 'block';
    }

    if (notCompleteWrap) {
      notCompleteWrap.style.display = isNotComplete ? 'block' : 'none';
    }

    if (notCompleteReasonInput) {
      notCompleteReasonInput.required = isNotComplete;
    }

    if (submitBtnLabel) {
      submitBtnLabel.textContent = isNotComplete ? 'Send Update' : 'Submit Feedback';
    }
  }

  completionInputs.forEach(input => {
    input.addEventListener('change', syncCompletionMode);
  });

  syncCompletionMode();

  // Star rating handler
  ratingStars.forEach(star => {
    star.addEventListener('click', (e) => {
      e.preventDefault();
      selectedRating = parseInt(star.dataset.rating);
      ratingValue.value = selectedRating;
      ratingStars.forEach(s => {
        const rating = parseInt(s.dataset.rating);
        s.style.opacity = rating <= selectedRating ? '1' : '.4';
        s.style.color = rating <= selectedRating ? '#6ee7b7' : 'inherit';
      });
    });
    
    star.addEventListener('mouseenter', () => {
      const hoverRating = parseInt(star.dataset.rating);
      ratingStars.forEach(s => {
        const rating = parseInt(s.dataset.rating);
        s.style.opacity = rating <= hoverRating ? '1' : '.4';
      });
    });
  });

  document.getElementById('rating-stars').addEventListener('mouseleave', () => {
    ratingStars.forEach(s => {
      const rating = parseInt(s.dataset.rating);
      s.style.opacity = rating <= selectedRating ? '1' : '.4';
    });
  });

  // Form submission
  form.addEventListener('submit', async (e) => {
    e.preventDefault();

    if (inFlight) return;

    const formData = new FormData(form);
    const decision = formData.get('completion_decision') || 'complete';
    const notCompleteReason = String(formData.get('not_complete_reason') || '').trim();

    if (decision === 'not_complete' && !notCompleteReason) {
      message.textContent = 'Please tell us what is still outstanding before sending your update.';
      message.style.color = '#dc2626';
      return;
    }

    inFlight = true;

    submitBtn.disabled = true;
    submitBtn.style.opacity = '0.75';
    spinner.classList.remove('hidden');
    spinner.style.display = 'flex';
    message.textContent = '';

    const body = new URLSearchParams({
      action: 'afb_submit_feedback',
      task_gid: formData.get('task_gid'),
      gateway_token: formData.get('gateway_token'),
      completion_decision: decision,
      not_complete_reason: notCompleteReason,
      rating: formData.get('rating'),
      reply: formData.get('reply'),
      feedback: formData.get('feedback')
    });

    try {
      const res = await fetch(afb_ajax.ajax_url, { method: 'POST', body });
      const result = await res.json();

      if (result.success) {
        message.textContent = result.data.message || 'Thank you for your feedback!';
        message.style.color = '#059669';
        if (submitBtnLabel) {
          submitBtnLabel.textContent = (result.data?.mode === 'not_complete') ? 'Update Sent' : 'Submitted';
        }

        // Rebuild cache first so the latest task state appears on reload
        const refreshUrl = form.dataset.refreshUrl;
        const doReload = () => window.location.reload();
        setTimeout(() => {
          if (refreshUrl) {
            fetch(refreshUrl + '&ts=' + Date.now(), { credentials: 'same-origin', cache: 'no-store' })
              .then(doReload)
              .catch(doReload);
          } else {
            doReload();
          }
        }, 1500);
      } else {
        message.textContent = '❌ ' + (result.data?.message || 'Unable to submit feedback.');
        message.style.color = '#dc2626';
      }
    } catch (err) {
      message.textContent = '❌ Network error. Please try again.';
      message.style.color = '#dc2626';
    } finally {
      inFlight = false;
      submitBtn.disabled = false;
      submitBtn.style.opacity = '1';
      spinner.classList.add('hidden');
      spinner.style.display = 'none';
    }
  });
});
</script>
