<?php
$stmt = $GLOBALS['con']->prepare("SELECT * FROM `address_book` WHERE `clientnumber`=? ") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $_REQUEST['clientnumber']);
$stmt->execute();
$cr = $stmt->get_result();
$stmt->close();

$siteOptions = [];
$clientnumber = (int)($_REQUEST['clientnumber'] ?? 0);
$siteStmt = $GLOBALS['con']->prepare("SELECT `locnumber`, `locname` FROM `locations` WHERE `clientnumber`=? ORDER BY `locname` ASC");
if ($siteStmt) {
  $siteStmt->bind_param('i', $clientnumber);
  $siteStmt->execute();
  $siteResult = $siteStmt->get_result();
  while ($siteRow = mysqli_fetch_assoc($siteResult)) {
    $siteOptions[] = [
      'locnumber' => (int)$siteRow['locnumber'],
      'locname' => (string)$siteRow['locname']
    ];
  }
  $siteStmt->close();
}
?>

<div class="row">
  <div class="col-12 col-md-6">
    <div class="note note-light mb-3">
      This list will be auto populated by your main client profile. Add to this list for quick access to client contacts.<br />
      <small>Select "auto" for all contacts you wish to add to any outgoing emails for certification</small>
    </div>
  </div>

  <div class="col-12 col-md-6">
    <span class="float-end">
      <a class="btn btn-secondary"
         onclick="importAddress('client')"
         data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Import Client Contacts">Import Client Contacts</a>

      <a class="btn btn-secondary"
         onclick="importAddress('agent')"
         data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Import Agent Contacts">Import Agent Contacts</a>

      <a class="btn btn-secondary"
         onclick="importAddress('broker')"
         data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Import Broker Contacts">Import Broker Contacts</a>
    </span>
  </div>
</div>

<p class="lead">New Entry</p>
<div id="addrow" class="row mb-5 alert-info p-3">
  <div class="col-12 col-md-2"><label class="control-label" for="firstName">First Name</label><input id="firstName" class="form-control" type="text" /></div>
  <div class="col-12 col-md-2"><label class="control-label" for="lastName">Last Name</label><input id="lastName" class="form-control" type="text" /></div>
  <div class="col-12 col-md-2"><label class="control-label" for="role">Role</label><input id="role" class="form-control" type="text" placeholder="Safety officer" /></div>
  <div class="col-12 col-md-2"><label class="control-label" for="phone1">Phone 1</label><input id="phone1" class="form-control" type="text" /></div>
  <div class="col-12 col-md-2"><label class="control-label" for="phone2">Phone 2</label><input id="phone2" class="form-control" type="text" /></div>
  <div class="col-12 col-md-2"><label class="control-label" for="email">Email</label><input id="email" class="form-control" type="text" /></div>
  <div class="col-12 col-md-2 text-center">
    <label class="control-label" for="add"></label><br>
    <button id="add" type="button" class="btn btn-success text-light"
            data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Add contact">
      <i class="fad fa-plus text-light"></i>
    </button>
  </div>
</div>

<table id="table2" class="table table-bordered table-sm">
  <thead class="table-dark">
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Role</th>
      <th>Phone 1</th>
      <th>Phone 2</th>
      <th>Email</th>
      <th>Sites</th>
      <th>Auto</th>
      <th>All</th>
      <th>Billing</th>
      <th>Delivery</th>
      <th>Renewal</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody id="ab_tbody"></tbody>
</table>

<script>
const AB = {
  clientnumber: <?= (int)$_REQUEST['clientnumber'] ?>,
  dataUrl: ROOT_URL + '/includes/client/client_addressbook_data.php',
  fcnUrl: ROOT_URL + '/includes/client/client_addressbook_functions.php',
  siteOptions: <?= json_encode($siteOptions, JSON_UNESCAPED_UNICODE) ?>,
};

function initTooltips(scope = document) {
  if (typeof mdb === 'undefined' || !mdb.Tooltip) return;
  scope.querySelectorAll('[data-mdb-tooltip-init]').forEach((el) => {
    try { new mdb.Tooltip(el); } catch (e) {}
  });
}

function importAddress(type) {
  const dest = ROOT_URL + '/includes/client/client_addressbook_functions.php?fcn=import&type=' + encodeURIComponent(type) +
               '&clientnumber=' + encodeURIComponent(String(AB.clientnumber)) +
               '&tenant=' + encodeURIComponent(String(TENANT_URL));
  loadModalContent(dest, 'addressBox', 'modal-xl', 1060, 'true', 'Import ' + type + ' contacts');
}

