<?php
require_once __DIR__ . '/functions.php';

enrep_require_admin();

$con = $GLOBALS['con'] ?? null;
$tenantKey = defined('TENANT_URL') ? trim((string)TENANT_URL, '/') : '';
$schemaStatus = $con instanceof mysqli ? assetmanager_schema_status($con) : ['ready' => false, 'installed' => [], 'missing_required' => [], 'missing_optional' => []];
$schemaReady = !empty($schemaStatus['ready']);
$clients = $con instanceof mysqli ? assetmanager_filter_clients_by_access($con, assetmanager_active_clients($con)) : [];
$defaultSettings = assetmanager_default_settings();
$selectedClientnumber = enrep_request_int('clientnumber', 0);
$selectedClient = null;

foreach ($clients as $client) {
    if ((int)$client['clientnumber'] === $selectedClientnumber) {
        $selectedClient = $client;
        break;
    }
}
if ($selectedClient === null) {
    $selectedClientnumber = 0;
}

$selectedSettings = ($con instanceof mysqli && $schemaReady && $selectedClientnumber > 0)
    ? assetmanager_get_client_settings($con, $tenantKey, $selectedClientnumber)
    : $defaultSettings;
$modules = $selectedSettings['modules'];
$limits = $selectedSettings['limits'];
$branding = $selectedSettings['branding'];
$permissions = $selectedSettings['permissions'];
$numbering = ($con instanceof mysqli && $schemaReady && $selectedClientnumber > 0)
    ? assetmanager_get_client_sequences($con, $tenantKey, $selectedClientnumber)
    : assetmanager_default_sequences();
$itemdetailsEdit = $selectedSettings['itemdetails_edit'];
$formId = $selectedClientnumber > 0 ? 'assetmanager_client_' . $selectedClientnumber : '';
$operators = ($con instanceof mysqli && $schemaReady && $selectedClientnumber > 0)
    ? assetmanager_operator_list($con, $tenantKey, $selectedClientnumber)
    : [];

$overview = [
    'active_clients' => count($clients),
    'enabled_clients' => 0,
    'configured_clients' => 0,
    'operators' => 0,
];

if ($con instanceof mysqli && $schemaReady && assetmanager_table_exists($con, 'assetmanager_client_settings')) {
    $accessScope = assetmanager_access_scope($con);
    $where = 'tenant_key=?';
    $types = 's';
    $params = [$tenantKey];
    if (empty($accessScope['all_clients'])) {
        $allowed = array_values(array_filter(array_map('intval', $accessScope['clientnumbers'] ?? [])));
        if (count($allowed) < 1) {
            $where .= ' AND 1=0';
        } else {
            $where .= ' AND clientnumber IN (' . implode(',', array_fill(0, count($allowed), '?')) . ')';
            $types .= str_repeat('i', count($allowed));
            $params = array_merge($params, $allowed);
        }
    }
    $stmt = $con->prepare("SELECT COUNT(*) AS configured, SUM(CASE WHEN enabled='1' THEN 1 ELSE 0 END) AS enabled FROM assetmanager_client_settings WHERE {$where}");
    if ($stmt) {
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        $overview['configured_clients'] = (int)($row['configured'] ?? 0);
        $overview['enabled_clients'] = (int)($row['enabled'] ?? 0);
    }
}
if ($con instanceof mysqli && $schemaReady && assetmanager_table_exists($con, 'assetmanager_users')) {
    $stmt = $con->prepare("SELECT COUNT(*) AS total FROM assetmanager_users WHERE tenant_key=?");
    if ($stmt) {
        $stmt->bind_param('s', $tenantKey);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        $overview['operators'] = (int)($row['total'] ?? 0);
    }
}

