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

$tenant = enrep_tenant_segment($_REQUEST['tenant'] ?? null);
if ($tenant !== '' && !defined('CONFIG_LOADED')) {
    require_once '../../' . $tenant . '/config.php';
}

assetmanager_require_user();

$con = $GLOBALS['con'] ?? null;
if (!$con instanceof mysqli) {
    echo '<div class="note note-danger">Tenant database connection unavailable.</div>';
    exit;
}
$con->set_charset('utf8mb4');

$clientnumber = enrep_request_int('clientnumber', 0);
$source = enrep_request_enum('source', ['enrep_item', 'assetmanager_item'], '');
$sourceId = enrep_request_int('source_id', 0);
$view = enrep_request_enum('view', ['quick', 'detail'], 'quick');

if ($clientnumber <= 0 || $source === '' || $sourceId <= 0) {
    echo '<div class="note note-danger">Asset could not be loaded.</div>';
    exit;
}
if (!assetmanager_user_can_access_client($con, $clientnumber)) {
    echo '<div class="note note-danger">You do not have access to this client.</div>';
    exit;
}
if (!assetmanager_user_can_access_asset($con, $tenant, $clientnumber, $source, $sourceId)) {
    echo '<div class="note note-danger">You do not have access to this asset.</div>';
    exit;
}

$clientSettings = assetmanager_get_client_settings($con, $tenant, $clientnumber);
if (empty($clientSettings['enabled'])) {
    echo '<div class="note note-warning">Asset Manager is not enabled for this client.</div>';
    exit;
}
$moduleMaintenance = !empty($clientSettings['modules']['maintenance']);
$moduleDocuments = !empty($clientSettings['modules']['documents']);
$moduleUsage = !empty($clientSettings['modules']['usage']);

$asset = null;
$supplement = [];
$coreFields = [];