async function postForm(url, paramsObj) {
  const body = new URLSearchParams(paramsObj);
  const res = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
    body: body.toString()
  });
  return (await res.text()).trim();
}

function syncAllAssignmentCheckbox(id) {
  const all = document.getElementById('AB_all_' + id);
  const b = document.getElementById('AB_billing_' + id);
  const d = document.getElementById('AB_delivery_' + id);
  const r = document.getElementById('AB_renewal_' + id);

  if (!all || !b || !d || !r) return;

  const onB = !!b.checked;
  const onD = !!d.checked;
  const onR = !!r.checked;

  const allOn = onB && onD && onR;
  const anyOn = onB || onD || onR;

  all.checked = allOn;
  all.indeterminate = (anyOn && !allOn);
}

function toggleAllAssignments(id) {
  const all = document.getElementById('AB_all_' + id);
  const b = document.getElementById('AB_billing_' + id);
  const d = document.getElementById('AB_delivery_' + id);
  const r = document.getElementById('AB_renewal_' + id);

  if (!all || !b || !d || !r) return;

  const setTo = !!all.checked; // checked => set all on, unchecked => set all off
  b.checked = setTo;
  d.checked = setTo;
  r.checked = setTo;

  syncAllAssignmentCheckbox(id);
  updateAssignments(id);
}

async function refreshAddressBookTable() {
  const html = await postForm(AB.dataUrl, { clientnumber: AB.clientnumber, tenant: TENANT_URL });
  const tbody = document.getElementById('ab_tbody');
  tbody.innerHTML = html;

  tbody.querySelectorAll('tr[id^="R"]').forEach((tr) => {
    const id = parseInt(tr.id.replace('R',''), 10);
    if (id) syncAllAssignmentCheckbox(id);
  });

  initTooltips(tbody);
}

async function addPerson() {
  const firstName = document.getElementById('firstName').value.trim();
  const lastName  = document.getElementById('lastName').value.trim();
  const role      = document.getElementById('role').value.trim();
  const phone1    = document.getElementById('phone1').value.trim();
  const phone2    = document.getElementById('phone2').value.trim();
  const email     = document.getElementById('email').value.trim();

  const ret = await postForm(AB.fcnUrl, {
    fcn: 'add',
    clientnumber: AB.clientnumber,
    firstName, lastName, role, phone1, phone2, email,
    tenant: TENANT_URL
  });

  const rtn = ret.split('|');
  if (rtn[0] === '1') {
    document.getElementById('firstName').value = '';
    document.getElementById('lastName').value = '';
    document.getElementById('role').value = '';
    document.getElementById('phone1').value = '';
    document.getElementById('phone2').value = '';
    document.getElementById('email').value = '';
    await refreshAddressBookTable();
    if (typeof showResponse === 'function') showResponse('success', 'Contact added');
  } else {
    if (typeof showResponse === 'function') showResponse('danger', 'USER EXISTS IN THIS ADDRESS BOOK');
  }
}

async function savePerson(id) {
  const fn = (document.getElementById('FN_' + id)?.value || '').trim();
  const ln = (document.getElementById('LN_' + id)?.value || '').trim();
  const rl = (document.getElementById('ROLE_' + id)?.value || '').trim();
  const p1 = (document.getElementById('P_' + id)?.value || '').trim();
  const p2 = (document.getElementById('M_' + id)?.value || '').trim();
  const em = (document.getElementById('E_' + id)?.value || '').trim();

  const ret = await postForm(AB.fcnUrl, {
    fcn: 'update',
    id,
    firstName: fn,
    lastName: ln,
    role: rl,
    phone1: p1,
    phone2: p2,
    email: em,
    tenant: TENANT_URL
  });

  if (ret === '1') {
    const row = document.getElementById('R' + id);
    if (row) {
      row.classList.add('table-success');
      setTimeout(() => row.classList.remove('table-success'), 900);
    }
    if (typeof showResponse === 'function') showResponse('success', 'Contact saved');
  } else {
    if (typeof showResponse === 'function') showResponse('danger', 'Failed to save contact');
  }
}

