<?php
/* POST /api/delete_photo.php
 * Body: { relpath: "commande/SO.../IMG_xxx.jpg" }
 *
 * Löscht eine Datei aus dem Anhang-Verzeichnis eines Parent-Objekts
 * (gleiche Logik wie ajax/delete_attachment.php, nur mit JWT-Auth).
 */
require_once __DIR__.'/_inc.php';

api_authenticate();
global $db, $user;

if (!$user->hasRight('bericht', 'write')) api_fail('Permission denied', 403);

$in = api_input();
$relpath = (string) ($in['relpath'] ?? '');
if (empty($relpath)) api_fail('relpath fehlt');

if (!preg_match('#^(facture|commande|propal)/[^/]+/[^/]+$#', $relpath)) {
    api_fail('Pfad nicht erlaubt: '.$relpath, 403);
}

$full = bericht_resolve_data_path($relpath);
if (!$full || !file_exists($full)) api_fail('Datei nicht gefunden', 404);

if (!@unlink($full)) api_fail('Löschen fehlgeschlagen', 500);

// Thumbs bereinigen
$dir = dirname($full);
$base = pathinfo($full, PATHINFO_FILENAME);
$ext = pathinfo($full, PATHINFO_EXTENSION);
foreach (array('_mini', '_small') as $suffix) {
    $thumb = $dir.'/thumbs/'.$base.$suffix.'.'.$ext;
    if (file_exists($thumb)) @unlink($thumb);
}

// ECM cleanup
$db->query("DELETE FROM ".$db->prefix()."ecm_files"
    ." WHERE filepath = '".$db->escape(dirname($relpath))."'"
    ." AND filename = '".$db->escape(basename($relpath))."'");

api_ok(array('deleted' => $relpath));