if ($source === 'enrep_item') {
    $stmt = $con->prepare("
        SELECT a.itemnumber, a.desc, a.plantnumber, a.serialnumber, a.manf, a.model, a.dateofmanf, a.duedate, a.lastReport, a.subloc, l.locname
        FROM itemdetails a
        LEFT JOIN locations l ON l.locnumber=a.locnumber
        WHERE a.clientnumber=? AND a.itemnumber=?
        LIMIT 1
    ");
    if ($stmt) {
        $stmt->bind_param('ii', $clientnumber, $sourceId);
        $stmt->execute();
        $asset = $stmt->get_result()->fetch_assoc();
        $stmt->close();
    }

    if (assetmanager_table_exists($con, 'assetmanager_assets')) {
        $stmt = $con->prepare("
            SELECT custom_fields_json
            FROM assetmanager_assets
            WHERE tenant_key=? AND clientnumber=? AND source_type='enrep_item' AND source_itemnumber=?
            LIMIT 1
        ");
        if ($stmt) {
            $stmt->bind_param('sii', $tenant, $clientnumber, $sourceId);
            $stmt->execute();
            $row = $stmt->get_result()->fetch_assoc();
            $supplement = assetmanager_decode_json($row['custom_fields_json'] ?? '');
            $stmt->close();
        }
    }
} else {
    $stmt = $con->prepare("
        SELECT id, asset_title, plantnumber, serialnumber, status_key, core_fields_json, custom_fields_json
        FROM assetmanager_assets
        WHERE tenant_key=? AND clientnumber=? AND id=?
        LIMIT 1
    ");
    if ($stmt) {
        $stmt->bind_param('sii', $tenant, $clientnumber, $sourceId);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        if ($row) {
            $core = assetmanager_decode_json($row['core_fields_json'] ?? '');
            $coreFields = $core;
            $supplement = assetmanager_decode_json($row['custom_fields_json'] ?? '');
            $asset = [
                'itemnumber' => 0,
                'desc' => $row['asset_title'] ?? '',
                'plantnumber' => $row['plantnumber'] ?? '',
                'serialnumber' => $row['serialnumber'] ?? '',
                'manf' => $core['manufacturer'] ?? '',
                'model' => $core['model'] ?? '',
                'dateofmanf' => $core['dateofmanf'] ?? '',
                'lastReport' => '',
                'duedate' => '',
                'locname' => $supplement['location_label'] ?? '',
                'subloc' => $supplement['subloc'] ?? '',
                'status_key' => $row['status_key'] ?? 'active',
            ];
        }
        $stmt->close();
    }
}

if (!$asset) {
    echo '<div class="note note-danger">Asset could not be found.</div>';
    exit;
}

$status = $supplement['operational_status'] ?? ($asset['status_key'] ?? 'active');
$assetTitle = (string)($asset['desc'] ?? 'Untitled asset');
$assetMeta = array_merge($coreFields, $supplement);
$inspectionSubloc = (string)($asset['subloc'] ?? '');
$liveSubloc = trim((string)($assetMeta['live_subloc'] ?? ''));
if ($liveSubloc === '') {
    $liveSubloc = $inspectionSubloc;
}
$liveSublocDiffers = $source === 'enrep_item' && trim($liveSubloc) !== trim($inspectionSubloc);
$assetClassLabels = [
    '' => 'Not specified',
    'general' => 'General asset',
    'plant' => 'Plant and equipment',
    'vehicle' => 'Vehicle',
    'electrical' => 'Electrical asset',
    'tooling' => 'Tools and attachments',
    'facility' => 'Facilities asset',
];
$ownershipLabels = [
    '' => 'Not specified',
    'owned' => 'Owned',
    'leased' => 'Leased',
    'hired_in' => 'Hired in',
    'customer_owned' => 'Customer owned',
    'managed_only' => 'Managed only',
];
$hireStateLabels = [
    '' => 'Not specified',
    'available' => 'Available',
    'reserved' => 'Reserved',
    'on_hire' => 'On hire',
    'off_hire' => 'Off hire',
    'returned' => 'Returned',
    'quarantined' => 'Quarantined',
];
$currentAssetClass = (string)($assetMeta['asset_class'] ?? '');
$hireEnabled = !empty($assetMeta['hire_enabled']) || $currentAssetClass === 'hire_plant';
if ($currentAssetClass === 'hire_plant') {
    $currentAssetClass = 'plant';
}
$classLabel = $assetClassLabels[$currentAssetClass] ?? ucwords(str_replace('_', ' ', $currentAssetClass));
$ownershipLabel = $ownershipLabels[(string)($assetMeta['ownership_status'] ?? '')] ?? ucwords(str_replace('_', ' ', (string)($assetMeta['ownership_status'] ?? '')));
$hireStateLabel = $hireStateLabels[(string)($assetMeta['hire_state'] ?? '')] ?? ucwords(str_replace('_', ' ', (string)($assetMeta['hire_state'] ?? '')));
$inspectionDueFormatted = assetmanager_format_date($asset['duedate'] ?? '');
$complianceRows = [
    'Insurance expires' => assetmanager_format_date($assetMeta['insurance_expires'] ?? ''),
    'MOT expires' => assetmanager_format_date($assetMeta['mot_expires'] ?? ''),
    'Vehicle tax expires' => assetmanager_format_date($assetMeta['tax_expires'] ?? ''),
    'PAT expires' => assetmanager_format_date($assetMeta['pat_expires'] ?? ''),
    'Warranty expires' => assetmanager_format_date($assetMeta['warranty_expires'] ?? ''),
    'Last service' => assetmanager_format_date($assetMeta['last_service_date'] ?? ''),
];
$referenceRows = [
    'Asset tag' => $assetMeta['asset_tag'] ?? '',
    'Fleet number' => $assetMeta['fleet_number'] ?? '',
    'Registration' => $assetMeta['registration_mark'] ?? '',
    'Department' => $assetMeta['department'] ?? '',
    'Responsible person' => $assetMeta['custodian'] ?? '',
    'Supplier' => $assetMeta['supplier'] ?? '',
];
$assetAlerts = [];
$todayTs = strtotime(date('Y-m-d'));
foreach ($complianceRows as $label => $value) {
    $value = trim((string)$value);
    if ($value === '') {
        continue;
    }
    $dueTs = strtotime(str_replace('/', '-', $value));
    if (!$dueTs) {
        continue;
    }
    if ($dueTs < $todayTs) {
        $assetAlerts[] = ['level' => 'danger', 'message' => $label . ' is overdue: ' . $value];
    } elseif ($dueTs <= strtotime('+30 days', $todayTs)) {
        $assetAlerts[] = ['level' => 'warning', 'message' => $label . ' is due soon: ' . $value];
    }
}
if ($source === 'enrep_item') {
    $inspectionDue = trim((string)($asset['duedate'] ?? ''));
    $inspectionTs = $inspectionDue !== '' ? strtotime(str_replace('/', '-', $inspectionDue)) : false;
    if ($inspectionTs && $inspectionTs < $todayTs) {
        $assetAlerts[] = ['level' => 'danger', 'message' => 'Inspection is overdue: ' . $inspectionDue];
    } elseif ($inspectionTs && $inspectionTs <= strtotime('+30 days', $todayTs)) {
        $assetAlerts[] = ['level' => 'warning', 'message' => 'Inspection is due soon: ' . $inspectionDue];
    }
}
$assetManagerId = 0;
if (assetmanager_table_exists($con, 'assetmanager_assets')) {
    $assetManagerId = assetmanager_resolve_asset_id($con, $tenant, $clientnumber, $source, $sourceId, $assetTitle, false);
}

$workOrders = [];
if ($moduleMaintenance && $assetManagerId > 0 && assetmanager_table_exists($con, 'assetmanager_maintenance')) {
    $stmt = $con->prepare("
        SELECT id, status_key, priority_key, due_at, summary, payload_json, created_at
        FROM assetmanager_maintenance
        WHERE tenant_key=? AND clientnumber=? AND asset_id=? AND record_type='work_order'
        ORDER BY
            CASE status_key WHEN 'open' THEN 0 WHEN 'in_progress' THEN 1 WHEN 'complete' THEN 2 ELSE 3 END,
            due_at IS NULL,
            due_at ASC,
            id DESC
        LIMIT 20
    ");
    if ($stmt) {
        $stmt->bind_param('sii', $tenant, $clientnumber, $assetManagerId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $row['details'] = assetmanager_decode_json($row['payload_json'] ?? '');
            $row['work_type'] = (string)($row['details']['work_type'] ?? 'maintenance');
            $workOrders[] = $row;
        }
        $stmt->close();
    }
}

$assetFiles = [];
if ($moduleDocuments && $assetManagerId > 0 && assetmanager_table_exists($con, 'assetmanager_documents')) {
    $stmt = $con->prepare("
        SELECT id, document_type AS file_type, title AS file_title, file_path, payload_json, expires_at, created_at
        FROM assetmanager_documents
        WHERE tenant_key=? AND clientnumber=? AND asset_id=? AND module_key='assets'
        ORDER BY created_at DESC, id DESC
        LIMIT 20
    ");
    if ($stmt) {
        $stmt->bind_param('sii', $tenant, $clientnumber, $assetManagerId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $row['meta'] = assetmanager_decode_json($row['payload_json'] ?? '');
            $assetFiles[] = $row;
        }
        $stmt->close();
    }
}

$schedules = [];
if ($moduleMaintenance && $assetManagerId > 0 && assetmanager_table_exists($con, 'assetmanager_maintenance')) {
    $stmt = $con->prepare("
        SELECT id, status_key, summary AS schedule_type, payload_json, due_at AS next_due_at, completed_at AS last_done_at, created_at
        FROM assetmanager_maintenance
        WHERE tenant_key=? AND clientnumber=? AND asset_id=? AND record_type='schedule'
        ORDER BY status_key ASC, due_at IS NULL, due_at ASC, id DESC
        LIMIT 20
    ");
    if ($stmt) {
        $stmt->bind_param('sii', $tenant, $clientnumber, $assetManagerId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $row['rule'] = assetmanager_decode_json($row['payload_json'] ?? '');
            $schedules[] = $row;
        }
        $stmt->close();
    }
}

$usageLogs = [];
if ($moduleUsage && $assetManagerId > 0 && assetmanager_table_exists($con, 'assetmanager_activity')) {
    $stmt = $con->prepare("
        SELECT id, activity_type AS usage_type, reading_value, reading_unit, activity_at AS usage_at, payload_json, created_at
        FROM assetmanager_activity
        WHERE tenant_key=? AND clientnumber=? AND asset_id=? AND module_key='usage'
        ORDER BY activity_at DESC, id DESC
        LIMIT 20
    ");
    if ($stmt) {
        $stmt->bind_param('sii', $tenant, $clientnumber, $assetManagerId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $row['payload'] = assetmanager_decode_json($row['payload_json'] ?? '');
            $usageLogs[] = $row;
        }
        $stmt->close();
    }
}

if ($view === 'quick') {
    ?>
    <div class="assetmanager-profile-summary">
        <div class="row g-3">
            <div class="col-12">
                <div class="small text-muted mb-1"><?= $source === 'enrep_item' ? 'Included in EnRep schedule' : 'Added asset' ?></div>
                <h3 class="h5 mb-3"><?= assetmanager_e($asset['desc'] ?? 'Untitled asset') ?></h3>
                <?php if (!empty($assetAlerts)) { ?>
                <div class="mb-3">
                    <?php foreach (array_slice($assetAlerts, 0, 4) as $alert) { ?>
                    <div class="note note-<?= assetmanager_e($alert['level']) ?> py-2 px-3 mb-2"><?= assetmanager_e($alert['message']) ?></div>
                    <?php } ?>
                </div>
                <?php } ?>
                <dl class="row small mb-0">
                    <dt class="col-5">Asset type</dt><dd class="col-7"><?= assetmanager_e($classLabel) ?></dd>
                    <dt class="col-5">Plant No.</dt><dd class="col-7"><?= assetmanager_e($asset['plantnumber'] ?? '-') ?></dd>
                    <dt class="col-5">Serial</dt><dd class="col-7"><?= assetmanager_e($asset['serialnumber'] ?? '-') ?></dd>
                    <dt class="col-5">Manufacturer</dt><dd class="col-7"><?= assetmanager_e($asset['manf'] ?? '-') ?></dd>
                    <dt class="col-5">Model</dt><dd class="col-7"><?= assetmanager_e($asset['model'] ?? '-') ?></dd>
                    <dt class="col-5">Location</dt><dd class="col-7"><?= assetmanager_e($asset['locname'] ?? '-') ?></dd>
                    <dt class="col-5">Live sited location</dt><dd class="col-7"><?= assetmanager_e($liveSubloc !== '' ? $liveSubloc : '-') ?></dd>
                    <dt class="col-5">Status</dt><dd class="col-7"><?= assetmanager_e(ucwords(str_replace('_', ' ', (string)$status))) ?></dd>
                    <?php if (trim((string)($assetMeta['asset_tag'] ?? '')) !== '') { ?>
                    <dt class="col-5">Asset tag</dt><dd class="col-7"><?= assetmanager_e($assetMeta['asset_tag']) ?></dd>
                    <?php } ?>
                    <?php if (trim((string)($assetMeta['fleet_number'] ?? '')) !== '') { ?>
                    <dt class="col-5">Fleet number</dt><dd class="col-7"><?= assetmanager_e($assetMeta['fleet_number']) ?></dd>
                    <?php } ?>
                    <?php if ($currentAssetClass === 'vehicle' && trim((string)($assetMeta['registration_mark'] ?? '')) !== '') { ?>
                    <dt class="col-5">Registration</dt><dd class="col-7"><?= assetmanager_e($assetMeta['registration_mark']) ?></dd>
                    <?php } ?>
                    <?php if ($source === 'enrep_item') { ?>
                    <dt class="col-5">Schedule marker</dt><dd class="col-7">Included in EnRep schedule</dd>
                    <dt class="col-5">Last examined sited location</dt><dd class="col-7"><?= assetmanager_e($inspectionSubloc !== '' ? $inspectionSubloc : '-') ?></dd>
                    <dt class="col-5">Inspection result</dt><dd class="col-7"><?= assetmanager_e($asset['lastReport'] ?? 'Not recorded') ?></dd>
                    <dt class="col-5">Inspection due</dt><dd class="col-7"><?= assetmanager_e($inspectionDueFormatted ?: '-') ?></dd>
                    <?php } ?>
                </dl>
            </div>
        </div>
        <div class="d-flex justify-content-end gap-2 mt-3">
            <button type="button" class="btn btn-success assetmanager-open-full-asset" data-source="<?= assetmanager_e($source) ?>" data-source-id="<?= (int)$sourceId ?>">
                <i class="fad fa-folder-open"></i> Open Asset
            </button>
        </div>
    </div>
    <?php
    exit;
}
?>
<style>
.assetmanager-profile .assetmanager-form-section {
    border: 1px solid rgba(0,0,0,.12);
    border-radius: 8px;
    margin-bottom: .85rem;
    background: #fff;
    overflow: hidden;
}
.assetmanager-profile .assetmanager-form-section-title {
    background: #263746;
    color: #fff;
    font-weight: 700;
    padding: .55rem .75rem;
}
.assetmanager-profile .assetmanager-form-section-body {
    padding: .85rem;
}
.assetmanager-profile .form-label {
    margin-bottom: .25rem;
}
.assetmanager-profile .form-control {
    min-height: 32px;
    padding-top: .35rem;
    padding-bottom: .35rem;
}
.assetmanager-profile .assetmanager-readonly-enrep {
    background: #f4f6f8;
    border-left: 4px solid #263746;
}
.assetmanager-profile .assetmanager-enrep-section {
    border-color: rgba(38,55,70,.32);
}
.assetmanager-profile .assetmanager-enrep-section .assetmanager-form-section-title {
    background: #1f3446;
}
.assetmanager-profile .assetmanager-enrep-section .assetmanager-form-section-body {
    background: #f4f6f8;
}
.assetmanager-profile .assetmanager-enrep-section .form-control {
    background: #eef1f4;
    border-color: #d2d8de;
    color: #263746;
}
.assetmanager-profile .assetmanager-enrep-lock-note {
    border-top: 1px solid #d2d8de;
    color: #5f6b76;
    margin-top: .75rem;
    padding-top: .6rem;
}
.assetmanager-profile .assetmanager-live-field {
    background: #f7fbf8;
    border-left: 4px solid #198754;
}
</style>
<div class="assetmanager-profile">
    <div class="row g-3">
        <div class="col-12">
            <form id="assetManagerSupplementForm" data-current-asset-class="<?= assetmanager_e($currentAssetClass) ?>">
                <input type="hidden" name="mode" value="save_supplement">
                <input type="hidden" name="tenant" value="<?= assetmanager_e($tenant) ?>">
                <input type="hidden" name="clientnumber" value="<?= (int)$clientnumber ?>">
                <input type="hidden" name="source" value="<?= assetmanager_e($source) ?>">
                <input type="hidden" name="source_id" value="<?= (int)$sourceId ?>">
                <div class="assetmanager-form-section<?= $source === 'enrep_item' ? ' assetmanager-enrep-section' : '' ?>">
                    <div class="card-header assetmanager-form-section-title d-flex align-items-center justify-content-between gap-2">
                        <span><i class="fad fa-id-card"></i> Asset Identification</span>
                        <?php if ($source === 'enrep_item') { ?>
                        <span class="badge bg-light text-dark"><i class="fad fa-lock"></i> Read-only EnRep schedule record</span>
                        <?php } ?>
                    </div>
                    <div class="assetmanager-form-section-body">
                    <?php if (!empty($assetAlerts)) { ?>
                    <div class="mb-2">
                        <?php foreach (array_slice($assetAlerts, 0, 4) as $alert) { ?>
                        <div class="note note-<?= assetmanager_e($alert['level']) ?> py-2 px-3 mb-2"><?= assetmanager_e($alert['message']) ?></div>
                        <?php } ?>
                    </div>
                    <?php } ?>
                    <div class="row g-2">
                        <div class="col-12 col-md-4">
                            <label class="form-label">Asset</label>
                            <input type="text" class="form-control" value="<?= assetmanager_e($asset['desc'] ?? 'Untitled asset') ?>" readonly>
                        </div>
                        <div class="col-12 col-md-2">
                            <label class="form-label">Plant No.</label>
                            <input type="text" class="form-control" value="<?= assetmanager_e($asset['plantnumber'] ?? '') ?>" readonly>
                        </div>
                        <div class="col-12 col-md-2">
                            <label class="form-label">Serial</label>
                            <input type="text" class="form-control" value="<?= assetmanager_e($asset['serialnumber'] ?? '') ?>" readonly>
                        </div>
                        <div class="col-12 col-md-2">
                            <label class="form-label">Manufacturer</label>
                            <input type="text" class="form-control" value="<?= assetmanager_e($asset['manf'] ?? '') ?>" readonly>
                        </div>
                        <div class="col-12 col-md-2">
                            <label class="form-label">Model</label>
                            <input type="text" class="form-control" value="<?= assetmanager_e($asset['model'] ?? '') ?>" readonly>
                        </div>
                        <div class="col-12 col-md-3">
                            <label class="form-label">Location</label>
                            <input type="text" class="form-control" value="<?= assetmanager_e($asset['locname'] ?? '') ?>" readonly>
                        </div>
                        <?php if ($source === 'enrep_item') { ?>
                        <div class="col-12 col-md-2">
                            <label class="form-label">Schedule marker</label>
                            <input type="text" class="form-control" value="EnRep" readonly>
                        </div>
                        <div class="col-12 col-md-4">
                            <label class="form-label">Last examined sited location</label>
                            <input type="text" class="form-control" value="<?= assetmanager_e($inspectionSubloc) ?>" readonly>
                        </div>
                        <div class="col-12 col-md-2">
                            <label class="form-label">Result</label>
                            <input type="text" class="form-control" value="<?= assetmanager_e($asset['lastReport'] ?? 'Not recorded') ?>" readonly>
                        </div>
                        <div class="col-12 col-md-2">
                            <label class="form-label">Inspection due</label>
                            <input type="text" class="form-control" value="<?= assetmanager_e($inspectionDueFormatted ?: '') ?>" readonly>
                        </div>
                        <?php } ?>
                    </div>
                    <?php if ($source === 'enrep_item') { ?>
                    <div class="small assetmanager-enrep-lock-note">
                        <i class="fad fa-lock"></i> These fields come from the read-only EnRep inspection schedule. Update live operational details in the section below.
                    </div>
                    <?php } ?>
                    </div>
                </div>
                <div class="assetmanager-form-section">
                    <div class="card-header assetmanager-form-section-title"><i class="fad fa-sliders-h"></i> Operational Details</div>
                    <div class="assetmanager-form-section-body">
                    <div class="row g-2">
                    <div class="col-12 col-md-4">
                        <label class="form-label" for="am_profile_nickname">Operational nickname</label>
                        <input type="text" class="form-control" id="am_profile_nickname" name="nickname" value="<?= assetmanager_e($supplement['nickname'] ?? '') ?>">
                    </div>
                    <div class="col-12 col-md-4">
                        <label class="form-label" for="am_profile_live_subloc">Live sited location</label>
                        <input type="text" class="form-control assetmanager-live-field" id="am_profile_live_subloc" name="live_subloc" value="<?= assetmanager_e($liveSubloc) ?>">
                        <?php if ($source === 'enrep_item') { ?>
                        <div class="small <?= $liveSublocDiffers ? 'text-success' : 'text-muted' ?> mt-1">
                            <i class="fad <?= $liveSublocDiffers ? 'fa-location-dot' : 'fa-circle-info' ?>"></i>
                            <?= $liveSublocDiffers ? 'Different from the last examined EnRep sited location.' : 'Defaults to the last examined EnRep sited location until updated.' ?>
                        </div>
                        <?php } ?>
                    </div>
                    <div class="col-12 col-md-3">
                        <label class="form-label" for="am_profile_status">Operational status</label>
                        <select class="filterSelect" data-mdb-select-init data-mdb-filter="true" data-mdb-container="#assetManagerAssetDetailHost" id="am_profile_status" name="operational_status">
                            <?php foreach (['active' => 'Active', 'available' => 'Available', 'in_use' => 'In use', 'under_repair' => 'Under repair', 'unavailable' => 'Unavailable'] as $value => $label) { ?>
                            <option value="<?= assetmanager_e($value) ?>" <?= $status === $value ? 'selected' : '' ?>><?= assetmanager_e($label) ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    <div class="col-12 col-md-3">
                        <label class="form-label" for="am_profile_class">Asset type</label>
                        <select class="filterSelect" data-mdb-select-init data-mdb-filter="true" data-mdb-container="#assetManagerAssetDetailHost" id="am_profile_class" name="asset_class">
                            <?php foreach ($assetClassLabels as $value => $label) { ?>
                            <option value="<?= assetmanager_e($value) ?>" <?= $currentAssetClass === (string)$value ? 'selected' : '' ?>><?= assetmanager_e($label) ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    <div class="col-12 col-md-2 d-flex align-items-end">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" value="1" id="am_profile_hire_enabled" name="hire_enabled" <?= $hireEnabled ? 'checked' : '' ?>>
                            <label class="form-check-label" for="am_profile_hire_enabled">Available for hire</label>
                        </div>
                    </div>
                    <div class="col-12 col-md-2">
                        <label class="form-label" for="am_profile_ownership">Ownership</label>
                        <select class="filterSelect" data-mdb-select-init data-mdb-filter="true" data-mdb-container="#assetManagerAssetDetailHost" id="am_profile_ownership" name="ownership_status">
                            <?php foreach ($ownershipLabels as $value => $label) { ?>
                            <option value="<?= assetmanager_e($value) ?>" <?= (string)($assetMeta['ownership_status'] ?? '') === (string)$value ? 'selected' : '' ?>><?= assetmanager_e($label) ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    </div>
                    </div>
                </div>
                <div class="assetmanager-form-section">
                    <div class="card-header assetmanager-form-section-title"><i class="fad fa-tags"></i> References And Responsibility</div>
                    <div class="assetmanager-form-section-body">
                    <div class="row g-2">
                    <div class="col-12 col-md-4">
                        <label class="form-label" for="am_profile_asset_tag">Asset tag</label>
                        <input type="text" class="form-control" id="am_profile_asset_tag" name="asset_tag" value="<?= assetmanager_e($assetMeta['asset_tag'] ?? '') ?>">
                    </div>
                    <div class="col-12 col-md-3">
                        <label class="form-label" for="am_profile_department">Department</label>
                        <input type="text" class="form-control" id="am_profile_department" name="department" value="<?= assetmanager_e($assetMeta['department'] ?? '') ?>">
                    </div>
                    <div class="col-12 col-md-3">
                        <label class="form-label" for="am_profile_custodian">Responsible person</label>
                        <input type="text" class="form-control" id="am_profile_custodian" name="custodian" value="<?= assetmanager_e($assetMeta['custodian'] ?? '') ?>">
                    </div>
                    <div class="col-12 col-md-2">
                        <label class="form-label" for="am_profile_supplier">Supplier</label>
                        <input type="text" class="form-control" id="am_profile_supplier" name="supplier" value="<?= assetmanager_e($assetMeta['supplier'] ?? '') ?>">
                    </div>
                    <div class="col-12 col-md-3" data-asset-context="vehicle">
                        <label class="form-label" for="am_profile_fleet">Fleet number</label>
                        <input type="text" class="form-control" id="am_profile_fleet" name="fleet_number" value="<?= assetmanager_e($assetMeta['fleet_number'] ?? '') ?>">
                    </div>
                    <div class="col-12 col-md-3" data-asset-context="vehicle">
                        <label class="form-label" for="am_profile_registration">Registration</label>
                        <input type="text" class="form-control" id="am_profile_registration" name="registration_mark" value="<?= assetmanager_e($assetMeta['registration_mark'] ?? '') ?>">
                    </div>
                    <div class="col-12 col-md-3" data-asset-context="vehicle">
                        <label class="form-label" for="am_profile_insurance_provider">Insurer</label>
                        <input type="text" class="form-control" id="am_profile_insurance_provider" name="insurance_provider" value="<?= assetmanager_e($assetMeta['insurance_provider'] ?? '') ?>">
                    </div>
                    <div class="col-12 col-md-3" data-asset-context="vehicle">
                        <label class="form-label" for="am_profile_insurance_policy">Policy number</label>
                        <input type="text" class="form-control" id="am_profile_insurance_policy" name="insurance_policy" value="<?= assetmanager_e($assetMeta['insurance_policy'] ?? '') ?>">
                    </div>
                    <div class="col-12 col-md-3" data-hire-context="enabled">
                        <label class="form-label" for="am_profile_hire_state">Hire status</label>
                        <select class="filterSelect" data-mdb-select-init data-mdb-filter="true" data-mdb-container="#assetManagerAssetDetailHost" id="am_profile_hire_state" name="hire_state">
                            <?php foreach ($hireStateLabels as $value => $label) { ?>
                            <option value="<?= assetmanager_e($value) ?>" <?= (string)($assetMeta['hire_state'] ?? '') === (string)$value ? 'selected' : '' ?>><?= assetmanager_e($label) ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    </div>
                    </div>
                </div>
                <div class="assetmanager-form-section">
                    <div class="card-header assetmanager-form-section-title"><i class="fad fa-calendar-check"></i> Compliance Dates And Readings</div>
                    <div class="assetmanager-form-section-body">
                    <div class="row g-2">
                    <?php foreach ([
                        'purchase_date' => ['Purchase date', ''],
                        'warranty_expires' => ['Warranty expires', ''],
                        'last_service_date' => ['Last service', 'plant vehicle electrical general tooling facility'],
                        'insurance_expires' => ['Insurance expires', 'vehicle'],
                        'mot_expires' => ['MOT expires', 'vehicle'],
                        'tax_expires' => ['Vehicle tax expires', 'vehicle'],
                        'pat_expires' => ['PAT expires', 'electrical'],
                    ] as $fieldName => $dateConfig) {
                        $label = $dateConfig[0];
                        $context = $dateConfig[1];
                    ?>
                    <div class="col-12 col-md-3"<?= $context !== '' ? ' data-asset-context="' . assetmanager_e($context) . '"' : '' ?>>
                        <label class="form-label" for="am_profile_<?= assetmanager_e($fieldName) ?>"><?= assetmanager_e($label) ?></label>
                        <div class="date-picker datepicker" data-date-type="open" data-mdb-toggle-button="false" data-mdb-container="#assetManagerAssetDetailHost">
                            <input type="text" class="form-control" id="am_profile_<?= assetmanager_e($fieldName) ?>" name="<?= assetmanager_e($fieldName) ?>" value="<?= assetmanager_e(assetmanager_format_date($assetMeta[$fieldName] ?? '')) ?>" data-mdb-confirm-date-on-select="true" data-mdb-toggle="datepicker">
                        </div>
                    </div>
                    <?php } ?>
                    <div class="col-12 col-md-3" data-asset-context="plant vehicle electrical tooling facility general">
                        <label class="form-label" for="am_profile_service_interval">Service interval</label>
                        <input type="text" class="form-control" id="am_profile_service_interval" name="service_interval" value="<?= assetmanager_e($assetMeta['service_interval'] ?? '') ?>">
                    </div>
                    <div class="col-12 col-md-3" data-asset-context="plant electrical tooling facility general">
                        <label class="form-label" for="am_profile_hours">Operating hours</label>
                        <input type="number" step="0.001" class="form-control" id="am_profile_hours" name="current_hours" value="<?= assetmanager_e($assetMeta['current_hours'] ?? '') ?>">
                    </div>
                    <div class="col-12 col-md-3" data-asset-context="vehicle">
                        <label class="form-label" for="am_profile_mileage">Mileage</label>
                        <input type="number" step="0.001" class="form-control" id="am_profile_mileage" name="current_mileage" value="<?= assetmanager_e($assetMeta['current_mileage'] ?? '') ?>">
                    </div>
                    </div>
                    </div>
                </div>
                <div class="assetmanager-form-section">
                    <div class="card-header assetmanager-form-section-title"><i class="fad fa-note-sticky"></i> Notes</div>
                    <div class="assetmanager-form-section-body">
                    <div class="row g-2">
                    <div class="col-12">
                        <label class="form-label" for="am_profile_notes">Operational notes</label>
                        <textarea class="form-control" id="am_profile_notes" name="notes" rows="3"><?= assetmanager_e($supplement['notes'] ?? '') ?></textarea>
                    </div>
                    </div>
                    </div>
                </div>
                <div class="text-end mt-3">
                    <button type="button" class="btn btn-success" onclick="assetManagerConfirmSupplementSave()">
                        <i class="fad fa-save"></i> Save
                    </button>
                </div>
            </form>
        </div>
    </div>
    <script>
    (function() {
        const host = document.getElementById('assetManagerAssetDetailHost');
        if (!host || !window.mdb) return;
        host.querySelectorAll('.filterSelect').forEach(function(selectEl) {
            if (!mdb.Select.getInstance || !mdb.Select.getInstance(selectEl)) {
                new mdb.Select(selectEl, {filter: true, container: '#assetManagerAssetDetailHost'});
            }
        });
        host.querySelectorAll('.datepicker').forEach(function(datepickerEl) {
            if (!mdb.Datepicker.getInstance || !mdb.Datepicker.getInstance(datepickerEl)) {
                new mdb.Datepicker(datepickerEl, {confirmDateOnSelect: true, format: 'dd-mm-yyyy', container: '#assetManagerAssetDetailHost'});
            }
        });
        host.querySelectorAll('.assetmanager-data-table').forEach(function(table) {
            const tbody = table.querySelector('tbody');
            if (!tbody) return;
            const allRows = Array.from(tbody.querySelectorAll('tr'));
            if (!allRows.length) return;
            const pageSize = 10;
            let page = 1;
            let sortIndex = -1;
            let sortDir = 1;
            const pager = document.createElement('div');
            pager.className = 'd-flex align-items-center justify-content-between gap-2 small text-muted mt-2';
            table.parentNode.appendChild(pager);

            function renderRows() {
                const rows = allRows.slice();
                if (sortIndex >= 0) {
                    rows.sort(function(a, b) {
                        const av = (a.children[sortIndex]?.innerText || '').trim().toLowerCase();
                        const bv = (b.children[sortIndex]?.innerText || '').trim().toLowerCase();
                        if (av < bv) return -1 * sortDir;
                        if (av > bv) return 1 * sortDir;
                        return 0;
                    });
                }
                const totalPages = Math.max(1, Math.ceil(rows.length / pageSize));
                page = Math.min(Math.max(1, page), totalPages);
                tbody.innerHTML = '';
                rows.slice((page - 1) * pageSize, page * pageSize).forEach(function(row) {
                    tbody.appendChild(row);
                });
                pager.innerHTML = '<span>Page ' + page + ' of ' + totalPages + '</span>' +
                    '<span class="d-flex gap-2">' +
                    '<button type="button" class="btn btn-sm btn-secondary" data-am-page="-1"><i class="fad fa-chevron-left"></i></button>' +
                    '<button type="button" class="btn btn-sm btn-secondary" data-am-page="1"><i class="fad fa-chevron-right"></i></button>' +
                    '</span>';
                pager.querySelectorAll('[data-am-page]').forEach(function(button) {
                    button.onclick = function() {
                        page += Number(button.getAttribute('data-am-page') || 0);
                        renderRows();
                    };
                });
            }

            table.querySelectorAll('thead th').forEach(function(th, index) {
                if (th.classList.contains('text-end')) return;
                th.style.cursor = 'pointer';
                th.addEventListener('click', function() {
                    if (sortIndex === index) {
                        sortDir *= -1;
                    } else {
                        sortIndex = index;
                        sortDir = 1;
                    }
                    page = 1;
                    renderRows();
                });
            });
            renderRows();
        });
    })();
    </script>
    <?php if ($moduleMaintenance) { ?>
    <div class="assetmanager-form-section mt-3">
        <div class="card-header assetmanager-form-section-title d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-2">
            <div>
                <span><i class="fad fa-calendar-check"></i> Maintenance Schedules</span>
                <div class="small fw-normal opacity-75">Planned service, compliance, and usage-based maintenance triggers.</div>
            </div>
            <button type="button" class="btn btn-secondary btn-sm" onclick="assetManagerOpenSchedule(<?= json_encode($source) ?>, <?= (int)$sourceId ?>, <?= json_encode($assetTitle) ?>)">
                <i class="fad fa-calendar-plus"></i> New Schedule
            </button>
        </div>
        <div class="assetmanager-form-section-body">
        <?php if (!assetmanager_table_exists($con, 'assetmanager_maintenance')) { ?>
        <div class="note note-warning mb-0">Maintenance table is not installed yet.</div>
        <?php } elseif (empty($schedules)) { ?>
        <div class="text-muted small">No maintenance schedules have been created for this asset.</div>
        <?php } else { ?>
        <div class="table-responsive">
            <table class="table table-sm align-middle mb-0 assetmanager-data-table">
                <thead class="table-light">
                    <tr>
                        <th>Type</th>
                        <th>Rule</th>
                        <th>Next Due</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($schedules as $schedule) {
                        $rule = $schedule['rule'] ?? [];
                        $interval = trim((string)($rule['interval_value'] ?? ''));
                        $unit = trim((string)($rule['interval_unit'] ?? ''));
                        $basis = trim((string)($rule['basis'] ?? 'date'));
                    ?>
                    <tr>
                        <td><?= assetmanager_e(ucwords(str_replace('_', ' ', (string)($schedule['schedule_type'] ?? 'maintenance')))) ?></td>
                        <td>
                            <?= assetmanager_e($interval !== '' && $interval !== '0' ? 'Every ' . $interval . ' ' . $unit : ucfirst($basis)) ?>
                            <?php if (!empty($rule['notes'])) { ?>
                            <div class="small text-muted"><?= assetmanager_e($rule['notes']) ?></div>
                            <?php } ?>
                        </td>
                        <td><?= assetmanager_e(assetmanager_format_date($schedule['next_due_at'] ?? '')) ?: '-' ?></td>
                        <td><span class="badge bg-secondary"><?= assetmanager_e(ucwords((string)($schedule['status_key'] ?? 'active'))) ?></span></td>
                    </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
        <?php } ?>
        </div>
    </div>
    <?php } ?>
    <?php if ($moduleUsage) { ?>
    <div class="assetmanager-form-section mt-3">
        <div class="card-header assetmanager-form-section-title d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-2">
            <div>
                <span><i class="fad fa-gauge-high"></i> Usage Logs</span>
                <div class="small fw-normal opacity-75">Operating hours, mileage, cycles, starts, fuel, and other readings.</div>
            </div>
            <button type="button" class="btn btn-secondary btn-sm" onclick="assetManagerOpenUsageLog(<?= json_encode($source) ?>, <?= (int)$sourceId ?>, <?= json_encode($assetTitle) ?>)">
                <i class="fad fa-gauge-high"></i> Log Usage
            </button>
        </div>
        <div class="assetmanager-form-section-body">
        <?php if (!assetmanager_table_exists($con, 'assetmanager_activity')) { ?>
        <div class="note note-warning mb-0">Activity table is not installed yet.</div>
        <?php } elseif (empty($usageLogs)) { ?>
        <div class="text-muted small">No usage readings have been logged for this asset.</div>
        <?php } else { ?>
        <div class="table-responsive">
            <table class="table table-sm align-middle mb-0 assetmanager-data-table">
                <thead class="table-light">
                    <tr>
                        <th>Reading</th>
                        <th>Type</th>
                        <th>Date</th>
                        <th>Notes</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($usageLogs as $log) { ?>
                    <tr>
                        <td><strong><?= assetmanager_e($log['reading_value'] ?? '') ?></strong> <?= assetmanager_e($log['reading_unit'] ?? '') ?></td>
                        <td><?= assetmanager_e(ucwords(str_replace('_', ' ', (string)($log['usage_type'] ?? '')))) ?></td>
                        <td><?= assetmanager_e(assetmanager_format_date($log['usage_at'] ?? '')) ?></td>
                        <td><?= assetmanager_e($log['payload']['notes'] ?? '-') ?></td>
                    </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
        <?php } ?>
        </div>
    </div>
    <?php } ?>
    <?php if ($moduleMaintenance) { ?>
    <div class="assetmanager-form-section mt-3">
        <div class="card-header assetmanager-form-section-title d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-2">
            <div>
                <span><i class="fad fa-clipboard-list-check"></i> Work Orders</span>
                <div class="small fw-normal opacity-75">Maintenance, defects, inspections follow-up, and service activity.</div>
            </div>
            <button type="button" class="btn btn-secondary btn-sm" onclick="assetManagerOpenWorkOrder(<?= json_encode($source) ?>, <?= (int)$sourceId ?>, <?= json_encode($assetTitle) ?>)">
                <i class="fad fa-plus"></i> New Work Order
            </button>
        </div>
        <div class="assetmanager-form-section-body">
        <?php if (!assetmanager_table_exists($con, 'assetmanager_maintenance')) { ?>
        <div class="note note-warning mb-0">Maintenance table is not installed yet.</div>
        <?php } elseif (empty($workOrders)) { ?>
        <div class="text-muted small">No work orders have been logged for this asset.</div>
        <?php } else { ?>
        <div class="table-responsive">
            <table class="table table-sm align-middle mb-0 assetmanager-data-table">
                <thead class="table-light">
                    <tr>
                        <th>Summary</th>
                        <th>Type</th>
                        <th>Priority</th>
                        <th>Due</th>
                        <th>Status</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($workOrders as $order) { ?>
                    <tr>
                        <td>
                            <strong><?= assetmanager_e($order['summary'] ?? '') ?></strong>
                            <?php if (!empty($order['details']['notes'])) { ?>
                            <div class="small text-muted"><?= assetmanager_e($order['details']['notes']) ?></div>
                            <?php } ?>
                        </td>
                        <td><?= assetmanager_e(ucwords(str_replace('_', ' ', (string)($order['work_type'] ?? '')))) ?></td>
                        <td><?= assetmanager_e(ucwords((string)($order['priority_key'] ?? 'normal'))) ?></td>
                        <td><?= assetmanager_e(assetmanager_format_date($order['due_at'] ?? '')) ?: '-' ?></td>
                        <td><span class="badge bg-secondary"><?= assetmanager_e(ucwords(str_replace('_', ' ', (string)($order['status_key'] ?? 'open')))) ?></span></td>
                        <td class="text-end">
                            <?php if (($order['status_key'] ?? '') === 'open') { ?>
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="assetManagerConfirmWorkOrderStatus(<?= (int)$order['id'] ?>, 'in_progress', <?= json_encode((string)($order['summary'] ?? '')) ?>)">
                                <i class="fad fa-play"></i>
                            </button>
                            <?php } ?>
                            <?php if (($order['status_key'] ?? '') !== 'complete') { ?>
                            <button type="button" class="btn btn-sm btn-outline-success" onclick="assetManagerConfirmWorkOrderStatus(<?= (int)$order['id'] ?>, 'complete', <?= json_encode((string)($order['summary'] ?? '')) ?>)">
                                <i class="fad fa-check"></i>
                            </button>
                            <?php } ?>
                        </td>
                    </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
        <?php } ?>
        </div>
    </div>
    <?php } ?>
    <?php if ($moduleDocuments) { ?>
    <div class="assetmanager-form-section mt-3">
        <div class="card-header assetmanager-form-section-title d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-2">
            <div>
                <span><i class="fad fa-folder-open"></i> Files And Documents</span>
                <div class="small fw-normal opacity-75">Manuals, certificates, service sheets, insurance, photos, and supporting evidence.</div>
            </div>
            <button type="button" class="btn btn-secondary btn-sm" onclick="assetManagerOpenFileUpload(<?= json_encode($source) ?>, <?= (int)$sourceId ?>, <?= json_encode($assetTitle) ?>)">
                <i class="fad fa-upload"></i> Upload File
            </button>
        </div>
        <div class="assetmanager-form-section-body">
        <?php if (!assetmanager_table_exists($con, 'assetmanager_documents')) { ?>
        <div class="note note-warning mb-0">Documents table is not installed yet.</div>
        <?php } elseif (empty($assetFiles)) { ?>
        <div class="text-muted small">No files have been uploaded for this asset.</div>
        <?php } else { ?>
        <div class="table-responsive">
            <table class="table table-sm align-middle mb-0 assetmanager-data-table">
                <thead class="table-light">
                    <tr>
                        <th>Title</th>
                        <th>Type</th>
                        <th>Uploaded</th>
                        <th>Expires</th>
                        <th class="text-end">Open</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($assetFiles as $file) {
                        $href = '../' . ltrim((string)($file['file_path'] ?? ''), '/');
                    ?>
                    <tr>
                        <td>
                            <strong><?= assetmanager_e($file['file_title'] ?? '') ?></strong>
                            <div class="small text-muted"><?= assetmanager_e($file['meta']['original_name'] ?? '') ?></div>
                        </td>
                        <td><?= assetmanager_e(ucwords(str_replace('_', ' ', (string)($file['file_type'] ?? 'document')))) ?></td>
                        <td><?= assetmanager_e(assetmanager_format_date($file['created_at'] ?? '')) ?></td>
                        <td><?= assetmanager_e(assetmanager_format_date($file['expires_at'] ?? '')) ?: '-' ?></td>
                        <td class="text-end">
                            <a class="btn btn-sm btn-outline-secondary" href="<?= assetmanager_e($href) ?>" target="_blank" rel="noopener">
                                <i class="fad fa-external-link"></i>
                            </a>
                        </td>
                    </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
        <?php } ?>
        </div>
    </div>
    <?php } ?>
</div>