async function deletePerson(id) {
  const ret = await postForm(AB.fcnUrl, { fcn: 'remove', id, tenant: TENANT_URL });
  if (ret === '1') {
    const row = document.getElementById('R' + id);
    if (row) {
      row.classList.add('table-danger');
      setTimeout(() => row.remove(), 600);
    }
    if (typeof showResponse === 'function') showResponse('success', 'Contact removed');
  } else {
    if (typeof showResponse === 'function') showResponse('danger', 'Failed to remove contact');
  }
}

async function checker(id) {
  const checked = !!document.getElementById('V_' + id)?.checked;
  await postForm(AB.fcnUrl, { fcn: 'check', id, set: checked ? 1 : 0, tenant: TENANT_URL });
}

async function updateAssignments(id) {
  const b = document.getElementById('AB_billing_' + id);
  const d = document.getElementById('AB_delivery_' + id);
  const r = document.getElementById('AB_renewal_' + id);

  if (!b || !d || !r) return;

  const assignments = JSON.stringify({
    billing:  b.checked ? 1 : 0,
    delivery: d.checked ? 1 : 0,
    renewal:  r.checked ? 1 : 0,
  });

  const ret = await postForm(AB.fcnUrl, {
    fcn: 'updateAssignments',
    id,
    clientnumber: AB.clientnumber,
    assignments,
    tenant: TENANT_URL
  });

  if (ret === '1') {
    if (typeof showResponse === 'function') showResponse('success', 'Contact assignment successful');
  } else {
    if (typeof showResponse === 'function') showResponse('danger', 'Failed to update assignment type');
  }
}

function escapeHtml(value) {
  return String(value ?? '').replace(/[&<>"']/g, (char) => ({
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  }[char]));
}

function getSiteById(siteId) {
  return AB.siteOptions.find((site) => parseInt(site.locnumber, 10) === parseInt(siteId, 10)) || null;
}

function getRowSiteIds(id) {
  const wrap = document.getElementById('SITE_WRAP_' + id);
  if (!wrap) return [];

  try {
    const parsed = JSON.parse(wrap.dataset.sites || '[]');
    return Array.isArray(parsed) ? parsed.map((siteId) => parseInt(siteId, 10)).filter((siteId) => siteId > 0) : [];
  } catch (e) {
    return [];
  }
}

function setRowSiteIds(id, siteIds) {
  const safeIds = Array.from(new Set((siteIds || []).map((siteId) => parseInt(siteId, 10)).filter((siteId) => siteId > 0)));
  const wrap = document.getElementById('SITE_WRAP_' + id);
  const summary = document.getElementById('SITE_SUMMARY_' + id);
  if (!wrap || !summary) return;

  wrap.dataset.sites = JSON.stringify(safeIds);
  summary.textContent = safeIds.length === 0 ? 'All sites' : safeIds.length + ' site' + (safeIds.length === 1 ? '' : 's');

  const title = safeIds.length === 0
    ? 'All sites'
    : safeIds.map((siteId) => getSiteById(siteId)?.locname || '').filter(Boolean).join(', ');
  summary.setAttribute('title', title);
}

function siteIdsForPost(siteIds) {
  return !siteIds || siteIds.length === 0 ? 'all' : JSON.stringify(siteIds);
}

async function saveSiteAssignments(id, siteIds) {
  const ret = await postForm(AB.fcnUrl, {
    fcn: 'updateSites',
    id,
    clientnumber: AB.clientnumber,
    siteNumbers: siteIdsForPost(siteIds),
    tenant: TENANT_URL
  });

  if (ret !== '1') {
    const message = ret === 'missing_site_column'
      ? 'Address book site storage is not installed. Run the address_book_role_site_columns.sql patch.'
      : 'Failed to update sites';
    if (typeof showResponse === 'function') showResponse('danger', message);
    return false;
  }

  setRowSiteIds(id, siteIds);
  renderSiteModalBody(id);
  if (typeof showResponse === 'function') showResponse('success', 'Site assignment updated');
  return true;
}

