const url = "https://briananikayi.com/connect/pinchecker.php?TaxpayerID=";

function validateid(idNumber) {
  if (!idNumber || idNumber.length < 1) {
    document.getElementById('formprocessing').innerText = 'Please enter a valid PIN/ID.';
    clearFormFields();
    return;
  }

  const fullUrl = url + encodeURIComponent(idNumber);
  document.getElementById('formprocessing').innerText = 'Fetching client details...';
  clearFormFields();

  axios.get(fullUrl).then(response => {
    let data = response.data;

    // If API returned a string, parse it
    if (typeof data === "string") {
      try {
        data = JSON.parse(data);
      } catch (e) {
        document.getElementById('formprocessing').innerText = 'Invalid response format.';
        return;
      }
    }

    if (!data || !data.TaxpayerName) {
      document.getElementById('formprocessing').innerText = 'No record found for this PIN/ID.';
      return;
    }

    // Fill fields
    document.getElementById('client_names').value = data.TaxpayerName;
    document.getElementById('formprocessing').innerText = 'Client details fetched successfully.';

  }).catch(error => {
    document.getElementById('formprocessing').innerText = "Error fetching data.";
    console.error("Fetch error:", error);
    clearFormFields();
  });
}

function clearFormFields() {
  document.getElementById('client_names').value = '';
}

window.onload = () => {
  document.getElementById('id_number').addEventListener('blur', (e) => {
    validateid(e.target.value.trim());
  });
};