$fieldLabels = [
    'plantnumber' => 'Plant number',
    'serialnumber' => 'Serial number',
    'manufacturer' => 'Manufacturer',
    'model' => 'Model',
    'dateofmanf' => 'Date of manufacture',
    'customer_reference' => 'Customer reference',
    'asset_tag' => 'Asset tag / NFC alias',
];
?>
<style>
.am-page { max-width: 1600px; }
.am-hero {
    border: 1px solid rgba(0,0,0,.12);
    border-radius: 8px;
    background: #fff;
    padding: 1rem 1.2rem;
}
.am-hero-icon,
.am-stat-icon {
    width: 42px;
    height: 42px;
    border-radius: 8px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    background: #245781;
}
.am-stat-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
    gap: .85rem;
}
.am-stat {
    border: 1px solid rgba(0,0,0,.12);
    border-radius: 8px;
    background: #fff;
    padding: .95rem;
}
.am-stat-value { font-size: 1.55rem; line-height: 1.1; font-weight: 700; }
.am-panel {
    border: 1px solid rgba(0,0,0,.12);
    border-radius: 8px;
    background: #fff;
    overflow: hidden;
}
.am-panel-header {
    background: #263746;
    color: #fff;
    padding: .78rem 1rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: .55rem;
}
.am-panel-body { padding: 1rem; }
.am-section {
    border: 1px solid rgba(0,0,0,.12);
    border-radius: 8px;
    margin-bottom: 1rem;
    overflow: hidden;
}
.am-section-header {
    background: #f1f4f7;
    border-bottom: 1px solid rgba(0,0,0,.1);
    padding: .72rem .9rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: .5rem;
}
.am-section-header i { color: #245781; }
.am-section-body { padding: 1rem; }
.am-module-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
    gap: .45rem .8rem;
}
.am-swatch {
    display: inline-block;
    width: 30px;
    height: 30px;
    border-radius: 4px;
    border: 1px solid rgba(0,0,0,.2);
}
.am-selected-client {
    background: #f8fafc;
    border: 1px solid rgba(0,0,0,.08);
    border-radius: 8px;
    padding: .85rem;
}
</style>

<script>
document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=settings.php">Settings</a><i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">Asset Manager</li>';
</script>

