<?php
// /var/www/html/jobs/delete-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 = intval($data['reference_id'] ?? 0);
    $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 = "DELETE FROM genericdatacontainer 
            WHERE gdc_obj_type = '$objType'
            AND gdc_obj_id = $referenceId
            AND gdc_gen_fieldname = 'file_upload'
            AND gdc_content = '$filename'
            AND gdc_context = '$context'";
    
    $conn->query($sql);
    
    $affectedRows = $conn->affected_rows;
    
    $conn->close();
    
    if ($affectedRows > 0) {
        echo json_encode(['success' => true, 'deleted' => $affectedRows . " " . $sql]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Eintrag nicht gefunden '. $sql]);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
} catch (Error $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}