<?php
//////////////////////////////////
// 	admin_notices ARRAY ORDER	//
// 	[0]=reports					//
// 	[1]=schedules				//
// 	[2]=defects					//
//	[3]=user creation			//
// 	[4]=system log				//
// 	[5]=						//
//////////////////////////////////

// ------------------------------
// Asset table column preferences
// ------------------------------


$stmt = $GLOBALS['con']->prepare("SELECT * FROM `system` WHERE `id`='1' ") or die(mysqli_error($GLOBALS['con']));
$stmt->execute();
$r = $stmt->get_result();
$stmt->close();
$i = mysqli_fetch_array($r);
$sd = explode(',', $i['admin_notices']);

$assetDefaults = [
    'description'  => ['label' => 'Description',  'visible' => true],
    'itemnumber'   => ['label' => 'Item ID',      'visible' => true],
    'manufacturer' => ['label' => 'Manufacturer', 'visible' => true],
    'make_model'   => ['label' => 'Make/Model',   'visible' => true],
    'condition'    => ['label' => 'Condition',    'visible' => true],
    'plantnumber'  => ['label' => 'Plant No.',    'visible' => true],
    'serialnumber' => ['label' => 'Serial',       'visible' => true],
    'locname'      => ['label' => 'Location',     'visible' => true],
    'subloc'       => ['label' => 'Sub-location', 'visible' => true],
    'postcode'     => ['label' => 'Post Code',    'visible' => true],
    'lastReport'   => ['label' => 'Result',       'visible' => true],
    'duedate'      => ['label' => 'Due',          'visible' => true],

];

$assetPrefs = [];
if (!empty($i['asset_table_prefs'])) {
    $tmp = json_decode((string)$i['asset_table_prefs'], true);
    if (is_array($tmp)) $assetPrefs = $tmp;
}

// Merge defaults (defaults are authoritative for missing keys)
foreach ($assetDefaults as $k => $def) {
    if (!isset($assetPrefs[$k]) || !is_array($assetPrefs[$k])) {
        $assetPrefs[$k] = $def;
        continue;
    }
    $assetPrefs[$k]['label'] = isset($assetPrefs[$k]['label']) ? (string)$assetPrefs[$k]['label'] : $def['label'];
    $assetPrefs[$k]['visible'] = isset($assetPrefs[$k]['visible']) ? (bool)$assetPrefs[$k]['visible'] : (bool)$def['visible'];
}

$assetPrefs['actions'] = ['label' => 'Actions', 'visible' => true];

$clientPortalDefaults = [
    'request_visit' => true,
    'report_fault'  => true,
    'nav_background' => '2b4055'
];

$clientPortalSettings = $clientPortalDefaults;

if (!empty($i['client_portal_settings'])) {
    $tmpPortal = json_decode((string)$i['client_portal_settings'], true);
    if (is_array($tmpPortal)) {
        $clientPortalSettings['request_visit'] = !empty($tmpPortal['request_visit']);
        $clientPortalSettings['report_fault'] = !empty($tmpPortal['report_fault']);
        $portalNavBackground = isset($tmpPortal['nav_background'])
            ? ltrim(trim((string)$tmpPortal['nav_background']), '#')
            : $clientPortalDefaults['nav_background'];
        $clientPortalSettings['nav_background'] = preg_match('/^[0-9a-fA-F]{6}$/', $portalNavBackground)
            ? strtolower($portalNavBackground)
            : $clientPortalDefaults['nav_background'];
    }
}

$reportImageDefaults = [
    'main_logo'        => '40',
    'client_logo'      => '40',
    'affiliation_logo' => '40'
];

$reportImageSettings = $reportImageDefaults;

if (!empty($i['report_image_settings'])) {
    $tmpReportImages = json_decode((string)$i['report_image_settings'], true);
    if (is_array($tmpReportImages)) {
        $reportImageSettings['main_logo'] = isset($tmpReportImages['main_logo']) && preg_match('/^\d{1,2}$/', (string)$tmpReportImages['main_logo'])
            ? str_pad((string)((int)$tmpReportImages['main_logo']), 2, '0', STR_PAD_LEFT)
            : $reportImageDefaults['main_logo'];

        $reportImageSettings['client_logo'] = isset($tmpReportImages['client_logo']) && preg_match('/^\d{1,2}$/', (string)$tmpReportImages['client_logo'])
            ? str_pad((string)((int)$tmpReportImages['client_logo']), 2, '0', STR_PAD_LEFT)
            : $reportImageDefaults['client_logo'];

        $reportImageSettings['affiliation_logo'] = isset($tmpReportImages['affiliation_logo']) && preg_match('/^\d{1,2}$/', (string)$tmpReportImages['affiliation_logo'])
            ? str_pad((string)((int)$tmpReportImages['affiliation_logo']), 2, '0', STR_PAD_LEFT)
            : $reportImageDefaults['affiliation_logo'];
    }
}

$defaultEmailReportMessageSettings = [
    'enabled' => false,
    'token' => 'default_reporting_email_message',
    'message' => ''
];

if (!empty($i['default_email_report_message'])) {
    $tmpDefaultEmailMessage = json_decode((string)$i['default_email_report_message'], true);
    if (is_array($tmpDefaultEmailMessage)) {
        $defaultEmailReportMessageSettings['enabled'] = !empty($tmpDefaultEmailMessage['enabled']);
        $defaultEmailReportMessageSettings['token'] = isset($tmpDefaultEmailMessage['token']) && $tmpDefaultEmailMessage['token'] !== ''
            ? (string)$tmpDefaultEmailMessage['token']
            : $defaultEmailReportMessageSettings['token'];
        $defaultEmailReportMessageSettings['message'] = isset($tmpDefaultEmailMessage['message'])
            ? (string)$tmpDefaultEmailMessage['message']
            : '';
    } else {
        $defaultEmailReportMessageSettings['message'] = (string)$i['default_email_report_message'];
    }
}

$mailConnectionType = (int)($i['mail_type'] ?? 1);
if (!in_array($mailConnectionType, [1, 2], true)) {
    $mailConnectionType = 1;
}

$spellcheckEnabled = !array_key_exists('spellcheck_enabled', $i) || (int)$i['spellcheck_enabled'] === 1;
?>

<style>
#assetCols .asset-column-control {
    align-items: center;
    display: grid;
    gap: 0.5rem;
    grid-template-columns: 7.5rem minmax(0, 1fr) auto;
}

#assetCols .asset-column-name {
    display: block;
    overflow: hidden;
    text-align: left;
    text-overflow: ellipsis;
}

#assetCols .asset-col-label {
    min-width: 0;
}

@media (max-width: 575.98px) {
    #assetCols .asset-column-control {
        grid-template-columns: 6.5rem minmax(0, 1fr) auto;
    }
}
</style>


