<?php
/* Copyright (C) 2026 Alles Watt lauft
 *
 * AJAX handler for equipment type icon upload
 * Accepts SVG and PNG files for schematic symbols
 */

$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 && 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';
dol_include_once('/kundenkarte/class/equipmenttype.class.php');

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

// Security check
if (!$user->admin && !$user->hasRight('kundenkarte', 'admin')) {
	echo json_encode(array('success' => false, 'error' => 'Access denied'));
	exit;
}

$action = GETPOST('action', 'aZ09');
$typeId = GETPOSTINT('type_id');

$response = array('success' => false);

// Directory for equipment type icons
$uploadDir = DOL_DATA_ROOT.'/kundenkarte/equipment_icons/';

// Create directory if not exists
if (!is_dir($uploadDir)) {
	dol_mkdir($uploadDir);
}

switch ($action) {
	case 'upload':
		if (empty($_FILES['icon_file']) || $_FILES['icon_file']['error'] !== UPLOAD_ERR_OK) {
			$response['error'] = 'No file uploaded or upload error';
			break;
		}

		$file = $_FILES['icon_file'];
		$fileName = dol_sanitizeFileName($file['name']);
		$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

		// Validate file type
		$allowedExtensions = array('svg', 'png');
		if (!in_array($fileExt, $allowedExtensions)) {
			$response['error'] = 'Invalid file type. Only SVG and PNG are allowed.';
			break;
		}

		// Validate MIME type
		$mimeType = mime_content_type($file['tmp_name']);
		$allowedMimes = array('image/svg+xml', 'image/png', 'text/plain', 'text/xml', 'application/xml');
		if (!in_array($mimeType, $allowedMimes)) {
			$response['error'] = 'Invalid MIME type: '.$mimeType;
			break;
		}

		// For SVG files, do basic security check
		if ($fileExt === 'svg') {
			$content = file_get_contents($file['tmp_name']);
			// Check for potentially dangerous content
			$dangerous = array('<script', 'javascript:', 'onload=', 'onerror=', 'onclick=', 'onmouseover=');
			foreach ($dangerous as $pattern) {
				if (stripos($content, $pattern) !== false) {
					$response['error'] = 'SVG contains potentially dangerous content';
					break 2;
				}
			}
		}

		// Generate unique filename
		$newFileName = 'icon_'.$typeId.'_'.dol_now().'.'.$fileExt;
		$destPath = $uploadDir.$newFileName;

		// Move uploaded file
		if (move_uploaded_file($file['tmp_name'], $destPath)) {
			// Update database
			$equipmentType = new EquipmentType($db);
			if ($equipmentType->fetch($typeId) > 0) {
				// Delete old icon file if exists
				if ($equipmentType->icon_file && file_exists($uploadDir.$equipmentType->icon_file)) {
					unlink($uploadDir.$equipmentType->icon_file);
				}

				$equipmentType->icon_file = $newFileName;
				$result = $equipmentType->update($user);

				if ($result > 0) {
					$response['success'] = true;
					$response['icon_file'] = $newFileName;
					$response['icon_url'] = DOL_URL_ROOT.'/document.php?modulepart=kundenkarte&file=equipment_icons/'.$newFileName;
				} else {
					$response['error'] = 'Database update failed';
					// Remove uploaded file on DB error
					unlink($destPath);
				}
			} else {
				$response['error'] = 'Equipment type not found';
				unlink($destPath);
			}
		} else {
			$response['error'] = 'Failed to move uploaded file';
		}
		break;

	case 'delete':
		$equipmentType = new EquipmentType($db);
		if ($equipmentType->fetch($typeId) > 0) {
			if ($equipmentType->icon_file && file_exists($uploadDir.$equipmentType->icon_file)) {
				unlink($uploadDir.$equipmentType->icon_file);
			}
			$equipmentType->icon_file = '';
			$result = $equipmentType->update($user);
			if ($result > 0) {
				$response['success'] = true;
			} else {
				$response['error'] = 'Database update failed';
			}
		} else {
			$response['error'] = 'Equipment type not found';
		}
		break;

	case 'get':
		$equipmentType = new EquipmentType($db);
		if ($equipmentType->fetch($typeId) > 0) {
			$response['success'] = true;
			$response['icon_file'] = $equipmentType->icon_file;
			if ($equipmentType->icon_file) {
				$response['icon_url'] = DOL_URL_ROOT.'/document.php?modulepart=kundenkarte&file=equipment_icons/'.$equipmentType->icon_file;
			}
		} else {
			$response['error'] = 'Equipment type not found';
		}
		break;

	default:
		$response['error'] = 'Unknown action';
}

echo json_encode($response);
$db->close();