function renderSiteModalBody(id) {
  const selected = getRowSiteIds(id);
  const body = document.getElementById('AB_site_modal_body_' + id);
  if (!body) return;

  const selectedSet = new Set(selected);
  const available = AB.siteOptions.filter((site) => !selectedSet.has(parseInt(site.locnumber, 10)));
  const selectedSites = selected.map((siteId) => getSiteById(siteId)).filter(Boolean);

  const selectHtml = available.length
    ? `<div class="input-group">
         <select id="AB_SITE_SELECT_${id}" class="form-control" data-mdb-select-init data-mdb-filter="true" data-mdb-container="#addressBookSitesModal">
           <option value="">Select site</option>
           ${available.map((site) => `<option value="${parseInt(site.locnumber, 10)}">${escapeHtml(site.locname)}</option>`).join('')}
         </select>
         <button type="button" class="btn btn-success" onclick="addSiteToContact(${id})"><i class="fad fa-plus"></i></button>
       </div>`
    : '<div class="alert alert-light mb-0">No further sites available.</div>';

  const assignedHtml = selected.length === 0
    ? '<div class="alert alert-info mb-0">Assigned to all sites.</div>'
    : `<div class="row g-2">
         ${selectedSites.map((site) => `
           <div class="col-12 col-md-6">
             <div class="border rounded p-2 d-flex align-items-center justify-content-between">
               <span class="text-truncate pe-2">${escapeHtml(site.locname)}</span>
               <button type="button" class="btn btn-danger btn-sm m-0 px-2 py-1" onclick="removeSiteFromContact(${id}, ${parseInt(site.locnumber, 10)})">
                 <i class="fad fa-trash"></i>
               </button>
             </div>
           </div>`).join('')}
       </div>`;

  const allSitesButton = selected.length === 0
    ? ''
    : `<button type="button" class="btn btn-light btn-sm" onclick="setContactToAllSites(${id})">Set all sites</button>`;

  body.innerHTML = `
    <div class="row g-3">
      <div class="col-12">
        <div class="d-flex align-items-center justify-content-between mb-2">
          <h6 class="mb-0">Assigned sites</h6>
          ${allSitesButton}
        </div>
        ${assignedHtml}
      </div>
      <div class="col-12">
        <h6 class="mb-2">Add site</h6>
        ${selectHtml}
      </div>
    </div>`;

  const select = document.getElementById('AB_SITE_SELECT_' + id);
  if (select && typeof mdb !== 'undefined' && mdb.Select) {
    try { new mdb.Select(select, { filter: true, container: '#addressBookSitesModal' }); } catch (e) {}
  }
}

function manageSites(id) {
  const name = [
    document.getElementById('FN_' + id)?.value || '',
    document.getElementById('LN_' + id)?.value || ''
  ].join(' ').trim();

  const dest = '<div id="AB_site_modal_body_' + id + '"></div>';
  loadModalContent(dest, 'addressBookSitesModal', 'modal-lg', 1060, 'true', 'Manage sites' + (name ? ' - ' + name : ''));
  setTimeout(() => renderSiteModalBody(id), 150);
}

async function addSiteToContact(id) {
  const select = document.getElementById('AB_SITE_SELECT_' + id);
  const siteId = parseInt(select?.value || '0', 10);
  if (!siteId) {
    if (typeof showResponse === 'function') showResponse('warning', 'Select a site to add');
    return;
  }

  const current = getRowSiteIds(id);
  await saveSiteAssignments(id, Array.from(new Set([...current, siteId])));
}

async function removeSiteFromContact(id, siteId) {
  const next = getRowSiteIds(id).filter((currentSiteId) => currentSiteId !== parseInt(siteId, 10));
  await saveSiteAssignments(id, next);
}

async function setContactToAllSites(id) {
  await saveSiteAssignments(id, []);
}

// Expose for modal import script (runs in parent)
window.refreshAddressBookTable = refreshAddressBookTable;

document.getElementById('add').addEventListener('click', addPerson);

document.getElementById('table2').addEventListener('click', (e) => {
  const btn = e.target.closest('button[data-action]');
  if (!btn) return;
  const id = parseInt(btn.getAttribute('data-id'), 10);
  if (!id) return;

  const action = btn.getAttribute('data-action');
  if (action === 'update') savePerson(id);
  if (action === 'remove') deletePerson(id);
  if (action === 'sites') manageSites(id);
});

refreshAddressBookTable();
initTooltips(document);

document.getElementById('navBox').innerHTML =
  '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&view=list">Client List</a><i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li>' +
  '<li class="breadcrumb_item"><a class="text-light" href="index.php?t=includes/master&p=client.php&clientnumber=<?= (int)$_REQUEST['clientnumber'] ?>&view=asset"><?= addslashes(getClientName($_REQUEST['clientnumber'])) ?></a><i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li>' +
  '<li class="breadcrumb-item active">Address Book</li>';
</script>
