<?php
/* Copyright (C) 2026 Alles Watt lauft
 *
 * AJAX handler for equipment type block image upload
 * Accepts image files for SchematicEditor block display
 */

$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 block images
$uploadDir = DOL_DATA_ROOT.'/kundenkarte/block_images/';

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

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

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

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

		// Validate MIME type
		$mimeType = mime_content_type($file['tmp_name']);
		$allowedMimes = array('image/svg+xml', 'image/png', 'image/jpeg', 'image/gif', 'image/webp', '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 = 'block_'.$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 block image file if exists
				if ($equipmentType->block_image && file_exists($uploadDir.$equipmentType->block_image)) {
					unlink($uploadDir.$equipmentType->block_image);
				}

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

				if ($result > 0) {
					$response['success'] = true;
					$response['block_image'] = $newFileName;
					$response['block_image_url'] = DOL_URL_ROOT.'/document.php?modulepart=kundenkarte&file=block_images/'.$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->block_image && file_exists($uploadDir.$equipmentType->block_image)) {
				unlink($uploadDir.$equipmentType->block_image);
			}
			$equipmentType->block_image = '';
			$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['block_image'] = $equipmentType->block_image;
			if ($equipmentType->block_image) {
				$response['block_image_url'] = DOL_URL_ROOT.'/document.php?modulepart=kundenkarte&file=block_images/'.$equipmentType->block_image;
			}
		} else {
			$response['error'] = 'Equipment type not found';
		}
		break;

	case 'select':
		// Select an existing image from the block_images folder
		$selectedImage = GETPOST('image', 'alphanohtml');
		if (empty($selectedImage)) {
			$response['error'] = 'No image selected';
			break;
		}

		// Path-Traversal-Schutz: nur Dateiname ohne Verzeichnisanteile
		$selectedImage = basename($selectedImage);

		// Validate that the image exists
		$imagePath = $uploadDir . $selectedImage;
		if (!file_exists($imagePath)) {
			$response['error'] = 'Image file not found';
			break;
		}

		// Validate file extension
		$fileExt = strtolower(pathinfo($selectedImage, PATHINFO_EXTENSION));
		$allowedExtensions = array('svg', 'png', 'jpg', 'jpeg', 'gif', 'webp');
		if (!in_array($fileExt, $allowedExtensions)) {
			$response['error'] = 'Invalid file type';
			break;
		}

		$equipmentType = new EquipmentType($db);
		if ($equipmentType->fetch($typeId) > 0) {
			$equipmentType->block_image = $selectedImage;
			$result = $equipmentType->update($user);
			if ($result > 0) {
				$response['success'] = true;
				$response['block_image'] = $selectedImage;
				$response['block_image_url'] = DOL_URL_ROOT.'/document.php?modulepart=kundenkarte&file=block_images/'.urlencode($selectedImage);
			} else {
				$response['error'] = 'Database update failed';
			}
		} else {
			$response['error'] = 'Equipment type not found';
		}
		break;

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

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