<?php
	 use PHPMailer\PHPMailer\PHPMailer;
	use PHPMailer\PHPMailer\SMTP;
	use PHPMailer\PHPMailer\Exception;
	require 'vendor/autoload.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $selectedOption = $_POST["option"];

  if ($selectedOption == "SMTP-AUTH") {
   

// Create a new PHPMailer object
$mail = new PHPMailer(true);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    try {
        // Set the mailer to use SMTP
        $mail->isSMTP();

        // Enable SMTP debugging 
        $mail->SMTPDebug = SMTP::DEBUG_OFF;
		$mail->SMTPDebug = 1;

        // Set the hostname of the mail server
        $mail->Host = $_POST['smtp'];

        // Set the SMTP port number - 587 for authenticated TLS
        $mail->Port = $_POST['port'];

        // Set the encryption mechanism to use - STARTTLS or SMTPS
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

        // Whether to use SMTP authentication
		$mail->SMTPAuth = true;

		  // Username to use for SMTP authentication
		   $mail->Username = $_POST['smtp_username'];
		  // Password to use for SMTP authentication
			$mail->Password = $_POST['smtp_password'];

        // Set the sender's email address
        $mail->setFrom($_POST['sender_email']);

        // Get the recipient email addresses from a file
		$file = fopen($_FILES['recipient_file']['tmp_name'], 'r');
        while (($line = fgetcsv($file)) !== false) {
            $mail->addAddress($line[0], $line[1]);
        }
        fclose($file);

        // Set the email subject
        $mail->Subject = $_POST['subject'];

        // Set the email body
        if ($_POST['format'] == 'html') {
            $mail->isHTML(true);
            $mail->Body = $_POST['message'];
        } else {
            $mail->isHTML(false);
            $mail->Body = strip_tags($_POST['message']);
        }

        // Add attachments
        if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == UPLOAD_ERR_OK) {
            $mail->addAttachment($_FILES['attachment']['tmp_name'], $_FILES['attachment']['name']);
        }

        // Send the email
        $mail->send();
        echo 'Message has been sent';
    } catch (Exception $e) {
        echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}
    echo "Možnosť 1 bola vybraná.";
  } elseif ($selectedOption == "SMTP-NOAUTH") {

	// Create a new PHPMailer object
	$mail = new PHPMailer(true);

	if ($_SERVER['REQUEST_METHOD'] == 'POST') {

		try {
			// Set the mailer to use SMTP
			$mail->isSMTP();

			// Enable SMTP debugging 
			$mail->SMTPDebug = SMTP::DEBUG_OFF;
			$mail->SMTPDebug = 1;
			$mail->SMTPOptions = array (
			'ssl' => array(
				'verify_peer'  => false,
				'verify_peer_name'  => false,
				'allow_self_signed' => true));


			// Set the hostname of the mail server
			$mail->Host = $_POST['smtp'];

			// Set the SMTP port number - 587 for authenticated TLS
			$mail->Port = $_POST['port'];

			// Set the encryption mechanism to use - STARTTLS or SMTPS
			//$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

			// Whether to use SMTP authentication
			//$mail->SMTPAuth = false;

			  // Username to use for SMTP authentication
			  // $mail->Username = $_POST['smtp_username'];
			  // Password to use for SMTP authentication
			  //  $mail->Password = $_POST['smtp_password'];

			// Set the sender's email address
			$mail->setFrom($_POST['sender_email']);

			// Get the recipient email addresses from a file
			$file = fopen($_FILES['recipient_file']['tmp_name'], 'r');
			while (($line = fgetcsv($file)) !== false) {
				$mail->addAddress($line[0], $line[1]);
			}
			fclose($file);

			// Set the email subject
			$mail->Subject = $_POST['subject'];
			$mail->CharSet = 'UTF-8';


			// Set the email body
			if ($_POST['format'] == 'html') {
				$mail->isHTML(true);
				$mail->Body = $_POST['message'];
			} else {
				$mail->isHTML(false);
				$mail->Body = strip_tags($_POST['message']);
			}

			// Add attachments
			if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == UPLOAD_ERR_OK) {
				$mail->addAttachment($_FILES['attachment']['tmp_name'], $_FILES['attachment']['name']);
			}

			// Send the email
			$mail->send();
			echo 'Message has been sent';
		} catch (Exception $e) {
			echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
		}
	}
		echo "Možnosť 2 bola vybraná.";
	  } else {
		// Neplatná voľba, vykonajte príslušné kroky
		echo "Neplatná voľba.";
	  }
	}
