<?php
include "../helper_functions/data_request.php";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require '../phpmailer/PHPMailer.php';
require '../phpmailer/Exception.php';
require '../phpmailer/SMTP.php';

function handleInvitation($coname, $email, $role, $slots, $type) {
	$token = bin2hex(random_bytes(16));
	try {
		$insertData = [
			'company_name' => $coname,
			'email' => $email,
			'token' => $token,
			'role' => $role,
			'dealer_slots' => $slots
		];
		$result = insertData('invitations', $insertData);
		if ($result) {
			$mail = new PHPMailer(true);
			try {
				$mail->isSMTP();
				$mail->Host = 'smtp.zeptomail.com';
				$mail->SMTPAuth = true;
				$mail->Username = 'your_postmark_api_token';
				$mail->Password = 'your_postmark_api_token';
				$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
				$mail->Port = 587;
				$mail->setFrom('no-reply@yourdomain.com', 'Your Application');
				$mail->addAddress($email);
				$mail->isHTML(true);
				$mail->Subject = 'Invitation to Register';
				$mail->Body = "
				<p>You have been invited to register as a {$type}. Please click the link below to complete your registration:</p>
				<p><a href='https://yourdomain.com/register.php?token=$token'>Register</a></p>
				";

				$mail->send();
				return true;
			} catch (Exception $e) {
				throw new Exception("Mailer Error: " . $mail->ErrorInfo);
			}
		} else {
			throw new Exception("Failed to create invitation in the database.");
		}
	} catch (Exception $e) {
		throw new Exception("Error: " . $e->getMessage());
	}
}

function resendInvitation($userId) {
	$userDatas = fetchData('invitations', ['id' => $userId]);
	$token = $userDatas[0]['token'];
	$email = $userDatas[0]['email'];
	$mail = new PHPMailer(true);
	try {
		$mail->isSMTP();
		$mail->Host = 'smtp.zeptomail.com';
		$mail->SMTPAuth = true;
		$mail->Username = 'your_postmark_api_token';
		$mail->Password = 'your_postmark_api_token';
		$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
		$mail->Port = 587;
		$mail->setFrom('no-reply@yourdomain.com', 'Your Application');
		$mail->addAddress($email);
		$mail->isHTML(true);
		$mail->Subject = 'Invitation to Register';
		$mail->Body = "
		<p>Please click the link below to complete your registration:</p>
		<p><a href='https://yourdomain.com/register.php?token=$token'>Register</a></p>
		";

		$mail->send();
		return "Success";
	} catch (Exception $e) {
	// echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
	// return;
	}
}