<?php /// DATABASE 
?>
<!--
<table class="table table-bordered">
    <thead class="thead-dark">
        <tr>
            <th colspan="5">Database <small class="text-danger">(Altering this data incorrectly can prevent your system from loading)</small></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Username</th>
            <th>Password</th>
            <th>Master Database</th>
            <th>Company Database</th>
        </tr>
        <tr>
            <td><input id="db_username" class="form-control" type="text" name="db_username" value="<?= $i['db_username'] ?>" required></td>
            <td><input id="db_password" class="form-control" type="password" name="db_password" value="<?= $i['db_password'] ?>" required></td>
            <td><input id="db_master" class="form-control" type="text" name="db_master" value="<?= $i['db_master'] ?>" required></td>
            <td><input id="db_tables" class="form-control" type="text" name="db_tables" value="<?= $i['db_tables'] ?>" required></td>
        </tr>
        <tr>
            <td colspan="4" class="text-center"><a href="javascript:void(0)" class="btn btn-success" onclick="saveDbPrefs()"><i class="fa fa-save"></i> Save</a></td>
        </tr>
    </tbody>

</table>
-->
<script src="<?= ROOT_URL ?>/src/main.min.js"></script>
<link rel="stylesheet" href="<?= ROOT_URL ?>/src/style.css?v=5.0.3">