?>
<html>
<head>
	<title>Radiobutton Example</title>
</head>
<body>
<style>
body {
  font-family: Arial, sans-serif;
  background-color: #f2f2f2;
}

h2 {
  color: #333;
}

label {
  display: block;
  margin-bottom: 5px;
}
form {
  margin: 0 auto;
}

input[type="text"],
input[type="email"],
input[type="password"],
textarea {
  width: 30%;
  padding: 10px;
  border-radius: 5px;
  border: 1px solid #ccc;
  box-sizing: border-box;
  margin-bottom: 10px;
}

input[type="file"] {
  margin-top: 5px;
}

fieldset {
  margin-bottom: 20px;
  padding: 10px;
  border-radius: 5px;
  border: 1px solid #ccc;
  text-align: left;
}

legend {
  font-weight: bold;
}

button[type="submit"] {
  padding: 10px 20px;
  background-color: #4CAF50;
  border: none;
  color: #fff;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}

button[type="button"] {
  padding: 5px 10px;
  background-color: #ccc;
  border: none;
  color: #333;
  border-radius: 5px;
  cursor: pointer;
  margin-right: 5px;
}

button[type="button"]:hover {
  background-color: #ddd;
}

input[type="radio"] {
  margin-right: 5px;
}

textarea {
  height: 150px;
}
</style>

<h2>Emailový Formulár </h2>
<p>Ak chcete odoslať e-mail, vyplňte formulár nižšie:</p>

<form action="" method="post" enctype="multipart/form-data">

    <!-- User Information -->
    <fieldset>
        <legend>Uživateľské údaje</legend>
        <label for="sender_email">Email odosielateľa:</label>
		<input type="email" name="sender_email" id="sender_email" required>   
    </fieldset>

    <fieldset>
        <legend id="smtpLegend">SMTP Nastavenie</legend>
        <div id="smtpSettings">
            <input type="radio" name="option" value="SMTP-AUTH" onchange="zobrazitPole()"> SMTP s AUTH<br>
            <input type="radio" name="option" value="SMTP-NOAUTH" onchange="zobrazitPole()"> SMTP bez AUTH<br>
            <div id="smtp_username" style="display: none;">
                <label for="smtp_username">SMTP Prihlasovacie meno:</label>
                <input type="text" name="smtp_username">
            </div>

            <div id="smtp_password" style="display: none;">
                <label for="smtp_password">SMTP Heslo:</label>
                <input type="password" name="smtp_password">
            </div>
        </div>

        <script>
        function zobrazitPole() {
            var option = document.querySelector('input[name="option"]:checked').value;
            var smtp_username = document.getElementById("smtp_username");
            var smtp_password = document.getElementById("smtp_password");

            if (option === "SMTP-AUTH") {
                smtp_username.style.display = "block";
                smtp_password.style.display = "block";
            } else {
                smtp_username.style.display = "none";
                smtp_password.style.display = "none";
            }
        }
        </script>

        <label for="smtp">SMTP Server:</label>
        <input type="text" name="smtp" id="smtp" required>
        <br>
        <label for="port">SMTP Port:</label>
        <input type="text" name="port" id="port" required>
        <br>
        <label for="smtpsettings">SMTP Nastavenie:</label>
        <br>
        <button type="button" onclick="fillGmail()">Gmail</button>
        <button type="button" onclick="fillOutlook365()">Outlook 365</button>
        <button type="button" onclick="customSMTP()">Vlastné</button>
    </fieldset>

    <!-- Recipient Information -->
    <fieldset>
        <legend> Informácie o príjemcovi</legend>
		<label for="recipient_file">Súbor s príjemcami:</label>
		<input type="file" name="recipient_file" id="recipient_file" accept=".csv" style="display: none">
		<button type="button" onclick="document.getElementById('recipient_file').click()">Vybrať súbor</button>
    </fieldset>

    <!-- Email Content -->
    <fieldset>
        <legend>Obsah e-mailu</legend>
        <label for="subject">Predmet:</label>
        <input type="text" name="subject" id="subject" required>
        <br>
        <label for="message">Správa:</label>
        <br>
        <textarea name="message" id="message" required></textarea>
        <br>
        <label for="format">Formátovanie:</label>
        <label><input type="radio" name="format" id="plain" value="plain" checked>Plain Text</label>
        <label><input type="radio" name="format" id="html" value="html">HTML</label>
        <br>
        <label for="attachment">Príloha:</label>
		<input type="file" name="attachment" id="attachment" accept=".pdf, .doc, .docx, .txt" style="display: none">
		<button type="button" onclick="document.getElementById('attachment').click()">Vybrať súbor</button>

    </fieldset>

    <fieldset>
        <button type="button" onclick="document.getElementById('recipient_file').click()">Načítať zo súboru</button>

        <br><br>
        <textarea id="emails" rows="10" cols="50" style="display:none"></textarea>
        <br><br>
        <button type="button" onclick="document.getElementById('file-input').click()">Vybrať náhodný email</button>

        <br><br>
        <div id="dialog" style="display:none">
            <p>Vyberte súbor s e-mailami:</p>
            <input type="file" id="file-input">
        </div>
    </fieldset>

    <!-- Submit Button -->
    <button type="submit">Poslať email</button>

</form>

<script>
    const smtpLegend = document.getElementById("smtpLegend");
    const smtpSettings = document.getElementById("smtpSettings");

    smtpLegend.addEventListener("click", function() {
        if (smtpSettings.style.display === "none") {
            smtpSettings.style.display = "block";
        } else {
            smtpSettings.style.display = "none";
        }
    });

    function fillGmail() {
        document.getElementById('smtp').value = 'smtp.gmail.com';
        document.getElementById('port').value = '587';
    }

    function fillOutlook365() {
        document.getElementById('smtp').value = 'smtp.office365.com';
        document.getElementById('port').value = '587';
    }

    function customSMTP() {
        document.getElementById('smtp').value = '';
        document.getElementById('port').value = '';
    }

    function openHelp() {
        window.open("help.html", "Help", "width=800,height=800");
    }

    document.getElementById("helpButton").addEventListener("click", openHelp);

    const loadEmailsButton = document.getElementById("load-emails");
    const emailsTextarea = document.getElementById("emails");
    const selectEmailButton = document.getElementById("select-email");
    const dialog = document.getElementById("dialog");
    const fileInput = document.getElementById("file-input");

    loadEmailsButton.addEventListener("click", function() {
        dialog.style.display = "block";
    });

    fileInput.addEventListener("change", function(e) {
        const file = e.target.files[0];
        const reader = new FileReader();
        
        reader.onload = function(e) {
            const contents = e.target.result;
            emailsTextarea.value = contents;
            emailsTextarea.style.display = "block";
        };
        
        reader.readAsText(file);
    });

    selectEmailButton.addEventListener("click", function() {
        const emails = emailsTextarea.value.trim().split("\n");
        const randomIndex = Math.floor(Math.random() * emails.length);
        const randomEmail = emails[randomIndex];
        document.getElementById('sender_email').value = randomEmail;
        dialog.style.display = "none";
    });

    function zobrazitPole() {
        var option = document.querySelector('input[name="option"]:checked').value;
        var smtp_username = document.getElementById("smtp_username");
        var smtp_password = document.getElementById("smtp_password");

        if (option === "SMTP-AUTH") {
            smtp_username.style.display = "block";
            smtp_password.style.display = "block";
        } else {
            smtp_username.style.display = "none";
            smtp_password.style.display = "none";
        }
    }
</script>

</body>
</html>

