<?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_documents') || !assetmanager_table_exists($con, 'assetmanager_assets')) {
    assetmanager_json_response(['success' => false, 'setup_required' => true, 'message' => 'Asset Manager document 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, 'documents', 'Documents');
assetmanager_json_require_asset_access($con, $tenant, $clientnumber, $source, $sourceId);

if (empty($_FILES['asset_file']) || !is_array($_FILES['asset_file'])) {
    assetmanager_json_response(['success' => false, 'message' => 'Choose a file to upload.']);
}

$file = $_FILES['asset_file'];
if ((int)($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
    assetmanager_json_response(['success' => false, 'message' => 'The file upload failed.']);
}

$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 file storage.']);
}

$originalName = enrep_safe_filename((string)($file['name'] ?? 'asset-file'));
$extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
$allowedExtensions = ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx', 'xls', 'xlsx', 'csv', 'txt'];
if (!in_array($extension, $allowedExtensions, true)) {
    assetmanager_json_response(['success' => false, 'message' => 'This file type is not allowed.']);
}

$tenantRoot = dirname(__DIR__) . '/../' . $tenant;
$tenantRoot = realpath($tenantRoot);
if ($tenantRoot === false) {
    assetmanager_json_response(['success' => false, 'message' => 'Tenant storage path could not be resolved.']);
}

$relativeDir = 'assetmanager/files/client_' . $clientnumber . '/asset_' . $assetId;
$targetDir = $tenantRoot . '/' . $relativeDir;
if (!is_dir($targetDir) && !mkdir($targetDir, 0755, true)) {
    assetmanager_json_response(['success' => false, 'message' => 'Asset file folder could not be created.']);
}

$basename = pathinfo($originalName, PATHINFO_FILENAME);
$basename = preg_replace('/[^A-Za-z0-9._ -]/', '_', $basename);
$basename = trim((string)$basename, " .\t\n\r\0\x0B");
if ($basename === '') {
    $basename = 'asset-file';
}

$storedName = $basename . '-' . date('YmdHis') . '-' . substr(bin2hex(random_bytes(4)), 0, 8) . '.' . $extension;
$targetPath = $targetDir . '/' . $storedName;

if (!move_uploaded_file((string)$file['tmp_name'], $targetPath)) {
    assetmanager_json_response(['success' => false, 'message' => 'Asset file could not be stored.']);
}

$fileTitle = enrep_request_string('file_title', $basename, 255);
$fileType = enrep_request_string('file_type', 'document', 80);
$expiresRaw = enrep_request_string('expires_at', '', 40);
$expiresAt = null;
if ($expiresRaw !== '') {
    $expiresTs = strtotime(str_replace('/', '-', $expiresRaw));
    if ($expiresTs) {
        $expiresAt = date('Y-m-d', $expiresTs);
    }
}

$relativePath = $relativeDir . '/' . $storedName;
$meta = [
    'original_name' => $originalName,
    'extension' => $extension,
    'source' => $source,
    'source_id' => $sourceId,
];
$metaJson = assetmanager_encode_json($meta);
$userId = assetmanager_actor_user_id();
$now = date('Y-m-d H:i:s');
$moduleKey = 'assets';
$parentType = 'asset';
$mimeType = (string)($file['type'] ?? '');
$fileSize = (int)($file['size'] ?? 0);

$stmt = $con->prepare("
    INSERT INTO assetmanager_documents
        (tenant_key, clientnumber, asset_id, module_key, parent_type, parent_id, document_type, title, file_path, mime_type, file_size, expires_at, payload_json, uploaded_by, created_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
if (!$stmt) {
    @unlink($targetPath);
    assetmanager_json_response(['success' => false, 'message' => 'Asset file metadata could not be prepared.']);
}
$stmt->bind_param('siississssissis', $tenant, $clientnumber, $assetId, $moduleKey, $parentType, $assetId, $fileType, $fileTitle, $relativePath, $mimeType, $fileSize, $expiresAt, $metaJson, $userId, $now);
$ok = $stmt->execute();
$fileId = $ok ? (int)$stmt->insert_id : 0;
$stmt->close();

if (!$ok) {
    @unlink($targetPath);
    assetmanager_json_response(['success' => false, 'message' => 'Asset file metadata could not be saved.']);
}

assetmanager_audit($con, $tenant, $clientnumber, $userId, 'asset_file', $fileId, 'upload', [], [
    'asset_id' => $assetId,
    'file_title' => $fileTitle,
    'file_path' => $relativePath,
]);

assetmanager_json_response([
    'success' => true,
    'file_id' => $fileId,
    'message' => 'Asset file uploaded.',
]);