<div class="card mb-3">
    <div class="card-header table-dark text-light">
        <span data-help-topic="system_email">Email Server <small>(Required for Email sending)</small></span>

        <div class="float-end">
            <span id="verified" class="badge bg-light"></span>
        </div>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-12">
                <!-- MAILER -->
                <table class="table table-bordered">

                    <tbody>
                        <tr>
                            <th>Connection Type</th>
                            <td colspan="4">
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="mail_type" id="mail_type_yes"
                                        value="1" <?= $mailConnectionType === 1 ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="mail_type_yes">SMTP</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="mail_type" id="mail_type_ms365"
                                        value="2" <?= $mailConnectionType === 2 ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="mail_type_ms365">Microsoft 365</label>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <th id="mail_host_label">Mail server</th>
                            <th id="mail_username_label">Mail Username</th>
                            <th id="mail_password_label">Mail Password</th>
                            <th>Mail "From" Address</th>
                            <th>Mail "From" Name</th>
                        </tr>
                        <tr>
                            <td><input id="mail_host" class="form-control" type="text" name="mail_host"
                                    placeholder="<?= $mailConnectionType === 2 ? 'Directory (tenant) ID' : 'mail.yourdomain.com' ?>" value="<?= $i['mail_host'] ?>" required></td>
                            <td><input id="mail_username" class="form-control" type="text" name="mail_username"
                                    placeholder="<?= $mailConnectionType === 2 ? 'Application (client) ID' : 'full username' ?>" value="<?= $i['mail_username'] ?>" required></td>
                            <td>
                                <div class="input-group">
                                    <input id="mail_password" class="form-control" type="password" name="mail_password"
                                        placeholder="<?= $mailConnectionType === 2 ? 'Client secret value' : '' ?>"
                                        value="<?= $i['mail_password'] ?>" required>
                                    <button id="mail_password_toggle" class="btn btn-outline-secondary" type="button"
                                        onclick="toggleMailPasswordVisibility()" aria-label="Show mail password"
                                        title="Show password">
                                        <i id="mail_password_toggle_icon" class="fad fa-eye"></i>
                                    </button>
                                </div>
                            </td>
                            <td><input id="mail_from" class="form-control" type="text" name="mail_from"
                                    placeholder="noreply@yourdomain.com" value="<?= $i['mail_from'] ?>" required></td>
                            <td><input id="mail_from_name" class="form-control" type="text" name="mail_from_name"
                                    placeholder="Your Business Name" value="<?= $i['mail_from_name'] ?>" required></td>
                        </tr>
                        <tr id="mail_ms365_note" class="<?= $mailConnectionType === 2 ? '' : 'd-none' ?>">
                            <td colspan="5">
                                <div class="note note-info small mb-0">
                                    Microsoft 365 uses Microsoft Graph. The Azure app needs application permission
                                    Mail.Send with admin consent, and the From address must be a mailbox the app is
                                    allowed to send as.
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <th>Test Email Address</th>
                            <th>Test Email Name</th>
                            <th colspan="3"></th>
                        </tr>
                        <tr>
                            <td><input id="mail_test_address" class="form-control" type="text" name="mail_test_address"
                                    placeholder="your email address" value="<?= $i['mail_test_address'] ?>" required>
                            </td>
                            <td><input id="mail_test_name" class="form-control" type="text" name="mail_test_name"
                                    placeholder="Your Name" value="<?= $i['mail_test_name'] ?>" required></td>
                            <td colspan="3" class="text-center">
                                <a href="javascript:void(0)" class="btn btn-success waves-effect"
                                    onclick="saveMailPrefs()"><i class="fad fa-save"></i> Save</a>
                                <a href="javascript:void(0)" class="btn btn-info waves-effect"
                                    onclick="testMailPrefs()"><i class="fad fa-envelope-open-text"></i> Test</a>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-12 col-md-6 mb-3">
        <div class="card">
            <div class="card-header table-dark text-light" data-help-topic="system_tenant_api">Tenant API Access</div>
            <div class="card-body">
                <table class="table table-bordered">
                    <tbody>
                        <tr>
                            <td style="width:220px">API status</td>
                            <td>
                                <div id="tenantApiStatus" class="small text-muted">Checking API access...</div>
                                <div id="tenantApiKeyPanel" class="d-none mt-3" style="max-width:760px">
                                    <label class="form-label mb-2">New API key</label>
                                    <div class="input-group mb-2">
                                        <input id="tenantApiKeyValue" type="text" class="form-control" readonly>
                                        <button type="button" class="btn btn-secondary m-0 px-3 py-2"
                                            onclick="copyTenantApiKey()" data-mdb-tooltip-init data-mdb-placement="top"
                                            data-mdb-trigger="hover" title="Copy API key">
                                            <i class="fad fa-copy"></i>
                                        </button>
                                    </div>
                                    <div class="note note-warning small mb-0">
                                        This key is shown once. Store it before leaving this page.
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td>Access scope</td>
                            <td>
                                This key gives read-only access to this tenant's clients, sites, assets, and reports
                                through the
                                EnRep Client API.
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2" class="text-center">
                                <a href="javascript:void(0)" id="tenantApiGenerateButton"
                                    class="btn btn-success waves-effect" onclick="generateTenantApiKey()"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                    title="Generate or replace the tenant API key">
                                    <i class="fad fa-key"></i> Generate API key
                                </a>
                                <a href="javascript:void(0)" id="tenantApiDisableButton"
                                    class="btn btn-danger waves-effect d-none" onclick="disableTenantApiKey()"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                    title="Disable the tenant API key">
                                    <i class="fad fa-ban"></i> Disable API
                                </a>
                                <a href="<?= ROOT_URL ?>/functions/api_manual.php?tenant=<?= urlencode(TENANT_URL) ?>"
                                    id="tenantApiManualButton" class="btn btn-info waves-effect d-none"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                    title="Download the EnRep Client API manual">
                                    <i class="fad fa-file-download"></i> Download manual
                                </a>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-12 col-md-6 mb-3">
        <div class="card">
            <div class="card-header table-dark text-light" data-help-topic="system_nfc">NFC Enable</div>
            <div class="card-body">
                <table class="table table-bordered">

                    <tbody>
                        <tr>
                            <td>
                                <div class="form-switch">
                                    <input type="checkbox" class="form-check-input" id="nfc_switch" name="nfcMode"
                                        value="1" <?= $i['nmode'] == '1' ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="nfc_switch">
                                        <span id="nfc_label"><?= $i['nmode'] == '1' ? 'On' : 'Off' ?></span>
                                    </label>
                                </div>

                                <script>
                                // Toggle label based on switch state
                                document.getElementById('nfc_switch').addEventListener('change', function() {
                                    var label = document.getElementById('nfc_label');
                                    label.textContent = this.checked ? 'On' : 'Off';
                                    this.value = this.checked ? '1' : '0';
                                });
                                </script>
                            </td>
                        </tr>
                        <tr>
                            <td class="text-center">
                                <a href="javascript:void(0)" class="btn btn-success waves-effect" onclick="saveNMode()">
                                    <i class="fad fa-save"></i> Save
                                </a>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-12 col-lg-6 mb-3 ">
        <div class="card">
            <div class="card-header table-dark text-light" data-help-topic="system_portal">Client Portal</div>

            <div class="card-body">
                <p class="text-muted small mb-3">
                    Choose the modules clients can use and apply your company branding across the Client Portal and
                    report preview system.
                </p>
                <table class="table table-bordered">

                    <tbody>

                        <tr>
                            <td colspan="2">
                                <div class="row g-3">
                                    <div class="col-12 col-md-6">
                                        <div class="form-check m-0">
                                            <input class="form-check-input" type="checkbox" id="cp_request_visit"
                                                <?= !empty($clientPortalSettings['request_visit']) ? 'checked' : '' ?>>
                                            <label class="form-check-label" for="cp_request_visit">Request a
                                                Visit</label>
                                        </div>
                                    </div>
                                    <div class="col-12 col-md-6">
                                        <div class="form-check m-0">
                                            <input class="form-check-input" type="checkbox" id="cp_report_fault"
                                                <?= !empty($clientPortalSettings['report_fault']) ? 'checked' : '' ?>>
                                            <label class="form-check-label" for="cp_report_fault">Report a Fault</label>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <div class="row g-4 align-items-start">
                                    <div class="col-12 col-lg-4">
                                        <label class="form-label" for="cp_nav_background">Navigation background</label>
                                        <div class="input-group" style="max-width:220px">
                                            <span class="input-group-text">#</span>
                                            <input type="text" id="cp_nav_background" class="form-control" maxlength="6"
                                                pattern="[0-9a-fA-F]{6}"
                                                value="<?= htmlspecialchars((string)$clientPortalSettings['nav_background'], ENT_QUOTES, 'UTF-8'); ?>">
                                            <span class="input-group-text p-1">
                                                <span id="cp_nav_background_swatch"
                                                    style="display:inline-block;width:28px;height:28px;border-radius:4px;border:1px solid rgba(0,0,0,.2);background-color:#<?= htmlspecialchars((string)$clientPortalSettings['nav_background'], ENT_QUOTES, 'UTF-8'); ?>"></span>
                                            </span>
                                        </div>
                                        <div id="cp_nav_background_picker" class="color-picker mt-2"
                                            data-mdb-color-picker-init data-mdb-color-picker-copy-icon="false"
                                            data-mdb-color-picker-dropdown="true" data-mdb-color-picker-type="hex"
                                            data-mdb-color-picker-value="#<?= htmlspecialchars((string)$clientPortalSettings['nav_background'], ENT_QUOTES, 'UTF-8'); ?>">
                                        </div>
                                    </div>
                                    <div class="col-12 col-lg-8">
                                        <label class="form-label">Navigation logo</label>
                                        <div style="max-width:440px">
                                            <div class="slim" data-ratio="16:6" data-did-remove="brandingImageRemoved"
                                                data-label="Client Portal Logo" data-force-type="png"
                                                data-service="images/branding_save.php" data-filter-sharpen="20"
                                                data-push="true" data-meta-userid="1234" data-meta-imageid="branding"
                                                data-size="330,120">
                                                <?php if (file_exists('images/company/branding/branding.png')) { ?>
                                                <img src="images/company/branding/branding.png?<?= rand() ?>"
                                                    alt="Client portal logo">
                                                <?php } elseif (file_exists('images/company/branding/branding.jpg')) { ?>
                                                <img src="images/company/branding/branding.jpg?<?= rand() ?>"
                                                    alt="Client portal logo">
                                                <?php } ?>
                                                <input type="file" name="file" />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2" class="text-center">
                                <a href="javascript:void(0)" class="btn btn-success waves-effect"
                                    onclick="saveClientPortalSettings()" data-mdb-tooltip-init data-mdb-placement="top"
                                    data-mdb-trigger="hover" title="Save client portal feature settings">
                                    <i class="fad fa-save"></i> Save
                                </a>
                                <span id="client_portal_settings_save" class="text-success ms-3"
                                    style="display:none">Saved</span>
                                <input type="hidden" id="client_portal_settings"
                                    value="<?= htmlspecialchars((string)($i['client_portal_settings'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>">
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-12 col-md-6 col-lg-3 mb-3 ">
        <div class="card">
            <div class="card-header table-dark text-light" data-help-topic="system_repimage">Report Images</div>

            <div class="card-body">
                <table class="table table-bordered">
                    <tbody>
                        <tr>
                            <td style="width:120px">Main logo</td>
                            <td>
                                <input type="text" id="ri_main_logo" class="form-control" maxlength="2"
                                    inputmode="numeric"
                                    value="<?= htmlspecialchars((string)$reportImageSettings['main_logo'], ENT_QUOTES, 'UTF-8'); ?>"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                    title="Two digit height for the main company logo">
                            </td>
                        </tr>
                        <tr>
                            <td>Client logo</td>
                            <td>
                                <input type="text" id="ri_client_logo" class="form-control" maxlength="2"
                                    inputmode="numeric"
                                    value="<?= htmlspecialchars((string)$reportImageSettings['client_logo'], ENT_QUOTES, 'UTF-8'); ?>"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                    title="Two digit height for the client logo">
                            </td>
                        </tr>
                        <tr>
                            <td>Affiliation logo</td>
                            <td>
                                <input type="text" id="ri_affiliation_logo" class="form-control" maxlength="2"
                                    inputmode="numeric"
                                    value="<?= htmlspecialchars((string)$reportImageSettings['affiliation_logo'], ENT_QUOTES, 'UTF-8'); ?>"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                    title="Two digit height for the affiliation logos">
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2" class="text-center">
                                <a href="javascript:void(0)" class="btn btn-success waves-effect"
                                    onclick="saveReportImageSettings()" data-mdb-tooltip-init data-mdb-placement="top"
                                    data-mdb-trigger="hover" title="Save report image size settings">
                                    <i class="fad fa-save"></i> Save
                                </a>
                                <span id="report_image_settings_save" class="text-success ms-3"
                                    style="display:none">Saved</span>
                                <input type="hidden" id="report_image_settings"
                                    value="<?= htmlspecialchars((string)($i['report_image_settings'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>">
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-12 col-md-6 col-lg-3 mb-3">
        <div class="card h-100">
            <div class="card-header table-dark text-light" data-help-topic="system_spellcheck">Spellchecker</div>

            <div class="card-body">
                <table class="table table-bordered mb-0">
                    <tbody>
                        <tr>
                            <td>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="spellcheck_enabled"
                                        value="<?= $spellcheckEnabled ? '1' : '0' ?>"
                                        <?= $spellcheckEnabled ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="spellcheck_enabled">
                                        <span id="spellcheck_enabled_label"><?= $spellcheckEnabled ? 'On' : 'Off' ?></span>
                                    </label>
                                </div>
                                <p class="text-muted small mb-0 mt-2">
                                    Enables report spelling review and the custom dictionary manager.
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <td class="text-center">
                                <a href="javascript:void(0)" class="btn btn-success waves-effect"
                                    onclick="saveSpellcheckSettings()" data-mdb-tooltip-init data-mdb-placement="top"
                                    data-mdb-trigger="hover" title="Save spellchecker setting">
                                    <i class="fad fa-save"></i> Save
                                </a>
                                <span id="spellcheck_enabled_save" class="text-success ms-3"
                                    style="display:none">Saved</span>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-12 mb-3">
        <div class="card">
            <div class="card-header table-dark text-light">
                <strong>Asset schedule table columns</strong><br>
                Toggle which columns are shown and rename the column headings for the asset schedule.
                <div class="mt-2 text-warning">
                    <i class="fad fa-triangle-exclamation"></i>
                    <strong>Warning:</strong> showing too many columns may cause layout issues on
                    smaller
                    screens.
                    If the table becomes cramped, reduce the number of visible columns.
                </div>
            </div>
            <div class="card-body">

                <input type="hidden" id="asset_table_prefs"
                    value="<?= htmlspecialchars((string)($i['asset_table_prefs'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>">

                <div class="card">
                    <div class="card-header table-dark text-light" data-help-topic="system_asset_columns">
                        Asset columns
                    </div>
                    <div class="card-body">
                        <div class="row g-2" id="assetCols">
                            <?php foreach ($assetDefaults as $key => $definition):
                                $defLabel = $definition['label'] ?? $key;
                                $label    = $assetPrefs[$key]['label'] ?? $defLabel;
                                $vis      = !empty($assetPrefs[$key]['visible']);
                            ?>
                            <div class="col-12 col-md-6 col-xl-3"
                                data-key="<?= htmlspecialchars($key, ENT_QUOTES, 'UTF-8'); ?>">
                                <div class="asset-column-control border rounded px-2 py-2 h-100">
                                    <span class="badge bg-secondary text-nowrap asset-column-name"
                                        title="<?= htmlspecialchars($defLabel, ENT_QUOTES, 'UTF-8'); ?>">
                                        <?= htmlspecialchars($defLabel, ENT_QUOTES, 'UTF-8'); ?>
                                    </span>

                                    <input type="text" class="form-control form-control-sm asset-col-label"
                                        value="<?= htmlspecialchars((string)$label, ENT_QUOTES, 'UTF-8'); ?>"
                                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                        title="Rename the column label">

                                    <div class="form-check form-switch m-0 ms-auto">
                                        <input class="form-check-input asset-col-visible" type="checkbox"
                                            <?= $vis ? 'checked' : '' ?> data-mdb-tooltip-init
                                            data-mdb-placement="top" data-mdb-trigger="hover"
                                            title="Show/hide this column">
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <div class="text-center mt-3">
                    <a href="javascript:void(0)" class="btn btn-success waves-effect me-2"
                        onclick="saveAssetTablePrefs()" data-mdb-tooltip-init data-mdb-placement="top"
                        data-mdb-trigger="hover" title="Save column visibility and labels">
                        <i class="fad fa-save"></i> Save
                    </a>

                    <a href="javascript:void(0)" class="btn btn-secondary waves-effect" onclick="resetAssetTablePrefs()"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                        title="Restore default column labels and show all">
                        <i class="fad fa-rotate-left"></i> Reset to defaults
                    </a>

                    <span id="asset_table_prefs_save" class="text-success ms-3" style="display:none">Saved</span>
                </div>

            </div>
        </div>
    </div>
