<?php
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) { require_once('../../../' . $_REQUEST['tenant'] . '/config.php'); }
if (file_exists('/config.php')) { require_once('/config.php'); }

function ab_normalise_assignment_type($raw): string {
    $default = ['billing' => 0, 'delivery' => 0, 'renewal' => 0];

    if ($raw === null) return json_encode($default);
    $raw = trim((string)$raw);
    if ($raw === '') return json_encode($default);

    if ($raw !== '' && ($raw[0] === '{' || $raw[0] === '[')) {
        $decoded = json_decode($raw, true);
        if (is_array($decoded)) {
            $out = $default;
            $isList = (array_keys($decoded) === range(0, count($decoded) - 1));
            if ($isList) {
                foreach ($decoded as $v) {
                    $k = strtolower(trim((string)$v));
                    if (array_key_exists($k, $out)) $out[$k] = 1;
                }
            } else {
                foreach ($out as $k => $v) {
                    if (isset($decoded[$k])) $out[$k] = (int)!!$decoded[$k];
                }
            }
            return json_encode($out);
        }
    }

    $out = $default;
    $legacy = strtolower($raw);
    if ($legacy === 'all') {
        $out = ['billing' => 1, 'delivery' => 1, 'renewal' => 1];
    } elseif (isset($out[$legacy])) {
        $out[$legacy] = 1;
    }

    return json_encode($out);
}

function ab_assignment_checkbox_html(int $id, string $role, int $checked): string {
    $role = strtolower($role);
    $isChecked = $checked ? 'checked' : '';
    return '
  <input
    class="form-check-input m-0"
    type="checkbox"
    id="AB_' . $role . '_' . $id . '"
    ' . $isChecked . '
    onchange="syncAllAssignmentCheckbox(' . $id . '); updateAssignments(' . $id . ')">
';
}

function ab_assignment_all_checkbox_html(int $id, bool $allChecked): string {
    $isChecked = $allChecked ? 'checked' : '';
    return '
  <input
    class="form-check-input m-0"
    type="checkbox"
    id="AB_all_' . $id . '"
    ' . $isChecked . '
    onchange="toggleAllAssignments(' . $id . ')">
';
}

function ab_normalise_site_numbers($raw): array {
    if ($raw === null) return [];
    $raw = trim((string)$raw);
    if ($raw === '' || strtolower($raw) === 'all') return [];

    if ($raw[0] === '[') {
        $decoded = json_decode($raw, true);
        if (is_array($decoded)) {
            return array_values(array_unique(array_filter(array_map('intval', $decoded))));
        }
    }

    return array_values(array_unique(array_filter(array_map('intval', preg_split('/\s*,\s*/', $raw)))));
}

function ab_site_summary_html(int $id, array $selectedSites, array $siteOptions): string {
    $label = empty($selectedSites) ? 'All sites' : count($selectedSites) . ' site' . (count($selectedSites) === 1 ? '' : 's');
    $titleSites = [];
    $siteNames = [];

    foreach ($siteOptions as $site) {
        $locnumber = (int)($site['locnumber'] ?? 0);
        if ($locnumber <= 0) continue;
        $siteNames[$locnumber] = (string)($site['locname'] ?? '');
    }

    if (empty($selectedSites)) {
        $titleSites[] = 'All sites';
    } else {
        foreach ($selectedSites as $siteId) {
            if (isset($siteNames[$siteId])) $titleSites[] = $siteNames[$siteId];
        }
    }

    return '
  <div id="SITE_WRAP_' . $id . '" class="d-flex align-items-center justify-content-between gap-2"
       data-sites="' . htmlspecialchars(json_encode(array_values($selectedSites)), ENT_QUOTES) . '">
    <span id="SITE_SUMMARY_' . $id . '"
          class="small fw-bold"
          data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
          title="' . htmlspecialchars(implode(', ', $titleSites), ENT_QUOTES) . '">' . htmlspecialchars($label, ENT_QUOTES) . '</span>
    <button type="button" class="btn btn-info btn-sm m-0 px-2 py-1"
            data-id="' . $id . '"
            data-action="sites"
            data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Manage sites">
      <i class="fad fa-map-marker-alt"></i>
    </button>
  </div>';
}

