<?php
/* Copyright (C) 2026 Alles Watt lauft
 *
 * AJAX endpoint to get file preview data for an installation element
 */

if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1');
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1');
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1');
if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1');

$res = 0;
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");

dol_include_once('/kundenkarte/class/anlagefile.class.php');
dol_include_once('/kundenkarte/class/anlage.class.php');

header('Content-Type: application/json');

// Permission check
if (!$user->hasRight('kundenkarte', 'read')) {
	http_response_code(403);
	echo json_encode(['error' => 'Permission denied']);
	exit;
}

$anlageId = GETPOSTINT('anlage_id');

if ($anlageId <= 0) {
	echo json_encode(array('error' => 'Invalid ID', 'files' => array()));
	exit;
}

// Get the anlage
$anlage = new Anlage($db);
if ($anlage->fetch($anlageId) <= 0) {
	echo json_encode(array('error' => 'Element not found', 'files' => array()));
	exit;
}

// Get all files for this element
$anlagefile = new AnlageFile($db);
$files = $anlagefile->fetchAllByAnlage($anlageId);

$images = array();
$documents = array();

foreach ($files as $file) {
	$fileData = array(
		'id' => $file->id,
		'name' => $file->filename,
		'url' => $file->getUrl(),
		'type' => $file->file_type,
		'is_pinned' => (int)$file->is_pinned,
		'is_cover' => (int)$file->is_cover,
	);

	if ($file->file_type == 'image') {
		// Add thumbnail URL for images
		$fileData['thumb_url'] = $file->getThumbnailUrl();
		$images[] = $fileData;
	} else {
		// Determine icon based on file type
		switch ($file->file_type) {
			case 'pdf':
				$fileData['icon'] = 'fa-file-pdf-o';
				$fileData['color'] = '#e74c3c';
				break;
			case 'archive':
				$fileData['icon'] = 'fa-file-archive-o';
				$fileData['color'] = '#9b59b6';
				break;
			default:
				// Check extension for more specific icons
				$ext = strtolower(pathinfo($file->filename, PATHINFO_EXTENSION));
				if (in_array($ext, array('doc', 'docx'))) {
					$fileData['icon'] = 'fa-file-word-o';
					$fileData['color'] = '#2980b9';
				} elseif (in_array($ext, array('xls', 'xlsx'))) {
					$fileData['icon'] = 'fa-file-excel-o';
					$fileData['color'] = '#27ae60';
				} elseif (in_array($ext, array('txt', 'rtf'))) {
					$fileData['icon'] = 'fa-file-text-o';
					$fileData['color'] = '#f39c12';
				} else {
					$fileData['icon'] = 'fa-file-o';
					$fileData['color'] = '#7f8c8d';
				}
		}
		$documents[] = $fileData;
	}
}

echo json_encode(array(
	'images' => $images,
	'documents' => $documents,
	'total_images' => count($images),
	'total_documents' => count($documents),
));
