<?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_json_response(['success' => false, 'setup_required' => true, 'message' => 'Asset Manager activity table is not installed yet.']);
}

$clientnumber = enrep_request_int('clientnumber', 0);
$notificationId = enrep_request_int('notification_id', 0);
if ($clientnumber <= 0) {
    assetmanager_json_response(['success' => false, 'message' => 'Client number is required.']);
}
assetmanager_json_require_client_access($con, $clientnumber);

$userId = assetmanager_actor_user_id();
$now = date('Y-m-d H:i:s');
if ($notificationId > 0) {
    $stmt = $con->prepare("
        UPDATE assetmanager_activity
        SET payload_json=JSON_SET(COALESCE(payload_json, JSON_OBJECT()), '$.read_at', ?)
        WHERE id=? AND tenant_key=? AND clientnumber=? AND module_key='system' AND activity_type='notification' AND (created_by IS NULL OR created_by=?)
        LIMIT 1
    ");
    if (!$stmt) {
        assetmanager_json_response(['success' => false, 'message' => 'Notification could not be prepared.']);
    }
    $stmt->bind_param('sisii', $now, $notificationId, $tenant, $clientnumber, $userId);
} else {
    $stmt = $con->prepare("
        UPDATE assetmanager_activity
        SET payload_json=JSON_SET(COALESCE(payload_json, JSON_OBJECT()), '$.read_at', ?)
        WHERE tenant_key=? AND clientnumber=? AND module_key='system' AND activity_type='notification' AND (created_by IS NULL OR created_by=?) AND JSON_UNQUOTE(JSON_EXTRACT(payload_json, '$.read_at')) IS NULL
    ");
    if (!$stmt) {
        assetmanager_json_response(['success' => false, 'message' => 'Notifications could not be prepared.']);
    }
    $stmt->bind_param('ssii', $now, $tenant, $clientnumber, $userId);
}
$ok = $stmt->execute();
$stmt->close();

assetmanager_json_response([
    'success' => $ok,
    'message' => $ok ? 'Notifications updated.' : 'Notifications could not be updated.',
]);
