<!-- templates/partials/pin_modal.html -->
<!-- 
  Include this in any template that needs PIN protection:
    {% include "partials/pin_modal.html" %}
  
  To trigger it, use a button or link with:
    onclick="openPinModal('action_description', callbackFn)"
  or on a form submit button:
    data-pin-action="add_product" data-pin-form="myFormId"
-->

<!-- PIN Modal -->
<div class="modal fade" id="pinModal" tabindex="-1" aria-labelledby="pinModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-sm">
    <div class="modal-content border-0 shadow-lg" style="border-radius:20px;overflow:hidden;">
      <!-- Header -->
      <div class="modal-header border-0 pb-0" style="background:linear-gradient(135deg,#667eea,#764ba2);">
        <div class="text-center w-100 py-2">
          <div class="mb-2">
            <i class="fas fa-lock fa-2x text-white opacity-75"></i>
          </div>
          <h5 class="modal-title text-white fw-bold" id="pinModalLabel">PIN Required</h5>
          <p class="text-white opacity-75 small mb-0" id="pinModalSubtitle">Enter your PIN to continue</p>
        </div>
      </div>

      <div class="modal-body px-4 pt-3">
        <!-- PIN Dots Display -->
        <div class="d-flex justify-content-center gap-3 mb-4" id="pinDots">
          <div class="pin-dot rounded-circle border border-2" style="width:16px;height:16px;transition:all .2s;"></div>
          <div class="pin-dot rounded-circle border border-2" style="width:16px;height:16px;transition:all .2s;"></div>
          <div class="pin-dot rounded-circle border border-2" style="width:16px;height:16px;transition:all .2s;"></div>
          <div class="pin-dot rounded-circle border border-2" style="width:16px;height:16px;transition:all .2s;"></div>
          <div class="pin-dot rounded-circle border border-2" style="width:16px;height:16px;transition:all .2s;"></div>
          <div class="pin-dot rounded-circle border border-2" style="width:16px;height:16px;transition:all .2s;"></div>
        </div>

        <!-- Hidden input for PIN value -->
        <input type="password" id="pinInput" maxlength="6"
               class="form-control text-center fw-bold fs-4 mb-3"
               placeholder="••••••" autocomplete="off"
               style="border-radius:12px;letter-spacing:8px;"
               oninput="updatePinDots(this.value)">

        <!-- Error message -->
        <div id="pinError" class="alert alert-danger small py-2 px-3 d-none" style="border-radius:10px;">
          <i class="fas fa-exclamation-circle me-1"></i>
          <span id="pinErrorText">Incorrect PIN. Please try again.</span>
        </div>

        <!-- Number Pad -->
        <div class="row g-2 mb-2">
          {% for num in "123456789" %}
            {% if forloop.counter == 10 %}<div class="col-4"></div>{% endif %}
            <div class="col-4">
              <button type="button" class="btn btn-light w-100 fw-bold fs-5 pin-btn"
                      style="border-radius:12px;height:52px;"
                      onclick="appendPin('{{ num }}')">{{ num }}</button>
            </div>
          {% endfor %}
          <div class="col-4">
            <button type="button" class="btn btn-light w-100 fw-bold fs-5 pin-btn"
                    style="border-radius:12px;height:52px;"
                    onclick="appendPin('0')">0</button>
          </div>
          <div class="col-4">
            <button type="button" class="btn btn-danger w-100 fw-bold pin-btn"
                    style="border-radius:12px;height:52px;"
                    onclick="clearPin()">
              <i class="fas fa-backspace"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- Footer -->
      <div class="modal-footer border-0 pt-0 pb-4 px-4 d-flex gap-2">
        <button type="button" class="btn btn-outline-secondary flex-fill" style="border-radius:12px;"
                data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary flex-fill fw-bold" style="border-radius:12px;"
                onclick="submitPin()" id="pinSubmitBtn">
          <span id="pinSubmitText"><i class="fas fa-check me-1"></i>Confirm</span>
          <span id="pinSubmitSpinner" class="d-none">
            <span class="spinner-border spinner-border-sm me-1"></span>Checking…
          </span>
        </button>
      </div>
    </div>
  </div>
</div>

<style>
.pin-dot.filled { background: #667eea; border-color: #667eea !important; }
.pin-btn:active { transform: scale(0.93); }
</style>

<script>
(function() {
  let _pinCallback = null;
  let _pinAction = '';

  // Called when a button/link needs PIN verification
  window.openPinModal = function(actionLabel, callback) {
    _pinAction = actionLabel || 'protected action';
    _pinCallback = callback;
    document.getElementById('pinInput').value = '';
    document.getElementById('pinError').classList.add('d-none');
    document.getElementById('pinModalSubtitle').textContent = 'Authorise: ' + _pinAction;
    updatePinDots('');
    var modal = new bootstrap.Modal(document.getElementById('pinModal'));
    modal.show();
    setTimeout(() => document.getElementById('pinInput').focus(), 400);
  };

  window.appendPin = function(digit) {
    var inp = document.getElementById('pinInput');
    if (inp.value.length < 6) {
      inp.value += digit;
      updatePinDots(inp.value);
    }
  };

  window.clearPin = function() {
    var inp = document.getElementById('pinInput');
    inp.value = inp.value.slice(0, -1);
    updatePinDots(inp.value);
  };

  window.updatePinDots = function(val) {
    var dots = document.querySelectorAll('.pin-dot');
    dots.forEach(function(dot, i) {
      dot.classList.toggle('filled', i < val.length);
    });
  };

  window.submitPin = function() {
    var pin = document.getElementById('pinInput').value.trim();
    if (!pin) return;

    var submitBtn = document.getElementById('pinSubmitBtn');
    document.getElementById('pinSubmitText').classList.add('d-none');
    document.getElementById('pinSubmitSpinner').classList.remove('d-none');
    submitBtn.disabled = true;

    fetch("{% url 'verify_pin' %}", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': getCsrfToken()
      },
      body: JSON.stringify({ pin: pin, action: _pinAction })
    })
    .then(r => r.json())
    .then(data => {
      document.getElementById('pinSubmitText').classList.remove('d-none');
      document.getElementById('pinSubmitSpinner').classList.add('d-none');
      submitBtn.disabled = false;

      if (data.ok) {
        bootstrap.Modal.getInstance(document.getElementById('pinModal')).hide();
        document.getElementById('pinInput').value = '';
        updatePinDots('');
        if (typeof _pinCallback === 'function') _pinCallback();
      } else {
        document.getElementById('pinError').classList.remove('d-none');
        document.getElementById('pinErrorText').textContent = data.message || 'Incorrect PIN.';
        document.getElementById('pinInput').value = '';
        updatePinDots('');
        document.getElementById('pinInput').focus();
      }
    })
    .catch(() => {
      document.getElementById('pinSubmitText').classList.remove('d-none');
      document.getElementById('pinSubmitSpinner').classList.add('d-none');
      submitBtn.disabled = false;
      document.getElementById('pinError').classList.remove('d-none');
      document.getElementById('pinErrorText').textContent = 'Network error. Try again.';
    });
  };

  function getCsrfToken() {
    var el = document.querySelector('[name=csrfmiddlewaretoken]');
    if (el) return el.value;
    var cookies = document.cookie.split(';');
    for (var c of cookies) {
      var parts = c.trim().split('=');
      if (parts[0] === 'csrftoken') return parts[1];
    }
    return '';
  }

  // Allow Enter key in PIN input
  document.addEventListener('DOMContentLoaded', function() {
    var inp = document.getElementById('pinInput');
    if (inp) {
      inp.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') submitPin();
      });
    }
  });
})();
</script>
