let currentBooking = null;
let officeReady = false;

Office.onReady((info) => {
  officeReady = info.host === Office.HostType.Outlook;
  if (!officeReady) {
    showMessage('Open this page from Outlook while composing or replying to an email.', 'error');
  }
});

document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('findBtn').addEventListener('click', findBooking);
  document.getElementById('attachBtn').addEventListener('click', attachDocument);
  document.getElementById('orderId').addEventListener('keydown', (event) => {
    if (event.key === 'Enter') findBooking();
  });
});

async function findBooking() {
  const orderId = Number(document.getElementById('orderId').value);
  if (!Number.isInteger(orderId) || orderId <= 0) {
    showMessage('Enter a valid booking ID.', 'error');
    return;
  }

  setBusy('findBtn', true, 'Finding…');
  showMessage('Looking up the booking…', 'info');

  try {
    const response = await fetch(`api/booking_document.php?action=lookup&order_id=${encodeURIComponent(orderId)}`, {
      credentials: 'include',
      headers: { 'Accept': 'application/json' }
    });
    const data = await readJson(response);
    if (!response.ok || !data.ok) throw new Error(data.message || 'Booking lookup failed.');

    currentBooking = data.booking;
    document.getElementById('bookingTitle').textContent =
      currentBooking.order_no || `Booking #${currentBooking.id}`;
    document.getElementById('guestName').textContent = currentBooking.guest_name || 'Guest';
    document.getElementById('stayDates').textContent =
      `${currentBooking.check_in || '—'} to ${currentBooking.check_out || '—'}`;
    document.getElementById('agentName').textContent = currentBooking.agent_name || 'Direct';
    document.getElementById('bookingCard').classList.remove('hidden');
    showMessage('Booking found. Choose the document and attach it.', 'ok');
  } catch (error) {
    currentBooking = null;
    document.getElementById('bookingCard').classList.add('hidden');
    showMessage(error.message, 'error');
  } finally {
    setBusy('findBtn', false, 'Find');
  }
}

async function attachDocument() {
  if (!officeReady || !Office.context.mailbox.item) {
    showMessage('This action must run inside an Outlook compose or reply window.', 'error');
    return;
  }
  if (!currentBooking) {
    showMessage('Find a booking first.', 'error');
    return;
  }

  const item = Office.context.mailbox.item;
  if (typeof item.addFileAttachmentFromBase64Async !== 'function') {
    showMessage('This Outlook version does not support direct Base64 attachment. Update Outlook or use Outlook on the web.', 'error');
    return;
  }

  const documentType = document.getElementById('documentType').value;
  setBusy('attachBtn', true, 'Preparing PDF…');
  showMessage('Generating the PDF securely from RoomZ…', 'info');

  try {
    const response = await fetch('api/booking_document.php', {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        action: 'document',
        order_id: currentBooking.id,
        document_type: documentType
      })
    });

    const data = await readJson(response);
    if (!response.ok || !data.ok) throw new Error(data.message || 'Could not generate the PDF.');

    setBusy('attachBtn', true, 'Attaching…');
    await addBase64Attachment(item, data.base64, data.filename);
    showMessage(`${data.filename} was attached to this Outlook message.`, 'ok');
  } catch (error) {
    showMessage(error.message, 'error');
  } finally {
    setBusy('attachBtn', false, 'Attach PDF to this reply');
  }
}

function addBase64Attachment(item, base64, filename) {
  return new Promise((resolve, reject) => {
    item.addFileAttachmentFromBase64Async(
      base64,
      filename,
      { isInline: false },
      (result) => {
        if (result.status === Office.AsyncResultStatus.Succeeded) {
          resolve(result.value);
        } else {
          reject(new Error(result.error?.message || 'Outlook could not attach the PDF.'));
        }
      }
    );
  });
}

async function readJson(response) {
  const text = await response.text();
  try { return JSON.parse(text); }
  catch (_) {
    throw new Error(text.trim() || `Unexpected server response (${response.status}).`);
  }
}

function setBusy(id, busy, label) {
  const button = document.getElementById(id);
  button.disabled = busy;
  button.textContent = label;
}

function showMessage(text, type) {
  const box = document.getElementById('message');
  box.textContent = text;
  box.className = `message ${type}`;
}
