<?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);
$assetTitle = enrep_request_string('asset_title', '', 255);

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_module($con, $tenant, $clientnumber, 'usage', 'Usage logging');
assetmanager_json_require_asset_access($con, $tenant, $clientnumber, $source, $sourceId);

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

$usageType = enrep_request_string('usage_type', 'hours', 80);
$readingRaw = enrep_request_string('reading_value', '', 40);
if ($readingRaw === '' || !is_numeric($readingRaw)) {
    assetmanager_json_response(['success' => false, 'message' => 'Reading value is required.']);
}
$readingValue = (string)((float)$readingRaw);
$readingUnit = enrep_request_string('reading_unit', 'hours', 40);
$usageAtRaw = enrep_request_string('usage_at', '', 40);
$usageTs = $usageAtRaw !== '' ? strtotime(str_replace('/', '-', $usageAtRaw)) : time();
$usageAt = date('Y-m-d H:i:s', $usageTs ?: time());
$payload = [
    'usage_type' => $usageType,
    'notes' => enrep_request_string('notes', '', 5000),
    'source' => $source,
    'source_id' => $sourceId,
];
$payloadJson = assetmanager_encode_json($payload);
$userId = assetmanager_actor_user_id();
$now = date('Y-m-d H:i:s');
$moduleKey = 'usage';
$parentType = 'asset';
$summary = 'Usage reading logged';

$stmt = $con->prepare("
    INSERT INTO assetmanager_activity
        (tenant_key, clientnumber, asset_id, module_key, parent_type, parent_id, activity_type, activity_at, summary, reading_value, reading_unit, payload_json, created_by, created_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
if (!$stmt) {
    assetmanager_json_response(['success' => false, 'message' => 'Usage log could not be prepared.']);
}
$stmt->bind_param('siississsdssis', $tenant, $clientnumber, $assetId, $moduleKey, $parentType, $assetId, $usageType, $usageAt, $summary, $readingValue, $readingUnit, $payloadJson, $userId, $now);
$ok = $stmt->execute();
$usageId = $ok ? (int)$stmt->insert_id : 0;
$stmt->close();

if ($ok) {
    $update = $con->prepare("
        UPDATE assetmanager_assets
        SET current_runtime_value=?, current_runtime_unit=?, updated_at=?
        WHERE id=? AND tenant_key=? AND clientnumber=?
    ");
    if ($update) {
        $update->bind_param('dssisi', $readingValue, $readingUnit, $now, $assetId, $tenant, $clientnumber);
        $update->execute();
        $update->close();
    }
    assetmanager_audit($con, $tenant, $clientnumber, $userId, 'usage_log', $usageId, 'create', [], [
        'asset_id' => $assetId,
        'usage_type' => $usageType,
        'reading_value' => $readingValue,
        'reading_unit' => $readingUnit,
        'usage_at' => $usageAt,
    ]);
}

assetmanager_json_response([
    'success' => $ok,
    'usage_id' => $usageId,
    'message' => $ok ? 'Usage reading logged.' : 'Usage reading could not be logged.',
]);
