<?php
/* Listet vorhandene Fotos im Upload-Ordner des Objekts auf.
 * Authentifizierung über Token in der URL.
 *
 * GET: token
 * Response: JSON { success: true, photos: [{ filename, url, size, date }] }
 */

if (!defined('NOLOGIN'))     define('NOLOGIN', '1');
if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1');
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1');
if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1');
if (!defined('NOREQUIREHTML'))  define('NOREQUIREHTML', '1');
if (!defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX', '1');

$res = 0;
if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; }
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php";
if (!$res) die("Include of main fails");

require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once __DIR__.'/../class/upload_token.class.php';

header('Content-Type: application/json; charset=utf-8');

// Token validieren
$token = (string) ($_REQUEST['token'] ?? '');
$tok = BerichtUploadToken::fetchValid($db, $token);

if (!$tok) {
    http_response_code(403);
    echo json_encode(array('success' => false, 'error' => 'Token ungültig oder abgelaufen'));
    exit;
}

// Upload-Ordner ermitteln
$upload_dir = $tok->getUploadDir();
if (!$upload_dir || !is_dir($upload_dir)) {
    echo json_encode(array('success' => true, 'photos' => array()));
    exit;
}

// Bilder auflisten
$files = dol_dir_list($upload_dir, 'files', 0, '\.(jpg|jpeg|png|gif)$', '', 'date', SORT_DESC);
$photos = array();

// Relative URL vom mobile_upload.php aus gesehen (liegt im Hauptordner, get_photo.php im ajax-Ordner)
$base_url = 'ajax/get_photo.php';

foreach ($files as $f) {
    $photos[] = array(
        'filename' => $f['name'],
        'url'      => $base_url . '?token=' . urlencode($token) . '&file=' . urlencode($f['name']),
        'size'     => $f['size'],
        'date'     => dol_print_date($f['date'], '%Y-%m-%d %H:%M'),
    );
}

echo json_encode(array(
    'success' => true,
    'photos'  => $photos,
    'count'   => count($photos),
));
