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

/**
 * assignment_type migration:
 * - Old: 'all' | 'billing' | 'delivery' | 'renewal'
 * - New: JSON object string: {"billing":1,"delivery":0,"renewal":1}
 */
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 '
<div class="form-check d-flex justify-content-center m-0">
  <input
    class="form-check-input m-0"
    type="checkbox"
    id="AB_' . $role . '_' . $id . '"
    ' . $isChecked . '
    onchange="syncAllAssignmentCheckbox(' . $id . '); updateAssignments(' . $id . ')">
</div>';
}

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

function ab_normalise_site_numbers_for_db($raw): string {
    $raw = trim((string)$raw);
    if ($raw === '' || strtolower($raw) === 'all') return '';

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

    $safe = array_values(array_unique(array_filter(array_map('intval', preg_split('/\s*,\s*/', $raw)))));
    return empty($safe) ? '' : json_encode($safe);
}

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

    $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="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 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>' . ab_assignment_all_checkbox_html($id, $allChecked) . '</td>
  <td>' . ab_assignment_checkbox_html($id, 'billing',  $billing) . '</td>
  <td>' . ab_assignment_checkbox_html($id, 'delivery', $delivery) . '</td>
  <td>' . 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>';
}

switch ($_REQUEST['fcn'] ?? '') {
    default:
        exit();

    case "updateAssignments":
        $id = (int)($_REQUEST['id'] ?? 0);
        $clientnumber = (int)($_REQUEST['clientnumber'] ?? 0);
        $assignments = (string)($_REQUEST['assignments'] ?? '');

        if ($id <= 0 || $clientnumber <= 0) { echo "0"; exit(); }

        $decoded = json_decode($assignments, true);
        if (!is_array($decoded)) { echo "0"; exit(); }

        $safe = [
            'billing'  => !empty($decoded['billing']) ? 1 : 0,
            'delivery' => !empty($decoded['delivery']) ? 1 : 0,
            'renewal'  => !empty($decoded['renewal']) ? 1 : 0,
        ];
        $json = json_encode($safe);

        $stmt = $GLOBALS['con']->prepare("UPDATE `address_book` SET `assignment_type`=? WHERE `id`=? AND `clientnumber`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param("sii", $json, $id, $clientnumber);
        $success = $stmt->execute();
        $stmt->close();

        echo $success ? "1" : "0";
        exit();

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

        $first = (string)($_REQUEST['firstName'] ?? '');
        $last  = (string)($_REQUEST['lastName'] ?? '');
        $email = (string)($_REQUEST['email'] ?? '');

        $stmt = $GLOBALS['con']->prepare("SELECT `id` FROM `address_book` WHERE `clientnumber`=? AND `firstName`=? AND `lastName`=? AND `email`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('isss', $clientnumber, $first, $last, $email);
        $stmt->execute(); $cr = $stmt->get_result(); $stmt->close();
        if (mysqli_num_rows($cr) >= 1) { echo "0"; exit(); }

        $stmt2 = $GLOBALS['con']->prepare("SELECT `indexer` FROM `address_book` WHERE `clientnumber`=? ORDER BY ABS(indexer) DESC LIMIT 1") or die(mysqli_error($GLOBALS['con']));
        $stmt2->bind_param('i', $clientnumber);
        $stmt2->execute(); $cr2 = $stmt2->get_result(); $stmt2->close();
        $c2 = mysqli_fetch_array($cr2);
        $index = ((int)($c2['indexer'] ?? 0) + 1);

        $defaultAssign = json_encode(['billing' => 0, 'delivery' => 0, 'renewal' => 0]);
        $role = (string)($_REQUEST['role'] ?? '');
        $siteNumbers = ab_normalise_site_numbers_for_db($_REQUEST['siteNumbers'] ?? '');

        $cname = getClientName($clientnumber);
        $p1 = (string)($_REQUEST['phone1'] ?? '');
        $p2 = (string)($_REQUEST['phone2'] ?? '');

        $stmt = $GLOBALS['con']->prepare("INSERT INTO `address_book` (`type`,`clientnumber`,`cname`,`firstName`,`lastName`,`role`,`phone1`,`phone2`,`email`,`site_numbers`,`auto`,`indexer`,`assignment_type`) VALUES ('client',?,?,?,?,?,?,?,?,?,0,?,?)");
        if ($stmt) {
            $stmt->bind_param('issssssssis', $clientnumber, $cname, $first, $last, $role, $p1, $p2, $email, $siteNumbers, $index, $defaultAssign);
        } else {
            $stmt = $GLOBALS['con']->prepare("INSERT INTO `address_book` (`type`,`clientnumber`,`cname`,`firstName`,`lastName`,`phone1`,`phone2`,`email`,`auto`,`indexer`,`assignment_type`) VALUES ('client',?,?,?,?,?,?,?,0,?,?)") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('issssssis', $clientnumber, $cname, $first, $last, $p1, $p2, $email, $index, $defaultAssign);
        }
        $stmt->execute();
        $stmt->close();

        echo "1|OK";
        exit();

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

        $first = (string)($_REQUEST['firstName'] ?? '');
        $last  = (string)($_REQUEST['lastName'] ?? '');
        $email = (string)($_REQUEST['email'] ?? '');

        $stmt = $GLOBALS['con']->prepare("SELECT `id` FROM `address_book` WHERE `clientnumber`=? AND `firstName`=? AND `lastName`=? AND `email`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('isss', $clientnumber, $first, $last, $email);
        $stmt->execute(); $cr = $stmt->get_result(); $stmt->close();
        if (mysqli_num_rows($cr) >= 1) { echo "0"; exit(); }

        $stmt2 = $GLOBALS['con']->prepare("SELECT `indexer` FROM `address_book` WHERE `clientnumber`=? ORDER BY ABS(indexer) DESC LIMIT 1") or die(mysqli_error($GLOBALS['con']));
        $stmt2->bind_param('i', $clientnumber);
        $stmt2->execute(); $cr2 = $stmt2->get_result(); $stmt2->close();
        $c2 = mysqli_fetch_array($cr2);
        $index = ((int)($c2['indexer'] ?? 0) + 1);

        $defaultAssign = json_encode(['billing' => 0, 'delivery' => 0, 'renewal' => 0]);
        $role = (string)($_REQUEST['role'] ?? '');
        $siteNumbers = ab_normalise_site_numbers_for_db($_REQUEST['siteNumbers'] ?? '');

        $type = (string)($_REQUEST['type'] ?? 'client');
        $cname = getClientName($clientnumber);
        $p1 = (string)($_REQUEST['phone1'] ?? '');
        $p2 = (string)($_REQUEST['phone2'] ?? '');

        $stmt = $GLOBALS['con']->prepare("INSERT INTO `address_book` (`type`,`clientnumber`,`cname`,`firstName`,`lastName`,`role`,`phone1`,`phone2`,`email`,`site_numbers`,`auto`,`indexer`,`assignment_type`) VALUES (?,?,?,?,?,?,?,?,?,?,0,?,?)");
        if ($stmt) {
            $stmt->bind_param('sissssssssis', $type, $clientnumber, $cname, $first, $last, $role, $p1, $p2, $email, $siteNumbers, $index, $defaultAssign);
        } else {
            $stmt = $GLOBALS['con']->prepare("INSERT INTO `address_book` (`type`,`clientnumber`,`cname`,`firstName`,`lastName`,`phone1`,`phone2`,`email`,`auto`,`indexer`,`assignment_type`) VALUES (?,?,?,?,?,?,?,?,0,?,?)") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('sissssssis', $type, $clientnumber, $cname, $first, $last, $p1, $p2, $email, $index, $defaultAssign);
        }
        $stmt->execute();
        $stmt->close();

        echo "1|OK";
        exit();

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

        $email = trim((string)($_REQUEST['email'] ?? ''));
        if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "0"; exit(); }

        $stmt = $GLOBALS['con']->prepare("SELECT `id` FROM `address_book` WHERE `clientnumber`=? AND LOWER(`email`)=LOWER(?) LIMIT 1") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('is', $clientnumber, $email);
        $stmt->execute();
        $cr = $stmt->get_result();
        $stmt->close();
        if (mysqli_num_rows($cr) >= 1) { echo "exists"; exit(); }

        $stmt2 = $GLOBALS['con']->prepare("SELECT `indexer` FROM `address_book` WHERE `clientnumber`=? ORDER BY ABS(indexer) DESC LIMIT 1") or die(mysqli_error($GLOBALS['con']));
        $stmt2->bind_param('i', $clientnumber);
        $stmt2->execute();
        $cr2 = $stmt2->get_result();
        $stmt2->close();
        $c2 = mysqli_fetch_array($cr2);
        $index = ((int)($c2['indexer'] ?? 0) + 1);

        $decoded = json_decode((string)($_REQUEST['assignments'] ?? ''), true);
        if (!is_array($decoded)) $decoded = [];
        $safeAssignments = [
            'billing'  => !empty($decoded['billing']) ? 1 : 0,
            'delivery' => !empty($decoded['delivery']) ? 1 : 0,
            'renewal'  => !empty($decoded['renewal']) ? 1 : 0,
        ];
        $assignmentJson = json_encode($safeAssignments);

        $first = (string)($_REQUEST['firstName'] ?? '');
        $last  = (string)($_REQUEST['lastName'] ?? '');
        $role = (string)($_REQUEST['role'] ?? '');
        $p1 = (string)($_REQUEST['phone1'] ?? '');
        $p2 = (string)($_REQUEST['phone2'] ?? '');
        $auto = !empty($_REQUEST['auto']) ? 1 : 0;
        $siteNumbers = ab_normalise_site_numbers_for_db($_REQUEST['siteNumbers'] ?? '');
        $cname = getClientName($clientnumber);

        $stmt = $GLOBALS['con']->prepare("INSERT INTO `address_book` (`type`,`clientnumber`,`cname`,`firstName`,`lastName`,`role`,`phone1`,`phone2`,`email`,`site_numbers`,`auto`,`indexer`,`assignment_type`) VALUES ('client',?,?,?,?,?,?,?,?,?,?,?,?)");
        if ($stmt) {
            $stmt->bind_param('issssssssiis', $clientnumber, $cname, $first, $last, $role, $p1, $p2, $email, $siteNumbers, $auto, $index, $assignmentJson);
        } else {
            $stmt = $GLOBALS['con']->prepare("INSERT INTO `address_book` (`type`,`clientnumber`,`cname`,`firstName`,`lastName`,`phone1`,`phone2`,`email`,`auto`,`indexer`,`assignment_type`) VALUES ('client',?,?,?,?,?,?,?,?,?,?)") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('issssssiis', $clientnumber, $cname, $first, $last, $p1, $p2, $email, $auto, $index, $assignmentJson);
        }
        $ok = $stmt->execute();
        $newId = mysqli_insert_id($GLOBALS['con']);
        $stmt->close();

        echo $ok ? "1|" . (int)$newId : "0";
        exit();

    case "check":
        $id = (int)($_REQUEST['id'] ?? 0);
        $set = (int)($_REQUEST['set'] ?? 0);
        if ($id <= 0) { echo "0"; exit(); }

        $stmt = $GLOBALS['con']->prepare("UPDATE `address_book` SET `auto`=? WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ii', $set, $id);
        $ok = $stmt->execute();
        $stmt->close();

        echo $ok ? "1" : "0";
        exit();

    case "updateSites":
        $id = (int)($_REQUEST['id'] ?? 0);
        $clientnumber = (int)($_REQUEST['clientnumber'] ?? 0);
        if ($id <= 0 || $clientnumber <= 0) { echo "0"; exit(); }

        $siteNumbers = ab_normalise_site_numbers_for_db($_REQUEST['siteNumbers'] ?? '');

        $stmt = $GLOBALS['con']->prepare("UPDATE `address_book` SET `site_numbers`=? WHERE `id`=? AND `clientnumber`=?");
        if (!$stmt) {
            $err = strtolower((string)mysqli_error($GLOBALS['con']));
            echo (strpos($err, 'site_numbers') !== false || strpos($err, 'unknown column') !== false) ? "missing_site_column" : "0";
            exit();
        }
        $stmt->bind_param('sii', $siteNumbers, $id, $clientnumber);
        $ok = $stmt->execute();
        $stmt->close();

        echo $ok ? "1" : "0";
        exit();

    case "import":
        $top = mysqli_query($GLOBALS['con'], "SELECT * FROM `clientdetails` WHERE `clientnumber`='" . (int)$_REQUEST['clientnumber'] . "'") or die($e = mysqli_error($GLOBALS['con']));
        $info = mysqli_fetch_array($top);

        switch ($_REQUEST['type'] ?? '') {
            default: exit();

            case "client":
                $recall = mysqli_query($GLOBALS['con'], "SELECT * FROM `clientdetails` WHERE `clientnumber`='" . (int)$_REQUEST['clientnumber'] . "'") or die($e = mysqli_error($GLOBALS['con']));
                break;

            case "agent":
                $recall = mysqli_query($GLOBALS['con'], "SELECT * FROM `agents` WHERE `agent_number`='" . (int)$info['agent_number'] . "'") or die($e = mysqli_error($GLOBALS['con']));
                break;

            case "broker":
                $recall = mysqli_query($GLOBALS['con'], "SELECT * FROM `brokers` WHERE `broker_number`='" . (int)$info['broker_number'] . "'") or die($e = mysqli_error($GLOBALS['con']));
                break;
        }
        ?>
        <div class="row">
            <div class="col-12">Select the <?= htmlspecialchars($_REQUEST['type']) ?> you wish to import into your address book.</div>
        </div>
        <div class="row">
            <div class="col-12">
                <table class="table table-sm table-striped">
                    <thead>
                        <tr>
                            <th><?= htmlspecialchars($_REQUEST['type']) ?> Name</th>
                            <th>Contact Type</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $rowData = '';
                    while ($data = mysqli_fetch_array($recall)) {
                        switch ($_REQUEST['type']) {
                            default: break;

                            case "client":
                                if (!empty($data['email'])) {
                                    $name = $data['clientname']; $type = "Main"; $email = $data['email']; $phone = $data['phone1'];
                                    $rowData .= '
                                    <tr>
                                        <td>' . htmlspecialchars($name) . '</td>
                                        <td>' . htmlspecialchars($type) . '</td>
                                        <td>' . htmlspecialchars($phone) . '</td>
                                        <td>' . htmlspecialchars($email) . '</td>
                                        <td><button type="button" class="btn btn-sm btn-success m-0 px-3 py-2" onclick="addImport(\'' . addslashes($name) . '\',\'\',\'' . addslashes($phone) . '\',\'\',\'' . addslashes($email) . '\',\'client\')"><i class="fad fa-plus"></i></button></td>
                                    </tr>';
                                }
                                if (!empty($data['pri_contact_email'])) {
                                    $name = $data['pri_contact_name']; $type = "Primary"; $email = $data['pri_contact_email']; $phone = $data['pri_contact_tel'];
                                    $rowData .= '
                                    <tr>
                                        <td>' . htmlspecialchars($name) . '</td>
                                        <td>' . htmlspecialchars($type) . '</td>
                                        <td>' . htmlspecialchars($phone) . '</td>
                                        <td>' . htmlspecialchars($email) . '</td>
                                        <td><button type="button" class="btn btn-sm btn-success m-0 px-3 py-2" onclick="addImport(\'' . addslashes($name) . '\',\'\',\'' . addslashes($phone) . '\',\'\',\'' . addslashes($email) . '\',\'client\')"><i class="fad fa-plus"></i></button></td>
                                    </tr>';
                                }
                                if (!empty($data['sec_contact_email'])) {
                                    $name = $data['sec_contact_name']; $type = "Secondary"; $email = $data['sec_contact_email']; $phone = $data['sec_contact_tel'];
                                    $rowData .= '
                                    <tr>
                                        <td>' . htmlspecialchars($name) . '</td>
                                        <td>' . htmlspecialchars($type) . '</td>
                                        <td>' . htmlspecialchars($phone) . '</td>
                                        <td>' . htmlspecialchars($email) . '</td>
                                        <td><button type="button" class="btn btn-sm btn-success m-0 px-3 py-2" onclick="addImport(\'' . addslashes($name) . '\',\'\',\'' . addslashes($phone) . '\',\'\',\'' . addslashes($email) . '\',\'client\')"><i class="fad fa-plus"></i></button></td>
                                    </tr>';
                                }
                                break;

                            case "agent":
                                if (!empty($data['agent_name']) && !empty($data['email'])) {
                                    $name = $data['agent_name'];
                                    $type = "Main";
                                    $email = $data['email'];
                                    $phone = $data['tel'] ?? '';
                                    $rowData .= '
                                    <tr>
                                        <td>' . htmlspecialchars($name) . '</td>
                                        <td>' . htmlspecialchars($type) . '</td>
                                        <td>' . htmlspecialchars($phone) . '</td>
                                        <td>' . htmlspecialchars($email) . '</td>
                                        <td><button type="button" class="btn btn-sm btn-success m-0 px-3 py-2" onclick="addImport(\'' . addslashes($name) . '\',\'\',\'' . addslashes($phone) . '\',\'\',\'' . addslashes($email) . '\',\'agent\')"><i class="fad fa-plus"></i></button></td>
                                    </tr>';
                                }
                                break;

                            case "broker":
                                if (!empty($data['broker_name']) && !empty($data['email'])) {
                                    $name = $data['broker_name'];
                                    $type = "Main";
                                    $email = $data['email'];
                                    $phone = $data['tel'] ?? '';
                                    $rowData .= '
                                    <tr>
                                        <td>' . htmlspecialchars($name) . '</td>
                                        <td>' . htmlspecialchars($type) . '</td>
                                        <td>' . htmlspecialchars($phone) . '</td>
                                        <td>' . htmlspecialchars($email) . '</td>
                                        <td><button type="button" class="btn btn-sm btn-success m-0 px-3 py-2" onclick="addImport(\'' . addslashes($name) . '\',\'\',\'' . addslashes($phone) . '\',\'\',\'' . addslashes($email) . '\',\'broker\')"><i class="fad fa-plus"></i></button></td>
                                    </tr>';
                                }
                                break;
                        }
                    }
                    echo $rowData;
                    ?>
                    </tbody>
                </table>
            </div>
        </div>

        <script>
        function addImport(f, l, p1, p2, em, ty) {
            const params = new URLSearchParams();
            params.set('firstName', f);
            params.set('lastName', l);
            params.set('phone1', p1);
            params.set('phone2', p2);
            params.set('email', em);
            params.set('type', ty);
            params.set('clientnumber', '<?= (int)$_REQUEST['clientnumber'] ?>');
            params.set('fcn', 'addImport');
            params.set('tenant', TENANT_URL);

            fetch(ROOT_URL + '/includes/client/client_addressbook_functions.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                body: params.toString()
            })
            .then(r => r.text())
            .then(ret => {
                const rtn = String(ret).split('|');
                if (rtn[0] === '1') {
                    if (parent && parent.refreshAddressBookTable) parent.refreshAddressBookTable();
                    if (parent && parent.killModal) parent.killModal('addressBox');
                } else {
                    if (parent && parent.showResponse) parent.showResponse('danger', 'USER EXISTS IN THIS ADDRESS BOOK');
                }
            })
            .catch(() => {
                if (parent && parent.showResponse) parent.showResponse('danger', 'Import failed');
            });
        }
        </script>
        <?php
        exit();

    case "update":
        $id = (int)($_REQUEST['id'] ?? 0);
        if ($id <= 0) { echo "0"; exit(); }

        $first = (string)($_REQUEST['firstName'] ?? '');
        $last  = (string)($_REQUEST['lastName'] ?? '');
        $role  = (string)($_REQUEST['role'] ?? '');
        $p1    = (string)($_REQUEST['phone1'] ?? '');
        $p2    = (string)($_REQUEST['phone2'] ?? '');
        $email = (string)($_REQUEST['email'] ?? '');

        $stmt = $GLOBALS['con']->prepare("UPDATE `address_book` SET `firstName`=?,`lastName`=?,`role`=?,`phone1`=?,`phone2`=?,`email`=? WHERE `id`=?");
        if ($stmt) {
            $stmt->bind_param('ssssssi', $first, $last, $role, $p1, $p2, $email, $id);
        } else {
            $stmt = $GLOBALS['con']->prepare("UPDATE `address_book` SET `firstName`=?,`lastName`=?,`phone1`=?,`phone2`=?,`email`=? WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('sssssi', $first, $last, $p1, $p2, $email, $id);
        }
        $ok = $stmt->execute();
        $stmt->close();

        echo $ok ? "1" : "0";
        exit();

    case "remove":
        $id = (int)($_REQUEST['id'] ?? 0);
        if ($id <= 0) { echo "0"; exit(); }

        $stmt = $GLOBALS['con']->prepare("DELETE FROM `address_book` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $id);
        $ok = $stmt->execute();
        $stmt->close();

        echo $ok ? "1" : "0";
        exit();
}