function ab_render_row(array $cd, array $siteOptions): string {
    $id = (int)$cd['id'];
    $auto = ((string)($cd['auto'] ?? '0') === '1') ? 'checked' : '';
    $selectedSites = ab_normalise_site_numbers($cd['site_numbers'] ?? '');

    $asJson = ab_normalise_assignment_type($cd['assignment_type'] ?? '');
    $as = json_decode($asJson, true);
    if (!is_array($as)) $as = ['billing' => 0, 'delivery' => 0, 'renewal' => 0];

    $billing  = !empty($as['billing']) ? 1 : 0;
    $delivery = !empty($as['delivery']) ? 1 : 0;
    $renewal  = !empty($as['renewal']) ? 1 : 0;

    $allChecked = ($billing === 1 && $delivery === 1 && $renewal === 1);

    $btnTipSave = 'data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save contact"';
    $btnTipDel  = 'data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Remove contact"';

    return '
<tr id="R' . $id . '">
  <td><input id="FN_' . $id . '" class="form-control" type="text" value="' . htmlspecialchars($cd['firstName'] ?? '', ENT_QUOTES) . '"></td>
  <td><input id="LN_' . $id . '" class="form-control" type="text" value="' . htmlspecialchars($cd['lastName'] ?? '', ENT_QUOTES) . '"></td>
  <td><input id="ROLE_' . $id . '" class="form-control" type="text" value="' . htmlspecialchars($cd['role'] ?? '', ENT_QUOTES) . '" placeholder="Safety officer"></td>
  <td><input id="P_' . $id . '" class="form-control" type="text" value="' . htmlspecialchars($cd['phone1'] ?? '', ENT_QUOTES) . '"></td>
  <td><input id="M_' . $id . '" class="form-control" type="text" value="' . htmlspecialchars($cd['phone2'] ?? '', ENT_QUOTES) . '"></td>
  <td><input id="E_' . $id . '" class="form-control" type="text" value="' . htmlspecialchars($cd['email'] ?? '', ENT_QUOTES) . '"></td>
  <td>' . ab_site_summary_html($id, $selectedSites, $siteOptions) . '</td>

  <td class="text-center align-middle">
    <input id="V_' . $id . '" type="checkbox"
           class="form-check-input m-0 mx-auto d-block"
           onclick="checker(' . $id . ')"
           ' . $auto . '>
  </td>

  <td class="text-center align-middle">' . ab_assignment_all_checkbox_html($id, $allChecked) . '</td>
  <td class="text-center align-middle">' . ab_assignment_checkbox_html($id, 'billing',  $billing) . '</td>
 <td class="text-center align-middle">' . ab_assignment_checkbox_html($id, 'delivery', $delivery) . '</td>
  <td class="text-center align-middle">' . ab_assignment_checkbox_html($id, 'renewal',  $renewal) . '</td>

  <td class="text-nowrap">
    <button type="button" data-id="' . $id . '" data-action="update" class="btn btn-success m-0 px-3 py-2 me-1 waves-effect" ' . $btnTipSave . '>
      <i class="fad fa-save"></i>
    </button>
    <button type="button" data-id="' . $id . '" data-action="remove" class="btn btn-danger m-0 px-3 py-2 waves-effect" ' . $btnTipDel . '>
      <i class="fad fa-trash"></i>
    </button>
  </td>
</tr>';
}

$clientnumber = (int)($_REQUEST['clientnumber'] ?? 0);
if ($clientnumber <= 0) { echo ''; exit(); }

$siteOptions = [];
$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();
}

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

$out = '';
while ($cd = mysqli_fetch_array($cr)) {
    $out .= ab_render_row($cd, $siteOptions);
}
echo $out;