<div class="am-page">
    <div class="am-hero d-flex flex-column flex-lg-row align-items-lg-center justify-content-between gap-3 mb-3">
        <div class="d-flex align-items-center gap-3">
            <span class="am-hero-icon"><i class="fad fa-boxes-stacked"></i></span>
            <div>
                <h2 class="mb-1">Asset Manager Settings</h2>
                <div class="text-muted">Configure client Asset Manager access, operators, modules, limits, branding, and protected EnRep fields.</div>
            </div>
        </div>
    </div>

    <?php if (!$schemaReady) { ?>
    <div class="note note-warning mb-3">
        Asset Manager database tables are not installed yet. Apply the current SQL from the Asset Manager development folder, then use Check Status.
    </div>
    <?php } ?>

    <div class="am-stat-grid mb-3">
        <div class="am-stat d-flex align-items-center gap-3">
            <span class="am-stat-icon"><i class="fad fa-building-user"></i></span>
            <div><div class="small text-muted">Accessible active clients</div><div class="am-stat-value"><?= (int)$overview['active_clients'] ?></div></div>
        </div>
        <div class="am-stat d-flex align-items-center gap-3">
            <span class="am-stat-icon bg-success"><i class="fad fa-toggle-on"></i></span>
            <div><div class="small text-muted">Asset Managers enabled</div><div class="am-stat-value"><?= (int)$overview['enabled_clients'] ?></div></div>
        </div>
        <div class="am-stat d-flex align-items-center gap-3">
            <span class="am-stat-icon bg-info"><i class="fad fa-user-helmet-safety"></i></span>
            <div><div class="small text-muted">Operators registered</div><div class="am-stat-value"><?= (int)$overview['operators'] ?></div></div>
        </div>
        <div class="am-stat d-flex align-items-center gap-3">
            <span class="am-stat-icon bg-secondary"><i class="fad fa-database"></i></span>
            <div>
                <div class="small text-muted">Database status</div>
                <div id="assetManagerSchemaBadge" class="badge <?= $schemaReady ? 'bg-success' : 'bg-warning text-dark' ?>">
                    <?= $schemaReady ? 'Ready' : 'Setup Required' ?>
                </div>
                <button type="button" class="btn btn-secondary btn-sm d-block mt-2" onclick="assetManagerLoadSchemaStatus()">
                    <i class="fad fa-sync"></i> Check Status
                </button>
            </div>
        </div>
    </div>

    <div class="row g-3">
        <div class="col-12 col-xl-3">
            <div class="am-panel mb-3">
                <div class="am-panel-header"><i class="fad fa-search"></i>Select Client</div>
                <div class="am-panel-body">
                    <label class="form-label" for="assetManagerClientSelect">Client</label>
                    <select id="assetManagerClientSelect" class="form-select" data-mdb-select-init data-mdb-filter="true" onchange="assetManagerSelectClient(this.value)">
                        <option value="">Choose client</option>
                        <?php foreach ($clients as $client) { ?>
                        <option value="<?= (int)$client['clientnumber'] ?>" <?= $selectedClientnumber === (int)$client['clientnumber'] ? 'selected' : '' ?>>
                            <?= assetmanager_e($client['clientname']) ?> - <?= (int)$client['clientnumber'] ?>
                        </option>
                        <?php } ?>
                    </select>
                    <div id="assetManagerSchemaStatus" class="small text-muted mt-3">
                        Installed tables: <?= count($schemaStatus['installed']) ?>
                        <?php if (!empty($schemaStatus['missing_required'])) { ?>
                        <div class="text-danger mt-1">Missing: <?= assetmanager_e(implode(', ', $schemaStatus['missing_required'])) ?></div>
                        <?php } ?>
                    </div>
                </div>
            </div>

            <?php if ($selectedClientnumber > 0) { ?>
            <div class="am-selected-client">
                <div class="fw-bold mb-1"><?= assetmanager_e($selectedClient['clientname'] ?? '') ?></div>
                <div class="small text-muted mb-2">Client <?= (int)$selectedClientnumber ?></div>
                <span class="badge <?= !empty($selectedSettings['enabled']) ? 'bg-success' : 'bg-secondary' ?>">
                    <?= !empty($selectedSettings['enabled']) ? 'Enabled' : 'Disabled' ?>
                </span>
            </div>
            <?php } ?>
        </div>

        <div class="col-12 col-xl-9">
            <?php if ($selectedClientnumber <= 0) { ?>
            <div class="am-panel">
                <div class="am-panel-header"><i class="fad fa-user-cog"></i>Client Configuration</div>
                <div class="am-panel-body text-center py-5">
                    <h3 class="h5 mb-2">Choose a client</h3>
                    <p class="text-muted mb-0">Select a client to configure their Asset Manager and operators.</p>
                </div>
            </div>
            <?php } else { ?>
            <form id="<?= $formId ?>" class="am-panel" data-clientnumber="<?= (int)$selectedClientnumber ?>">
                <input type="hidden" name="clientnumber" value="<?= (int)$selectedClientnumber ?>">
                <div class="am-panel-header"><i class="fad fa-user-cog"></i><?= assetmanager_e($selectedClient['clientname'] ?? '') ?></div>
                <div class="am-panel-body">
                    <div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-3 mb-3">
                        <div>
                            <h3 class="h5 mb-1"><?= assetmanager_e($selectedClient['clientname'] ?? '') ?></h3>
                            <div class="text-muted small">Client <?= (int)$selectedClientnumber ?></div>
                        </div>
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" role="switch" name="enabled" value="1" id="am_enabled_<?= (int)$selectedClientnumber ?>" <?= !empty($selectedSettings['enabled']) ? 'checked' : '' ?>>
                            <label class="form-check-label" for="am_enabled_<?= (int)$selectedClientnumber ?>">Asset Manager enabled</label>
                        </div>
                    </div>

                    <div class="am-section">
                        <div class="am-section-header"><i class="fad fa-user-lock"></i>Client Operators</div>
                        <div class="am-section-body">
                            <div class="note note-secondary mb-3">Create one or more operators for this client. Operators log in at `/assetmanager` and go directly into this client's Asset Manager.</div>
                            <?php if (empty($operators)) { ?>
                            <div class="text-muted small mb-3">No operators have been created for this client yet.</div>
                            <?php } else { ?>
                            <div class="table-responsive mb-3">
                                <table class="table table-sm align-middle mb-0">
                                    <thead><tr><th>Operator</th><th>Email</th><th>Role</th><th>Status</th><th>Last Login</th><th class="text-end">Action</th></tr></thead>
                                    <tbody>
                                        <?php foreach ($operators as $operator) {
                                            $operatorId = (int)($operator['id'] ?? 0);
                                            $operatorStatus = (string)($operator['status_key'] ?? 'active');
                                        ?>
                                        <tr>
                                            <td><?= assetmanager_e($operator['name'] ?? '') ?></td>
                                            <td><?= assetmanager_e($operator['email'] ?? '') ?></td>
                                            <td><?= assetmanager_e(ucwords((string)($operator['role_key'] ?? 'operator'))) ?></td>
                                            <td><span class="badge <?= $operatorStatus === 'active' ? 'bg-success' : 'bg-secondary' ?>"><?= assetmanager_e(ucwords($operatorStatus)) ?></span></td>
                                            <td><?= assetmanager_e(assetmanager_format_date($operator['last_login_at'] ?? '')) ?: '-' ?></td>
                                            <td class="text-end">
                                                <button type="button" class="btn btn-sm btn-secondary" onclick="assetManagerOperatorStatus(<?= $operatorId ?>, '<?= $operatorStatus === 'active' ? 'disabled' : 'active' ?>')">
                                                    <i class="fad <?= $operatorStatus === 'active' ? 'fa-user-slash' : 'fa-user-check' ?>"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php } ?>
                            <div class="row g-2">
                                <div class="col-12 col-md-3">
                                    <label class="form-label" for="am_operator_name">Name</label>
                                    <input type="text" class="form-control" id="am_operator_name">
                                </div>
                                <div class="col-12 col-md-3">
                                    <label class="form-label" for="am_operator_email">Email / username</label>
                                    <input type="email" class="form-control" id="am_operator_email">
                                </div>
                                <div class="col-12 col-md-2">
                                    <label class="form-label" for="am_operator_role">Role</label>
                                    <select class="form-select" id="am_operator_role">
                                        <option value="operator">Operator</option>
                                        <option value="manager">Manager</option>
                                    </select>
                                </div>
                                <div class="col-12 col-md-2">
                                    <label class="form-label" for="am_operator_password">Password</label>
                                    <input type="password" class="form-control" id="am_operator_password">
                                </div>
                                <div class="col-12 col-md-2 d-flex align-items-end">
                                    <button type="button" class="btn btn-secondary w-100" onclick="assetManagerConfirmOperatorCreate()">
                                        <i class="fad fa-user-plus"></i> Add
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="am-section">
                        <div class="am-section-header"><i class="fad fa-puzzle-piece"></i>Modules</div>
                        <div class="am-section-body">
                            <div class="am-module-grid">
                                <?php foreach ($defaultSettings['modules'] as $moduleKey => $defaultEnabled) { ?>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="module_<?= assetmanager_e($moduleKey) ?>" value="1" id="am_<?= (int)$selectedClientnumber ?>_<?= assetmanager_e($moduleKey) ?>" <?= !empty($modules[$moduleKey]) ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="am_<?= (int)$selectedClientnumber ?>_<?= assetmanager_e($moduleKey) ?>"><?= assetmanager_e(ucwords(str_replace('_', ' ', $moduleKey))) ?></label>
                                </div>
                                <?php } ?>
                            </div>
                        </div>
                    </div>

                    <div class="am-section">
                        <div class="am-section-header"><i class="fad fa-hashtag"></i>Hire Numbering</div>
                        <div class="am-section-body">
                            <div class="note note-secondary mb-3">Set the next number during provisioning so a hire company can continue its existing agreement and quote references.</div>
                            <div class="row g-3">
                                <div class="col-12">
                                    <div class="fw-bold mb-2">Hire agreements</div>
                                </div>
                                <div class="col-12 col-md-3">
                                    <label class="form-label" for="am_hire_agreement_prefix">Prefix</label>
                                    <input type="text" maxlength="40" class="form-control" id="am_hire_agreement_prefix" name="hire_agreement_prefix" value="<?= assetmanager_e($numbering['hire_agreement']['prefix'] ?? 'HA-') ?>">
                                </div>
                                <div class="col-12 col-md-3">
                                    <label class="form-label" for="am_hire_agreement_next">Next number</label>
                                    <input type="number" min="1" class="form-control" id="am_hire_agreement_next" name="hire_agreement_next_number" value="<?= (int)($numbering['hire_agreement']['next_number'] ?? 1) ?>">
                                </div>
                                <div class="col-12 col-md-3">
                                    <label class="form-label" for="am_hire_agreement_padding">Padding</label>
                                    <input type="number" min="0" max="12" class="form-control" id="am_hire_agreement_padding" name="hire_agreement_padding" value="<?= (int)($numbering['hire_agreement']['padding'] ?? 4) ?>">
                                </div>
                                <div class="col-12 col-md-3">
                                    <label class="form-label" for="am_hire_agreement_suffix">Suffix</label>
                                    <input type="text" maxlength="40" class="form-control" id="am_hire_agreement_suffix" name="hire_agreement_suffix" value="<?= assetmanager_e($numbering['hire_agreement']['suffix'] ?? '') ?>">
                                </div>
                                <div class="col-12">
                                    <div class="small text-muted">Next agreement reference: <strong><?= assetmanager_e(assetmanager_format_sequence_ref($numbering['hire_agreement'] ?? [])) ?></strong></div>
                                </div>
                                <div class="col-12 mt-2">
                                    <div class="fw-bold mb-2">Hire quotes</div>
                                </div>
                                <div class="col-12 col-md-3">
                                    <label class="form-label" for="am_hire_quote_prefix">Prefix</label>
                                    <input type="text" maxlength="40" class="form-control" id="am_hire_quote_prefix" name="hire_quote_prefix" value="<?= assetmanager_e($numbering['hire_quote']['prefix'] ?? 'HQ-') ?>">
                                </div>
                                <div class="col-12 col-md-3">
                                    <label class="form-label" for="am_hire_quote_next">Next number</label>
                                    <input type="number" min="1" class="form-control" id="am_hire_quote_next" name="hire_quote_next_number" value="<?= (int)($numbering['hire_quote']['next_number'] ?? 1) ?>">
                                </div>
                                <div class="col-12 col-md-3">
                                    <label class="form-label" for="am_hire_quote_padding">Padding</label>
                                    <input type="number" min="0" max="12" class="form-control" id="am_hire_quote_padding" name="hire_quote_padding" value="<?= (int)($numbering['hire_quote']['padding'] ?? 4) ?>">
                                </div>
                                <div class="col-12 col-md-3">
                                    <label class="form-label" for="am_hire_quote_suffix">Suffix</label>
                                    <input type="text" maxlength="40" class="form-control" id="am_hire_quote_suffix" name="hire_quote_suffix" value="<?= assetmanager_e($numbering['hire_quote']['suffix'] ?? '') ?>">
                                </div>
                                <div class="col-12">
                                    <div class="small text-muted">Next quote reference: <strong><?= assetmanager_e(assetmanager_format_sequence_ref($numbering['hire_quote'] ?? [])) ?></strong></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="am-section">
                        <div class="am-section-header"><i class="fad fa-gauge-high"></i>Limits</div>
                        <div class="am-section-body">
                            <div class="row g-3">
                                <div class="col-12 col-md-4"><label class="form-label" for="am_users_<?= (int)$selectedClientnumber ?>">User limit</label><input type="number" min="1" class="form-control" id="am_users_<?= (int)$selectedClientnumber ?>" name="limit_users" value="<?= (int)$limits['users'] ?>"></div>
                                <div class="col-12 col-md-4"><label class="form-label" for="am_assets_<?= (int)$selectedClientnumber ?>">Local asset limit</label><input type="number" min="0" class="form-control" id="am_assets_<?= (int)$selectedClientnumber ?>" name="limit_local_assets" value="<?= (int)$limits['local_assets'] ?>"></div>
                                <div class="col-12 col-md-4"><label class="form-label" for="am_storage_<?= (int)$selectedClientnumber ?>">Storage limit MB</label><input type="number" min="0" class="form-control" id="am_storage_<?= (int)$selectedClientnumber ?>" name="limit_storage_mb" value="<?= (int)$limits['storage_mb'] ?>"></div>
                            </div>
                        </div>
                    </div>

                    <div class="am-section">
                        <div class="am-section-header"><i class="fad fa-palette"></i>Branding</div>
                        <div class="am-section-body">
                            <div class="row g-3">
                                <div class="col-12 col-md-6">
                                    <label class="form-label" for="am_primary_<?= (int)$selectedClientnumber ?>">Primary colour</label>
                                    <div class="input-group"><input type="text" maxlength="6" class="form-control" id="am_primary_<?= (int)$selectedClientnumber ?>" name="brand_primary" value="<?= assetmanager_e($branding['primary']) ?>"><span class="input-group-text p-1"><span class="am-swatch" style="background:#<?= assetmanager_e($branding['primary']) ?>"></span></span></div>
                                </div>
                                <div class="col-12 col-md-6">
                                    <label class="form-label" for="am_accent_<?= (int)$selectedClientnumber ?>">Accent colour</label>
                                    <div class="input-group"><input type="text" maxlength="6" class="form-control" id="am_accent_<?= (int)$selectedClientnumber ?>" name="brand_accent" value="<?= assetmanager_e($branding['accent']) ?>"><span class="input-group-text p-1"><span class="am-swatch" style="background:#<?= assetmanager_e($branding['accent']) ?>"></span></span></div>
                                </div>
                                <div class="col-12 col-md-6"><div class="form-check"><input class="form-check-input" type="checkbox" name="brand_tenant_logo" value="1" id="am_tenant_logo_<?= (int)$selectedClientnumber ?>" <?= !empty($branding['tenant_logo']) ? 'checked' : '' ?>><label class="form-check-label" for="am_tenant_logo_<?= (int)$selectedClientnumber ?>">Show tenant logo</label></div></div>
                                <div class="col-12 col-md-6"><div class="form-check"><input class="form-check-input" type="checkbox" name="brand_client_logo" value="1" id="am_client_logo_<?= (int)$selectedClientnumber ?>" <?= !empty($branding['client_logo']) ? 'checked' : '' ?>><label class="form-check-label" for="am_client_logo_<?= (int)$selectedClientnumber ?>">Show client logo</label></div></div>
                            </div>
                        </div>
                    </div>

                    <div class="am-section">
                        <div class="am-section-header"><i class="fad fa-lock-alt"></i>Client Actions And Protected Fields</div>
                        <div class="am-section-body">
                            <div class="form-check form-switch mb-2"><input class="form-check-input" type="checkbox" role="switch" name="perm_include_enrep_assets" value="1" id="am_include_enrep_<?= (int)$selectedClientnumber ?>" <?= !empty($permissions['include_enrep_assets']) ? 'checked' : '' ?>><label class="form-check-label fw-bold" for="am_include_enrep_<?= (int)$selectedClientnumber ?>">Include EnRep inspection assets</label></div>
                            <div class="note note-secondary mb-3">Turn this off when this client should use Asset Manager as a standalone asset register.</div>
                            <div class="form-check mb-2"><input class="form-check-input" type="checkbox" name="perm_client_add_assets" value="1" id="am_add_assets_<?= (int)$selectedClientnumber ?>" <?= !empty($permissions['client_add_assets']) ? 'checked' : '' ?>><label class="form-check-label" for="am_add_assets_<?= (int)$selectedClientnumber ?>">Can add Asset Manager assets</label></div>
                            <div class="form-check mb-3"><input class="form-check-input" type="checkbox" name="perm_client_archive_local_assets" value="1" id="am_archive_assets_<?= (int)$selectedClientnumber ?>" <?= !empty($permissions['client_archive_local_assets']) ? 'checked' : '' ?>><label class="form-check-label" for="am_archive_assets_<?= (int)$selectedClientnumber ?>">Can archive Asset Manager assets</label></div>
                            <div class="form-check form-switch mb-2"><input class="form-check-input" type="checkbox" role="switch" name="itemdetails_edit_enabled" value="1" id="am_itemdetails_edit_<?= (int)$selectedClientnumber ?>" <?= !empty($itemdetailsEdit['enabled']) ? 'checked' : '' ?>><label class="form-check-label fw-bold" for="am_itemdetails_edit_<?= (int)$selectedClientnumber ?>">Allow selected master plant edits</label></div>
                            <div class="note note-secondary mb-3">Inspection data, report data, item definitions, and deletion stay locked.</div>
                            <?php foreach ($fieldLabels as $fieldKey => $fieldLabel) { ?>
                            <div class="form-check form-check-inline mb-2"><input class="form-check-input" type="checkbox" name="itemdetails_fields[]" value="<?= assetmanager_e($fieldKey) ?>" id="am_field_<?= (int)$selectedClientnumber ?>_<?= assetmanager_e($fieldKey) ?>" <?= in_array($fieldKey, $itemdetailsEdit['fields'] ?? [], true) ? 'checked' : '' ?>><label class="form-check-label" for="am_field_<?= (int)$selectedClientnumber ?>_<?= assetmanager_e($fieldKey) ?>"><?= assetmanager_e($fieldLabel) ?></label></div>
                            <?php } ?>
                        </div>
                    </div>

                    <button type="button" class="btn btn-success" onclick="assetManagerConfirmSave('<?= $formId ?>')" <?= $schemaReady ? '' : 'disabled' ?>>
                        <i class="fad fa-save"></i> Save Settings
                    </button>
                    <span class="text-success ms-2" id="<?= $formId ?>_saved" style="display:none">Saved</span>
                </div>
            </form>
            <?php } ?>
        </div>
    </div>
</div>

<script>
function assetManagerSelectClient(clientnumber) {
    const base = 'index.php?t=assetmanager&p=settings.php';
    window.location.href = clientnumber ? base + '&clientnumber=' + encodeURIComponent(clientnumber) : base;
}
function assetManagerEscapeHtml(value) {
    return String(value ?? '').replace(/[&<>"']/g, function(ch) {
        return {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;'}[ch];
    });
}
function assetManagerConfirmSave(formId) {
    const form = document.getElementById(formId);
    if (!form) return;
    const clientTitle = <?= json_encode((string)($selectedClient['clientname'] ?? 'this client')) ?>;
    const dest = '<p>Save Asset Manager settings for <strong>' + assetManagerEscapeHtml(clientTitle) + '</strong>?</p>';
    loadModalContent(dest, 'assetManagerConfirmBox', 'modal-md', 1080, document.querySelector('.modal.show') ? 'false' : 'true', 'Save Asset Manager Settings', 'cancelConfirm', function() {
        assetManagerSave(formId);
        killModal('assetManagerConfirmBox');
    });
}
function assetManagerSave(formId) {
    const form = document.getElementById(formId);
    if (!form) return;
    const data = new FormData(form);
    data.append('tenant', TENANT_URL);
    if (!form.querySelector('[name="enabled"]').checked) data.set('enabled', '0');
    if (!form.querySelector('[name="itemdetails_edit_enabled"]').checked) data.set('itemdetails_edit_enabled', '0');
    form.querySelectorAll('input[type="checkbox"][name^="module_"], input[type="checkbox"][name^="perm_"], input[type="checkbox"][name^="brand_"]').forEach(function(input) {
        if (!input.checked) data.set(input.name, '0');
    });
    fetch(ROOT_URL + '/assetmanager/settings_save.php', {method: 'POST', body: data})
        .then(response => response.json())
        .then(function(result) {
            if (result.success) {
                const saved = document.getElementById(formId + '_saved');
                if (saved) {
                    saved.style.display = 'inline';
                    setTimeout(function() { saved.style.display = 'none'; }, 1200);
                }
                showResponse('success', result.message || 'Asset Manager settings saved.');
                return;
            }
            showResponse('danger', result.message || 'Asset Manager settings could not be saved.');
        }).catch(function() {
            showResponse('danger', 'Asset Manager settings could not be saved.');
        });
}
function assetManagerConfirmOperatorCreate() {
    const name = document.getElementById('am_operator_name')?.value || '';
    const email = document.getElementById('am_operator_email')?.value || '';
    const dest = '<p>Create Asset Manager operator <strong>' + assetManagerEscapeHtml(name || email || 'new operator') + '</strong>?</p>';
    loadModalContent(dest, 'assetManagerOperatorBox', 'modal-md', 1080, document.querySelector('.modal.show') ? 'false' : 'true', 'Create Operator', 'cancelConfirm', function() {
        assetManagerOperatorCreate();
        killModal('assetManagerOperatorBox');
    });
}
function assetManagerOperatorCreate() {
    const data = new URLSearchParams({
        tenant: TENANT_URL,
        clientnumber: '<?= (int)$selectedClientnumber ?>',
        mode: 'create',
        operator_name: document.getElementById('am_operator_name')?.value || '',
        operator_email: document.getElementById('am_operator_email')?.value || '',
        role_key: document.getElementById('am_operator_role')?.value || 'operator',
        operator_password: document.getElementById('am_operator_password')?.value || ''
    });
    fetch(ROOT_URL + '/assetmanager/operator_save.php', {method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: data})
        .then(response => response.json())
        .then(function(result) {
            if (result.success) {
                showResponse('success', result.message || 'Operator created.');
                window.location.reload();
                return;
            }
            showResponse('danger', result.message || 'Operator could not be created.');
        }).catch(function() {
            showResponse('danger', 'Operator could not be created.');
        });
}
function assetManagerOperatorStatus(operatorId, statusKey) {
    const dest = '<p>Update this operator status?</p>';
    loadModalContent(dest, 'assetManagerOperatorBox', 'modal-md', 1080, document.querySelector('.modal.show') ? 'false' : 'true', 'Update Operator', 'cancelConfirm', function() {
        const data = new URLSearchParams({
            tenant: TENANT_URL,
            clientnumber: '<?= (int)$selectedClientnumber ?>',
            mode: 'update_status',
            operator_id: String(operatorId || 0),
            status_key: statusKey
        });
        fetch(ROOT_URL + '/assetmanager/operator_save.php', {method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: data})
            .then(response => response.json())
            .then(function(result) {
                if (result.success) {
                    showResponse('success', result.message || 'Operator updated.');
                    window.location.reload();
                    return;
                }
                showResponse('danger', result.message || 'Operator could not be updated.');
            }).catch(function() {
                showResponse('danger', 'Operator could not be updated.');
            });
        killModal('assetManagerOperatorBox');
    });
}
function assetManagerLoadSchemaStatus() {
    const data = new URLSearchParams({tenant: TENANT_URL});
    fetch(ROOT_URL + '/assetmanager/schema_status.php', {method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: data})
        .then(response => response.json())
        .then(function(result) {
            if (!result.success) {
                showResponse('danger', result.message || 'Asset Manager schema status could not be checked.');
                return;
            }
            assetManagerRenderSchemaStatus(result);
        }).catch(function() {
            showResponse('danger', 'Asset Manager schema status could not be checked.');
        });
}
function assetManagerRenderSchemaStatus(result) {
    const badge = document.getElementById('assetManagerSchemaBadge');
    const box = document.getElementById('assetManagerSchemaStatus');
    if (!badge || !box) return;
    const missingRequired = Array.isArray(result.missing_required) ? result.missing_required : [];
    badge.className = 'badge ' + (result.ready && missingRequired.length === 0 ? 'bg-success' : 'bg-warning text-dark');
    badge.textContent = result.ready && missingRequired.length === 0 ? 'Ready' : 'Setup Required';
    const installed = Array.isArray(result.installed) ? result.installed : [];
    box.innerHTML = 'Installed tables: ' + installed.length + (missingRequired.length ? '<div class="text-danger mt-1">Missing: ' + missingRequired.map(assetManagerEscapeHtml).join(', ') + '</div>' : '');
}
document.querySelectorAll('[name="brand_primary"], [name="brand_accent"]').forEach(function(input) {
    input.addEventListener('input', function() {
        const value = String(input.value || '').replace('#', '').trim();
        const swatch = input.closest('.input-group')?.querySelector('.am-swatch');
        if (swatch && /^[0-9a-fA-F]{6}$/.test(value)) swatch.style.backgroundColor = '#' + value;
    });
});
</script>