</div>

<div class="row">

    <div class="col-12 col-md-4 mb-3 ">
        <div class="card">
            <div class="card-header table-dark text-light" data-help-topic="system_email_subject">Default reporting email subject</div>
            <div class="card-body">
                <table class="table table-bordered">
                    <tbody>
                        <tr>
                            <td colspan="2">
                                <div class="input-group">
                                    <input class="form-control" type="text" id="default_email_report_subject"
                                        value="<?= htmlspecialchars((string)($i['default_email_report_subject'] ?: 'Your ' . strtoupper($_SESSION['company']) . ' inspection reports'), ENT_QUOTES, 'UTF-8'); ?>">
                                    <button class="btn btn-success m-0 px-3 py-2 waves-effect" type="button"
                                        onClick="updateSetting('default_email_report_subject','string','Default reporting email subject saved.')">
                                        <i class="fad fa-save"></i>
                                    </button>
                                </div>
                                <span id="default_email_report_subject_save" class="text-success"
                                    style="display:none">Saved</span>
                                <p id="default_email_error" class="text-danger"></p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-12 col-md-8 mb-3 ">
        <div class="card">
            <div class="card-header table-dark text-light" data-help-topic="system_email_message">Default reporting email message</div>
            <div class="card-body">
                <table class="table table-bordered">
                    <tbody>
                        <tr>
                            <td colspan="2">
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox"
                                        id="default_email_report_message_enabled"
                                        <?= !empty($defaultEmailReportMessageSettings['enabled']) ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="default_email_report_message_enabled">
                                        Use this message when sending delivery emails
                                    </label>
                                </div>
                                <input type="hidden" id="default_email_report_message_token"
                                    value="<?= htmlspecialchars((string)$defaultEmailReportMessageSettings['token'], ENT_QUOTES, 'UTF-8'); ?>">
                                <input type="hidden" id="default_email_report_message" value="">
                                <div class="alert alert-info py-2 mb-3">
                                    Add dynamic fields to the email message. They are replaced when delivery
                                    emails are
                                    prepared.
                                    Click a field to insert it at the current cursor position.
                                    <div class="mt-2">
                                        <button type="button" class="btn btn-sm btn-light me-2"
                                            onclick="insertDefaultEmailToken('[CLIENT_NAME]')">[CLIENT_NAME]</button>
                                        <button type="button" class="btn btn-sm btn-light me-2"
                                            onclick="insertDefaultEmailToken('[LOCATION_NAME]')">[LOCATION_NAME]</button>
                                        <button type="button" class="btn btn-sm btn-light"
                                            onclick="insertDefaultEmailToken('[DATE_RANGE]')">[DATE_RANGE]</button>
                                    </div>
                                </div>
                                <div class="input-group">
                                    <textarea class="form-control" id="default_email_report_message_text"
                                        rows="4"><?= htmlspecialchars((string)$defaultEmailReportMessageSettings['message'], ENT_QUOTES, 'UTF-8'); ?></textarea>
                                    <button class="btn btn-success m-0 px-3 py-2 waves-effect" type="button"
                                        onClick="saveDefaultEmailReportMessage()">
                                        <i class="fad fa-save"></i>
                                    </button>
                                </div>
                                <span id="default_email_report_message_save" class="text-success"
                                    style="display:none">Saved</span>
                                <p id="default_email_error" class="text-danger"></p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
