<?php
// /var/www/html/jobs/save-file-upload.php
error_reporting(0);
header('Content-Type: application/json');
try {
    include_once("../include/glob_defs.inc.php");
    
    // Direkte MySQLi-Verbindung
    $conn = new mysqli($dbhostOnly, $dblogin, $dbpassword, $dbname, $dbport);
    
    if ($conn->connect_error) {
        echo json_encode(['success' => false, 'error' => 'DB-Verbindung fehlgeschlagen']);
        exit;
    }
    
    $conn->query('SET NAMES latin1');
    
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    
    if (!$data) {
        echo json_encode(['success' => false, 'error' => 'Keine Daten']);
        exit;
    }
    
    $objType = ($data['upload_type'] != 0) ? 'tr' : 'jb';
    $referenceId = $conn->real_escape_string($data['reference_id'] ?? '');
    $filename = $conn->real_escape_string($data['filename'] ?? '');
    $viewUrl = $conn->real_escape_string($data['view_url'] ?? '');
    $counter = intval($data['counter'] ?? 0);
    $remark = $conn->real_escape_string($data['remark'] ?? '');
    $remark = str_replace('|', ' ', $remark);
    $context = $conn->real_escape_string($remark . '|' . $viewUrl . '|' . $counter);
    
    $sql = "INSERT INTO genericdatacontainer 
            (gdc_obj_type, gdc_obj_id, gdc_gen_fieldname, gdc_content, gdc_context) 
            VALUES ('$objType', $referenceId, 'file_upload', '$filename', '$context')";
    
    $conn->query($sql);
    
    $insertId = $conn->insert_id;
    
    $conn->close();
    
    echo json_encode(['success' => true, 'gdc_id' => $insertId]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
} catch (Error $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}