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

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

assetmanager_require_user();

$con = $GLOBALS['con'] ?? null;
if (!$con instanceof mysqli) {
    assetmanager_json_response(['success' => false, 'message' => 'Tenant database connection unavailable.']);
}
$con->set_charset('utf8mb4');

if (!assetmanager_table_exists($con, 'assetmanager_activity') || !assetmanager_table_exists($con, 'assetmanager_assets')) {
    assetmanager_json_response(['success' => false, 'setup_required' => true, 'message' => 'Asset Manager activity tables are not installed yet.']);
}

$clientnumber = enrep_request_int('clientnumber', 0);
$source = enrep_request_enum('source', ['enrep_item', 'assetmanager_item'], '');
$sourceId = enrep_request_int('source_id', 0);
if ($clientnumber <= 0 || $source === '' || $sourceId <= 0) {
    assetmanager_json_response(['success' => false, 'message' => 'Asset reference is required.']);
}
assetmanager_json_require_client_access($con, $clientnumber);
assetmanager_json_require_asset_access($con, $tenant, $clientnumber, $source, $sourceId);

$assetId = assetmanager_resolve_asset_id($con, $tenant, $clientnumber, $source, $sourceId, enrep_request_string('asset_title', '', 255), true);
if ($assetId <= 0) {
    assetmanager_json_response(['success' => false, 'message' => 'Asset could not be linked for event logging.']);
}

$eventType = enrep_request_string('event_type', '', 80);
if ($eventType === '') {
    assetmanager_json_response(['success' => false, 'message' => 'Event type is required.']);
}
$eventAt = assetmanager_parse_datetime(enrep_request_string('event_at', '', 40)) ?: date('Y-m-d H:i:s');
$payload = assetmanager_request_json_array('payload_json');
$payload['notes'] = enrep_request_string('notes', $payload['notes'] ?? '', 5000);
$payload['source'] = $source;
$payload['source_id'] = $sourceId;
$payloadJson = assetmanager_encode_json($payload);
$userId = assetmanager_actor_user_id();
$now = date('Y-m-d H:i:s');
$moduleKey = 'assets';
$parentType = 'asset';
$summary = ucwords(str_replace('_', ' ', $eventType));

$stmt = $con->prepare("
    INSERT INTO assetmanager_activity
        (tenant_key, clientnumber, asset_id, module_key, parent_type, parent_id, activity_type, activity_at, summary, payload_json, created_by, created_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
if (!$stmt) {
    assetmanager_json_response(['success' => false, 'message' => 'Asset event could not be prepared.']);
}
$stmt->bind_param('siississssis', $tenant, $clientnumber, $assetId, $moduleKey, $parentType, $assetId, $eventType, $eventAt, $summary, $payloadJson, $userId, $now);
$ok = $stmt->execute();
$eventId = $ok ? (int)$stmt->insert_id : 0;
$stmt->close();

if ($ok) {
    assetmanager_audit($con, $tenant, $clientnumber, $userId, 'asset_event', $eventId, 'create', [], [
        'asset_id' => $assetId,
        'event_type' => $eventType,
        'event_at' => $eventAt,
    ]);
}

assetmanager_json_response([
    'success' => $ok,
    'asset_event_id' => $eventId,
    'message' => $ok ? 'Asset event logged.' : 'Asset event could not be logged.',
]);
