<?php
include 'cookie.php';
require_once 'mail.php';

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

try {
	$input = file_get_contents('php://input');
	$data = json_decode($input, true);

	if (!$data) {
		throw new Exception('Hibás JSON adatok');
	}

	if (empty($data['description']) || empty($data['url'])) {
		throw new Exception('Hiányzó kötelező mezők');
	}

	$bugReportDir = 'bugreport';
	if (!is_dir($bugReportDir)) {
		mkdir($bugReportDir, 0755, true);
	}

	$timestamp = date('Y-m-d_H-i-s');
	$randomId = substr(md5(uniqid()), 0, 8);
	$filePrefix = $timestamp . '_' . $randomId;

	$attachments = [];
	$toEmailAttachments = [];

	// Console logok mentése (log.txt)
	if (!empty($data['logs'])) {
		$logFile = $bugReportDir . '/log_' . $filePrefix . '.txt';
		$logContent = "=== CONSOLE LOGS ===\n";
		$logContent .= "Időpont: " . ($data['timestamp'] ?? date('c')) . "\n";
		$logContent .= "URL: " . $data['url'] . "\n";
		$logContent .= "User Agent: " . ($data['userAgent'] ?? 'N/A') . "\n";
		$logContent .= "\n=== FELHASZNÁLÓ ADATAI ===\n";
		$logContent .= "Név: ". (isset($userName) ? $userName : 'N/A') . " (" . (isset($userID) ? $userID : 'N/A') . ")" . "\n";
		$logContent .= "Jogosultságok: ". (isset($userPermsList) ? $userPermsList : 'N/A') ." \n";
		$logContent .= "Hiba leírása: " . ($data['description'] ?? 'N/A') . "\n";
		$logContent .= "\n=== LOGOK ===\n";
		foreach ($data['logs'] as $log) {
			$logContent .= $log . "\n";
		}

		file_put_contents($logFile, $logContent);
		$attachments[] = $logFile;
		$toEmailAttachments[] = $logFile;
	}

	// Browser adatok mentése (browser.txt)
	if (!empty($data['browserData'])) {
		$browserFile = $bugReportDir . '/browser_' . $filePrefix . '.txt';

		$browserContent = "\n=== FELHASZNÁLÓ ADATAI ===\n";
		$browserContent .= "Név: ". (isset($userName) ? $userName : 'N/A') . " (" . (isset($userID) ? $userID : 'N/A') . ")" . "\n";
		$browserContent .= "Jogosultságok: ". (isset($userPermsList) ? $userPermsList : 'N/A') ." \n";
		$browserContent .= "Hiba leírása: " . ($data['description'] ?? 'N/A') . "\n";
		$browserContent .= "\n=== Böngésző adatai ===\n";
		foreach ($data['browserData'] as $browser) {
			$browserContent .= $browser . "\n";
		}

		file_put_contents($browserFile, $browserContent);
		$attachments[] = $browserFile;
	}

	// Screenshot mentése
	if (!empty($data['screenshot'])) {
		$screenshotFile = $bugReportDir . '/screenshot_' . $filePrefix . '.png';

		$screenshotData = $data['screenshot'];
		if (strpos($screenshotData, 'data:image/png;base64,') === 0) {
			$screenshotData = substr($screenshotData, strlen('data:image/png;base64,'));
		}

		$decodedImage = base64_decode($screenshotData);
		if ($decodedImage !== false) {
			file_put_contents($screenshotFile, $decodedImage);
			$attachments[] = $screenshotFile;
			$toEmailAttachments[] = $screenshotFile;
		}
	}

	if (!empty($data['screenshotFull'])) {
		$screenshotFile = $bugReportDir . '/screenshotFull_' . $filePrefix . '.png';

		$screenshotData = $data['screenshotFull'];
		if (strpos($screenshotData, 'data:image/png;base64,') === 0) {
			$screenshotData = substr($screenshotData, strlen('data:image/png;base64,'));
		}

		$decodedImage = base64_decode($screenshotData);
		if ($decodedImage !== false) {
			file_put_contents($screenshotFile, $decodedImage);
			$attachments[] = $screenshotFile;
			$toEmailAttachments[] = $screenshotFile;
		}
	}

	if (!empty($data['screenshotPainted'])) {
		$screenshotFile = $bugReportDir . '/screenshotPainted_' . $filePrefix . '.png';

		$screenshotData = $data['screenshotPainted'];
		if (strpos($screenshotData, 'data:image/png;base64,') === 0) {
			$screenshotData = substr($screenshotData, strlen('data:image/png;base64,'));
		}

		$decodedImage = base64_decode($screenshotData);
		if ($decodedImage !== false) {
			file_put_contents($screenshotFile, $decodedImage);
			$attachments[] = $screenshotFile;
			$toEmailAttachments[] = $screenshotFile;
		}
	}

	// Email tartalom összeállítása

	$AttachmentsDiff = array_diff($attachments, $toEmailAttachments);

	$subject = 'BUG REPORT - ' . date('Y-m-d H:i:s');

	$emailContent = "<h2>=== SZATURNUSZ HIBABEJELENTÉS ===</h2><br><br>";
	$emailContent .= "<b>FELHASZNÁLÓ ADATOK:</b><br>";
	$emailContent .= "<b>Név: </b>" . (isset($userName) ? $userName : 'N/A') . " (" . (isset($userID) ? $userID : 'N/A') . ")" . "<br>";
	$emailContent .= "<b>Jogosultságok: </b>" . (isset($userPermsList) ? $userPermsList : 'N/A') . "<br><br>";

	$emailContent .= "<b>HIBA LEÍRÁSA:</b><br>";
	$emailContent .= $data['description'] . "<br><br>";

	$emailContent .= "<b>TECHNIKAI ADATOK</b>:<br>";
	$emailContent .= "<b>URL: </b>" . $data['url'] . "<br>";
	$emailContent .= "<b>Időpont: </b>" . ($data['timestamp'] ?? date('c')) . "<br>";
	$emailContent .= "<b>User Agent: </b>" . ($data['userAgent'] ?? 'N/A') . "<br>";
	$emailContent .= "<b>Szerver IP: </b>" . $_SERVER['SERVER_ADDR'] . "<br>";
	$emailContent .= "<b>Kliens IP: </b>" . $_SERVER['REMOTE_ADDR'] . "<br><br>";

	$emailContent .= "<b>CSATOLMÁNYOK:</b><br>";
	foreach ($toEmailAttachments as $attachment) {
		$emailContent .= "- " . basename($attachment) . "<br>";
	}

	$emailContent .= "<br><b>SZERVEREN PLUSZ FÁJL:</b><br>";
	foreach ($AttachmentsDiff as $attachment) {
		$emailContent .= "- " . basename($attachment) . "<br>";
	}


	// Email küldése
	$recipient_email = 'sperg.tamas@gmail.com';
	$recipient_name = 'Sperg Tamás';

	$attachment_path = null;
	$zipFile = null;
	$zip = null;
	if (count($toEmailAttachments) === 1) {
		$attachment_path = $toEmailAttachments[0];
	} elseif (count($toEmailAttachments) > 1) {
		$zipFile = $bugReportDir . '/report_' . $filePrefix . '.zip';
		$zip = new ZipArchive();

		if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
			foreach ($toEmailAttachments as $file) {
				$zip->addFile($file, basename($file));
			}
			$zip->close();
			$attachment_path = $zipFile;
		}
	}

	$res_mail = sendFormattedEmail($recipient_email, $recipient_name, $subject, $emailContent, $attachment_path);

	/* Csatolmány Management */
	if (isset($zipFile) && file_exists($zipFile)) {
		foreach ($toEmailAttachments as $file) {
			if (file_exists($file)) {
				unlink($file);
			}
		}
	}

	if (count($AttachmentsDiff) > 0) {

		if ($zip == null) {
			$zipFile = $bugReportDir . '/report_' . $filePrefix . '.zip';
			$zip = new ZipArchive();
		}

		if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
			foreach ($AttachmentsDiff as $file) {
				$zip->addFile($file, basename($file));
			}
			$zip->close();
		}

		foreach ($AttachmentsDiff as $file) {
			if (file_exists($file)) {
				unlink($file);
			}
		}
	}

	echo json_encode([
		'success' => true,
		'message' => 'Hibabejelentés sikeresen elküldve',
		'email_result' => $res_mail
	]);

} catch (Exception $e) {
	http_response_code(500);
	echo json_encode([
		'success' => false,
		'error' => $e->getMessage()
	]);
}
?>