<?php if ($i['mail_check'] == 1) { ?>
$('#verified').html('<span style="color:green">Verified</span>')
<?php } else { ?>$('#verified').html('<span style="color:red">Not Verified</span>')
<?php } ?>

// Save database preferences
function saveDbPrefs() {
    const u = document.getElementById('db_username').value;
    const p = document.getElementById('db_password').value;
    const t = document.getElementById('db_tables').value;
    const m = document.getElementById('db_master').value;

    if (!u || !p || !t) {
        showResponse('danger', 'You must complete all fields');
    } else {
        const params = new URLSearchParams({
            FCN: 'updateDB',
            db_username: u,
            db_password: p,
            db_tables: t,
            db_master: m
        });

        fetch(ROOT_URL + '/includes/master/system_functions.php', {
                method: 'POST',
                body: params,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })
            .then(response => response.text())
            .then(res => {
                if (res.trim() === "success") {
                    showResponse('success', 'The database settings have been saved');
                } else {
                    console.log(res);
                }
            });
    }
}

// Save site path preferences
function saveSitePath() {
    const s = document.getElementById('site_path').value;

    if (!s) {
        showResponse('danger', 'You must complete all fields');
    } else {
        const params = new URLSearchParams({
            FCN: 'updateSitePath',
            site_path: s,
            tenant: TENANT_URL
        });

        fetch(ROOT_URL + '/includes/master/system_functions.php', {
                method: 'POST',
                body: params,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })
            .then(response => response.text())
            .then(res => {
                if (res.trim() === "success") {
                    showResponse('success', 'The site path settings have been saved');
                } else {
                    console.log(res);
                }
            });
    }
}

// Toggle mail password visibility
function toggleMailPasswordVisibility() {
    const passwordField = document.getElementById('mail_password');
    const toggleButton = document.getElementById('mail_password_toggle');
    const toggleIcon = document.getElementById('mail_password_toggle_icon');
    const isHidden = passwordField.type === 'password';

    passwordField.type = isHidden ? 'text' : 'password';
    toggleButton.setAttribute('aria-label', isHidden ? 'Hide mail password' : 'Show mail password');
    toggleButton.setAttribute('title', isHidden ? 'Hide password' : 'Show password');
    toggleIcon.className = isHidden ? 'fad fa-eye-slash' : 'fad fa-eye';
}

function updateMailConnectionLabels() {
    const mt = document.querySelector('input[name="mail_type"]:checked')?.value || '1';
    const isMicrosoft365 = mt === '2';

    document.getElementById('mail_host_label').textContent = isMicrosoft365 ? 'Directory (tenant) ID' :
        'Mail server';
    document.getElementById('mail_username_label').textContent = isMicrosoft365 ? 'Application (client) ID' :
        'Mail Username';
    document.getElementById('mail_password_label').textContent = isMicrosoft365 ? 'Client secret value' :
        'Mail Password';
    document.getElementById('mail_host').placeholder = isMicrosoft365 ? 'Directory (tenant) ID' :
        'mail.yourdomain.com';
    document.getElementById('mail_username').placeholder = isMicrosoft365 ? 'Application (client) ID' :
        'full username';
    document.getElementById('mail_password').placeholder = isMicrosoft365 ? 'Client secret value' : '';
    document.getElementById('mail_ms365_note').classList.toggle('d-none', !isMicrosoft365);
}

document.querySelectorAll('input[name="mail_type"]').forEach((input) => {
    input.addEventListener('change', updateMailConnectionLabels);
});
updateMailConnectionLabels();

function persistMailConnectionType(mt) {
    const params = new URLSearchParams({
        FCN: 'update',
        col: 'mail_type',
        val: mt,
        tenant: TENANT_URL
    });

    return fetch(ROOT_URL + '/includes/master/system_functions.php', {
        method: 'POST',
        body: params,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
}

// Save mail preferences
function saveMailPrefs(showMessage = true) {
    const mt = document.querySelector('input[name="mail_type"]:checked').value;
    const h = document.getElementById('mail_host').value;
    const u = document.getElementById('mail_username').value;
    const p = document.getElementById('mail_password').value;
    const f = document.getElementById('mail_from').value;
    const fn = document.getElementById('mail_from_name').value;
    const t = document.getElementById('mail_test_address').value;
    const tn = document.getElementById('mail_test_name').value;

    if (!h || !u || !p || !f || !fn || !t || !tn) {
        showResponse('danger', 'You must complete all fields');
        return Promise.reject(new Error('Missing mail settings'));
    } else {
        const params = new URLSearchParams({
            FCN: 'updateMailer',
            mail_type: mt,
            mail_host: h,
            mail_username: u,
            mail_password: p,
            mail_from: f,
            mail_from_name: fn,
            mail_test_address: t,
            mail_test_name: tn,
            tenant: TENANT_URL
        });

        return fetch(ROOT_URL + '/includes/master/system_functions.php', {
                method: 'POST',
                body: params,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })
            .then(response => response.text())
            .then(res => {
                if (res.trim() === "success") {
                    return persistMailConnectionType(mt).then(() => {
                        if (showMessage) {
                            showResponse('success', 'The mail settings have been saved');
                        }
                    });
                } else {
                    console.log(res);
                    throw new Error(res);
                }
            });
    }
}

// Test mail preferences
function testMailPrefs() {
    const mt = document.querySelector('input[name="mail_type"]:checked').value;
    const h = document.getElementById('mail_host').value;
    const u = document.getElementById('mail_username').value;
    const p = document.getElementById('mail_password').value;
    const f = document.getElementById('mail_from').value;
    const fn = document.getElementById('mail_from_name').value;
    const t = document.getElementById('mail_test_address').value;
    const tn = document.getElementById('mail_test_name').value;

    if (!h || !u || !p || !f || !fn || !t || !tn) {
        showResponse('danger', 'You must complete all fields');
        return;
    }

    if (mt === '2') {
        saveMailPrefs(false).then(() => {
            const params = new URLSearchParams({
                tenant: TENANT_URL,
                recipient_1: t,
                subject: 'EnRep test email',
                message: 'This is testing the Microsoft 365 email connection.',
                reference: 'system-mail-test',
                source_1: 'System Test'
            });

            return fetch(ROOT_URL + '/functions/sendmail.php', {
                method: 'POST',
                body: params,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            });
        }).then(response => response.text())
        .then(res => {
            let data = null;
            try {
                const jsonStart = res.indexOf('{');
                const jsonEnd = res.lastIndexOf('}');
                data = JSON.parse(jsonStart >= 0 && jsonEnd >= jsonStart ? res.substring(jsonStart, jsonEnd + 1) :
                    res);
            } catch (e) {}

            if (data && data.status === 'success') {
                showResponse('success', 'The mail settings have been accepted');
                document.getElementById('verified').innerHTML = '<span style="color:green">Verified</span>';
            } else {
                document.getElementById('verified').innerHTML =
                    `<span style="color:red">Not Verified: ${(data && data.message) ? data.message : res}</span>`;
            }
        }).catch(error => {
            document.getElementById('verified').innerHTML =
                `<span style="color:red">Not Verified: ${error.message}</span>`;
        });
        return;
    }

    const params = new URLSearchParams({
        FCN: 'testMailer',
        mail_type: mt,
        mail_host: h,
        mail_username: u,
        mail_password: p,
        mail_from: f,
        mail_from_name: fn,
        mail_test_address: t,
        mail_test_name: tn,
        tenant: TENANT_URL
    });

    fetch(ROOT_URL + '/includes/master/system_functions.php', {
            method: 'POST',
            body: params,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => response.text())
        .then(res => {
            if (res.trim() === "success") {
                showResponse('success', 'The mail settings have been accepted');
                document.getElementById('verified').innerHTML = '<span style="color:green">Verified</span>';
                saveMailPrefs();
            } else {
                document.getElementById('verified').innerHTML =
                    `<span style="color:red">Not Verified: ${res}</span>`;
            }
        });
}

// Email validation check
function checkEmail() {
    const emailStatus = document.getElementById('default_email_status');
    const emailField = document.getElementById('default_email');
    const emailError = document.getElementById('default_email_error');
    const emailButton = document.getElementById('default_email_button');

    if (emailStatus.checked) {
        if (!emailField.value) {
            emailField.style.borderColor = '#f00';
            emailError.textContent = 'You must add a valid email address to enable this feature';
            emailButton.classList.add('disabled');
        } else {
            valEml();
        }
    } else {
        emailField.style.borderColor = '';
        emailField.value = '';
        emailError.textContent = '';
        emailButton.classList.add('disabled');
        updateSetting('default_email', 'string');
    }
}

// Validate email format
function valEml() {
    const sEmail = document.getElementById('default_email').value;
    const emailError = document.getElementById('default_email_error');
    const emailField = document.getElementById('default_email');
    const emailButton = document.getElementById('default_email_button');

    if (validatedEmail(sEmail)) {
        emailError.textContent = 'Email address accepted';
        emailError.style.color = 'green';
        emailField.style.borderColor = 'green';
        emailButton.classList.remove('disabled');
    } else {
        emailError.textContent = 'You must add a valid email address to enable this feature';
        emailField.style.borderColor = '#f00';
        emailError.style.color = '#f00';
        emailButton.classList.add('disabled');
    }
}

// Update settings
function updateSetting(i, t, successMessage = '') {
    let state;
    if (t === "toggle") {
        state = [
            document.getElementById('default_email_status').checked ? '1' : '0',
            document.getElementById('opt_report').checked ? '1' : '0',
            document.getElementById('opt_schedule').checked ? '1' : '0',
            document.getElementById('opt_defect').checked ? '1' : '0',
            document.getElementById('opt_user').checked ? '1' : '0',
            document.getElementById('opt_system').checked ? '1' : '0'
        ].join(',');
        i = 'admin_notices';
    } else if (t === "string") {
        state = document.getElementById(i).value;
    }

    const params = new URLSearchParams({
        FCN: 'update',
        col: i,
        val: state,
        tenant: TENANT_URL
    });

    fetch(ROOT_URL + '/includes/master/system_functions.php', {
            method: 'POST',
            body: params,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => response.text())
        .then(() => {
            document.getElementById(`${i}_save`).style.display = 'inline';
            setTimeout(() => {
                document.getElementById(`${i}_save`).style.display = 'none';
            }, 1000);

            if (successMessage !== '' && typeof showResponse === 'function') {
                showResponse('success', successMessage);
            }
        });
}

const tenantApiEndpoint = ROOT_URL + '/functions/system_api_key.php';

function tenantApiDate(value) {
    const intValue = Number(value || 0);
    if (!intValue) return 'Never';
    return new Date(intValue * 1000).toLocaleString('en-GB');
}

function setTenantApiBusy(isBusy) {
    document.getElementById('tenantApiGenerateButton').classList.toggle('disabled', isBusy);
    document.getElementById('tenantApiDisableButton').classList.toggle('disabled', isBusy);
}

function updateTenantApiCard(data) {
    const status = document.getElementById('tenantApiStatus');
    const disableButton = document.getElementById('tenantApiDisableButton');
    const generateButton = document.getElementById('tenantApiGenerateButton');
    const manualButton = document.getElementById('tenantApiManualButton');
    const keyPanel = document.getElementById('tenantApiKeyPanel');
    const keyValue = document.getElementById('tenantApiKeyValue');

    if (!data.ok) {
        status.innerHTML = `<span class="text-danger">${data.error || 'API access unavailable'}</span>`;
        disableButton.classList.add('d-none');
        manualButton.classList.add('d-none');
        generateButton.classList.toggle('d-none', !!data.setup_required);
        keyPanel.classList.add('d-none');
        keyValue.value = '';
        return;
    }

    if (!data.configured) {
        status.innerHTML = '<span class="text-warning">No tenant API key has been generated.</span>';
        disableButton.classList.add('d-none');
        manualButton.classList.add('d-none');
        generateButton.innerHTML = '<i class="fad fa-key"></i> Generate API key';
        keyPanel.classList.add('d-none');
        keyValue.value = '';
        return;
    }

    const enabledText = data.enabled ?
        '<span class="text-success">Enabled</span>' :
        '<span class="text-danger">Disabled</span>';
    status.innerHTML = `
            <div><strong>Status:</strong> ${enabledText}</div>
            <div><strong>Key prefix:</strong> ${data.key_prefix || ''}</div>
            <div><strong>Generated:</strong> ${tenantApiDate(data.regenerated_at || data.created_at)}</div>
            <div><strong>Last used:</strong> ${tenantApiDate(data.last_used_at)}</div>
        `;

    disableButton.classList.toggle('d-none', !data.enabled);
    manualButton.classList.toggle('d-none', !data.enabled);
    generateButton.innerHTML = '<i class="fad fa-sync-alt"></i> Regenerate API key';
    if (!data.api_key) {
        keyPanel.classList.add('d-none');
        keyValue.value = '';
    }
}

function tenantApiRequest(action) {
    const params = new URLSearchParams({
        tenant: TENANT_URL,
        action
    });

    return fetch(tenantApiEndpoint, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params.toString()
    }).then((response) => response.json().then((data) => {
        if (!response.ok && data.ok !== true) {
            return data;
        }
        return data;
    }));
}

function loadTenantApiStatus() {
    tenantApiRequest('status')
        .then(updateTenantApiCard)
        .catch(() => updateTenantApiCard({
            ok: false,
            error: 'API access unavailable'
        }));
}

function generateTenantApiKey() {
    const dest =
        '<p>Generate a new tenant API key?</p><p class="text-danger mb-0">Any previous key will stop working.</p>';
    loadModalContent(dest, 'tenantApiConfirmBox', 'modal-md', 1060, 'true', 'Generate API Key', 'cancelConfirm',
        generateTenantApiKeyConfirm);
}

function generateTenantApiKeyConfirm() {
    setTenantApiBusy(true);
    tenantApiRequest('generate')
        .then((data) => {
            if (!data.ok) {
                document.getElementById('tenantApiKeyPanel').classList.add('d-none');
                document.getElementById('tenantApiKeyValue').value = '';
            }
            if (data.api_key) {
                document.getElementById('tenantApiKeyValue').value = data.api_key;
                document.getElementById('tenantApiKeyPanel').classList.remove('d-none');
            }
            updateTenantApiCard(data);
            showResponse(data.ok ? 'success' : 'danger', data.ok ? 'API key generated successfully' : (data
                .error ||
                'API key generation failed'));
            $('.modal.show').modal('hide');
        })
        .catch(() => {
            updateTenantApiCard({
                ok: false,
                error: 'API key generation failed'
            });
            showResponse('danger', 'API key generation failed');
        })
        .finally(() => setTenantApiBusy(false));
}

function disableTenantApiKey() {
    const dest =
        '<p>Disable tenant API access?</p><p class="text-danger mb-0">Existing integrations using this key will stop working.</p>';
    loadModalContent(dest, 'tenantApiConfirmBox', 'modal-md', 1060, 'true', 'Disable API Access',
        'cancelConfirm',
        disableTenantApiKeyConfirm);
}

function disableTenantApiKeyConfirm() {
    setTenantApiBusy(true);
    tenantApiRequest('disable')
        .then((data) => {
            document.getElementById('tenantApiKeyPanel').classList.add('d-none');
            document.getElementById('tenantApiKeyValue').value = '';
            updateTenantApiCard(data);
            showResponse(data.ok ? 'success' : 'danger', data.ok ? 'API access disabled' : (data.error ||
                'API access could not be disabled'));
            $('.modal.show').modal('hide');
        })
        .catch(() => {
            updateTenantApiCard({
                ok: false,
                error: 'API access could not be disabled'
            });
            showResponse('danger', 'API access could not be disabled');
        })
        .finally(() => setTenantApiBusy(false));
}

function copyTenantApiKey() {
    const input = document.getElementById('tenantApiKeyValue');
    input.select();
    input.setSelectionRange(0, 99999);
    navigator.clipboard.writeText(input.value).then(() => showResponse('success', 'API key copied'));
}

loadTenantApiStatus();

// Save schedule mode
function saveSMode() {
    const m = document.querySelector('input[name="scheduleMode"]').value;

    const params = new URLSearchParams({
        FCN: 'saveSMode',
        mode: m,
        tenant: TENANT_URL
    });

    fetch(ROOT_URL + '/includes/master/system_functions.php', {
            method: 'POST',
            body: params,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => response.text())
        .then(res => {
            if (res.trim() === "success") {
                showResponse('success', 'The schedule settings have been saved');
            } else {
                console.log(res);
            }
        });
}

function saveNMode() {
    const m = document.querySelector('input[name="nfcMode"]').value;

    const params = new URLSearchParams({
        FCN: 'saveNMode',
        mode: m,
        tenant: TENANT_URL
    });

    fetch(ROOT_URL + '/includes/master/system_functions.php', {
            method: 'POST',
            body: params,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => response.text())
        .then(res => {
            if (res.trim() === "success") {
                showResponse('success', 'The NFC settings have been saved');
            } else {
                console.log(res);
            }
        });
}

// Update navigation box content
document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item">Tools <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">System Setup</li>';
</script>

<script>
const ASSET_TABLE_DEFAULTS = {
    description: {
        label: 'Description',
        visible: true
    },
    manufacturer: {
        label: 'Manufacturer',
        visible: true
    },
    make_model: {
        label: 'Make/Model',
        visible: true
    },
    condition: {
        label: 'Condition',
        visible: true
    },
    plantnumber: {
        label: 'Plant No.',
        visible: true
    },
    serialnumber: {
        label: 'Serial',
        visible: true
    },
    locname: {
        label: 'Location',
        visible: true
    },
    subloc: {
        label: 'Sub-location',
        visible: true
    },
    postcode: {
        label: 'Post Code',
        visible: true
    },
    lastReport: {
        label: 'Result',
        visible: true
    },
    duedate: {
        label: 'Due',
        visible: true
    },
    actions: {
        label: 'Actions',
        visible: true
    }
};

function buildAssetPrefsFromUI() {
    const prefs = {};

    document.querySelectorAll('#assetCols [data-key]').forEach((wrap) => {
        const key = wrap.getAttribute('data-key');
        if (!key) return;

        const vis = !!wrap.querySelector('.asset-col-visible')?.checked;
        const lbl = String(wrap.querySelector('.asset-col-label')?.value ?? '').trim();

        prefs[key] = {
            visible: vis,
            label: lbl !== '' ? lbl : (ASSET_TABLE_DEFAULTS[key]?.label || key)
        };
    });

    // Actions is mandatory (not shown in UI)
    prefs.actions = {
        label: 'Actions',
        visible: true
    };

    return prefs;
}

function saveAssetTablePrefs() {
    const prefs = buildAssetPrefsFromUI();
    document.getElementById('asset_table_prefs').value = JSON.stringify(prefs);

    updateSetting('asset_table_prefs', 'string');

    // optional user feedback using your standard response (if present)
    if (typeof showResponse === 'function') {
        showResponse('success', 'Asset schedule table columns saved.');
    }
}

function resetAssetTablePrefs() {
    document.querySelectorAll('#assetCols [data-key]').forEach((wrap) => {
        const key = wrap.getAttribute('data-key');
        const def = ASSET_TABLE_DEFAULTS[key];
        if (!def) return;

        const cb = wrap.querySelector('.asset-col-visible');
        const inp = wrap.querySelector('.asset-col-label');

        if (cb) cb.checked = !!def.visible;
        if (inp) inp.value = String(def.label || '');
    });
}

function saveClientPortalSettings() {
    const navBackground = getClientPortalSelectedHex();

    const settings = {
        request_visit: document.getElementById('cp_request_visit').checked ? 1 : 0,
        report_fault: document.getElementById('cp_report_fault').checked ? 1 : 0,
        nav_background: navBackground
    };

    document.getElementById('cp_nav_background').value = navBackground;
    document.getElementById('cp_nav_background_picker').setAttribute('data-mdb-color-picker-value', '#' +
        navBackground);
    updateClientPortalColourSwatch(navBackground);
    document.getElementById('client_portal_settings_save').style.display = 'none';
    document.getElementById('client_portal_settings').value = JSON.stringify(settings);

    updateSetting('client_portal_settings', 'string');

    if (typeof showResponse === 'function') {
        showResponse('success', 'Client portal settings saved.');
    }
}

function normaliseClientPortalHex(value, fallback = '2b4055') {
    let raw = value;

    if (raw && typeof raw === 'object') {
        raw = raw.hex || raw.value || raw.rgb || '';
    }

    const v = String(raw ?? '').replace('#', '').trim();

    if (/^[0-9a-fA-F]{8}$/.test(v)) {
        return v.substring(0, 6).toLowerCase();
    }

    return /^[0-9a-fA-F]{6}$/.test(v) ? v.toLowerCase() : fallback;
}

function updateClientPortalColourSwatch(value) {
    const swatch = document.getElementById('cp_nav_background_swatch');
    if (!swatch) return;

    const hex = normaliseClientPortalHex(value, '2b4055');
    swatch.style.backgroundColor = '#' + hex;
}

function getClientPortalPickerColour() {
    const picker = document.getElementById('cp_nav_background_picker');
    const pickerInput = picker ? picker.querySelector('input') : null;

    return pickerInput?.value || picker?.getAttribute('data-mdb-color-picker-value') || '';
}

function getClientPortalSelectedHex() {
    const input = document.getElementById('cp_nav_background');
    const inputHex = normaliseClientPortalHex(input?.value || '', '');

    if (inputHex !== '') {
        return inputHex;
    }

    return normaliseClientPortalHex(getClientPortalPickerColour(), '2b4055');
}

function syncClientPortalColourPicker() {
    const input = document.getElementById('cp_nav_background');
    const picker = document.getElementById('cp_nav_background_picker');

    if (!input || !picker) return;

    const applyValue = (value) => {
        const hex = normaliseClientPortalHex(value, input.value || '2b4055');
        input.value = hex;
        picker.setAttribute('data-mdb-color-picker-value', '#' + hex);
        updateClientPortalColourSwatch(hex);
    };

    applyValue(input.value);

    input.addEventListener('input', () => {
        input.value = input.value.replace(/[^0-9a-fA-F]/g, '').substring(0, 6);
        picker.setAttribute('data-mdb-color-picker-value', '#' + (input.value || '2b4055'));
        updateClientPortalColourSwatch(input.value || '2b4055');
    });

    document.querySelector('.color-picker').addEventListener('colorChanged.mdb.colorPicker', () => {
        const colourEvent = window.event || (typeof event !== 'undefined' ? event : null);
        const color = normaliseClientPortalHex(colourEvent?.color, input.value || '2b4055');
        input.value = color;
        updateClientPortalColourSwatch(color);
    });
}

function brandingImageRemoved(data) {
    $.post('images/branding_remove.php', {
        image: data?.input?.name || 'branding.jpg'
    });
}

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', syncClientPortalColourPicker);
} else {
    syncClientPortalColourPicker();
}

function normaliseTwoDigitImageValue(value, fallback = '40') {
    let v = String(value ?? '').replace(/\D/g, '').trim();

    if (v === '') {
        v = fallback;
    }

    v = String(parseInt(v, 10) || parseInt(fallback, 10));

    if (v.length > 2) {
        v = v.substring(0, 2);
    }

    return v.padStart(2, '0');
}

function saveReportImageSettings() {
    const settings = {
        main_logo: normaliseTwoDigitImageValue(document.getElementById('ri_main_logo').value, '40'),
        client_logo: normaliseTwoDigitImageValue(document.getElementById('ri_client_logo').value, '40'),
        affiliation_logo: normaliseTwoDigitImageValue(document.getElementById('ri_affiliation_logo').value,
            '40')
    };

    document.getElementById('ri_main_logo').value = settings.main_logo;
    document.getElementById('ri_client_logo').value = settings.client_logo;
    document.getElementById('ri_affiliation_logo').value = settings.affiliation_logo;

    document.getElementById('report_image_settings_save').style.display = 'none';
    document.getElementById('report_image_settings').value = JSON.stringify(settings);

    updateSetting('report_image_settings', 'string');

    if (typeof showResponse === 'function') {
        showResponse('success', 'Report image settings saved.');
    }
}

function saveSpellcheckSettings() {
    const enabled = document.getElementById('spellcheck_enabled').checked ? '1' : '0';
    document.getElementById('spellcheck_enabled').value = enabled;
    document.getElementById('spellcheck_enabled_label').textContent = enabled === '1' ? 'On' : 'Off';

    updateSetting('spellcheck_enabled', 'string', 'Spellchecker setting saved.');
}

document.getElementById('spellcheck_enabled')?.addEventListener('change', function() {
    this.value = this.checked ? '1' : '0';
    document.getElementById('spellcheck_enabled_label').textContent = this.checked ? 'On' : 'Off';
});

function saveDefaultEmailReportMessage() {
    const settings = {
        enabled: document.getElementById('default_email_report_message_enabled').checked ? 1 : 0,
        token: document.getElementById('default_email_report_message_token').value ||
            'default_reporting_email_message',
        message: document.getElementById('default_email_report_message_text').value || ''
    };

    document.getElementById('default_email_report_message_save').style.display = 'none';
    document.getElementById('default_email_report_message').value = JSON.stringify(settings);

    updateSetting('default_email_report_message', 'string', 'Default reporting email message saved.');
}

function insertDefaultEmailToken(token) {
    const textarea = document.getElementById('default_email_report_message_text');
    if (!textarea) return;

    const start = textarea.selectionStart ?? textarea.value.length;
    const end = textarea.selectionEnd ?? textarea.value.length;
    const before = textarea.value.substring(0, start);
    const after = textarea.value.substring(end);

    textarea.value = before + token + after;
    textarea.focus();
    textarea.selectionStart = textarea.selectionEnd = start + token.length;
}
</script>
