<?php

// Use __DIR__ to generate absolute paths relative to the current file
require_once __DIR__ . '/../../phpmailer/Exception.php';
require_once __DIR__ . '/../../phpmailer/PHPMailer.php';
require_once __DIR__ . '/../../phpmailer/SMTP.php';

// Import the classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Get the POST data
$input = json_decode(file_get_contents('php://input'), true);
$competitionCode = $input['competitionCode'] ?? null;
$iwwfId = $input['iwwf_id'] ?? null;
$email = $input['email'] ?? null;
$host = $input['host'] ?? null;

if (!$competitionCode || !$iwwfId || !$email) {
	echo json_encode(['success' => false, 'error' => 'Invalid data provided.']);
	exit;
}

try {
	// Generate a token for email verification
	$token = bin2hex(random_bytes(16));
	$tokenExpiration = date("Y-m-d H:i:s", strtotime("+1 hour"));

	// Check if the email entry already exists
	$query = "SELECT * FROM user WHERE iwwf_id = ?";
	$stmt = $conn->prepare($query);
	$stmt->bind_param("s", $iwwfId);
	$stmt->execute();
	$result = $stmt->get_result();

	if ($result->num_rows > 0) {
		// Update existing entry with new email and token
		$updateQuery = "UPDATE user SET email = ?, token = ?, token_expiration = ? WHERE iwwf_id = ?";
		$updateStmt = $conn->prepare($updateQuery);
		$updateStmt->bind_param("ssss", $email, $token, $tokenExpiration, $iwwfId);
		$updateStmt->execute();
		$updateStmt->close();
	} else {
		// Insert a new entry with email and token
		$insertQuery = "INSERT INTO user (iwwf_id, email, token, token_expiration) VALUES (?, ?, ?, ?)";
		$insertStmt = $conn->prepare($insertQuery);
		$insertStmt->bind_param("ssss", $iwwfId, $email, $token, $tokenExpiration);
		$insertStmt->execute();
		$insertStmt->close();
	}

	$stmt->close();

	// Prepare verification email content
	$verificationLink = "https://".$host."/sign-up.html?token=$token";
	$subject = "Score Now - Verify Your Email Address";
	$message = "
		<!DOCTYPE html>
		<html lang='en'>
		<head>
			<meta charset='UTF-8'>
			<meta name='viewport' content='width=device-width, initial-scale=1.0'>
			<title>Email Verification</title>
			<style>
				body {
					font-family: Arial, sans-serif;
					background-color: #f9f9f9;
					color: #333333;
					line-height: 1.6;
					margin: 0;
					padding: 0;
				}
				.container {
					max-width: 600px;
					margin: 20px auto;
					background: #ffffff;
					padding: 20px;
					border-radius: 8px;
					box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
				}
				.header {
					text-align: center;
					padding-bottom: 20px;
					border-bottom: 1px solid #dddddd;
				}
				.header img {
					max-width: 150px;
				}
				.header h1 {
					font-size: 24px;
					margin: 10px 0 0;
					color: #333333;
				}
				.content {
					margin: 20px 0;
				}
				.content p {
					margin: 10px 0;
				}
				.button {
					text-align: center;
					margin: 20px 0;
				}
				.button a {
					background-color: #0056b3;
					color: #ffffff;
					text-decoration: none;
					padding: 10px 20px;
					font-size: 16px;
					border-radius: 5px;
					display: inline-block;
				}
				.button a:hover {
					background-color: #003d80;
				}
				.footer {
					text-align: center;
					font-size: 12px;
					color: #666666;
					margin-top: 20px;
					border-top: 1px solid #dddddd;
					padding-top: 10px;
				}
				.footer a {
					color: #0056b3;
					text-decoration: none;
				}
				.footer a:hover {
					text-decoration: underline;
				}
			</style>
		</head>
		<body>
			<div class='container'>
				<div class='header'>
					<img src='https://score-now.com/assets/img/logos/logo-180.png' alt='Score Now Logo'>
					<h1>Verify Your Email Address</h1>
				</div>
				<div class='content'>
					<p>Dear Official,</p>
					<p>Welcome to Score Now! To complete your account setup and start using our platform, please verify your email address by clicking the button below:</p>
					<div class='button'>
						<a href='$verificationLink' target='_blank'>Verify Email Address</a>
					</div>
					<p>If the button above does not work, copy and paste the following link into your browser:</p>
					<p><a href='$verificationLink' target='_blank'>$verificationLink</a></p>
					<p>Thank you for joining us!</p>
					<p>Best Regards, <br> The Score Now Team</p>
				</div>
				<div class='footer'>
					<p>&copy; 2025 Score Now. All rights reserved.</p>
					<p><a href='https://score-now.com/impressum.html' target='_blank'>Impressum</a></p>
				</div>
			</div>
		</body>
		</html>
	";

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

	try {
		// Configure PHPMailer to use Gmail SMTP
		$mail->isSMTP();
		$mail->Host       = 'smtp.gmail.com';
		$mail->SMTPAuth   = true;
		$mail->Username   = 'aaron.armborst@dwwv.de';   // Replace with your Gmail address
		$mail->Password   = 'kjho fewe wqyq juwv';          // Replace with your Gmail App Password
		$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;      // Use TLS encryption
		$mail->Port       = 587;

		// Set email headers and content
		$mail->setFrom('noreply@score-now.com', 'Score Now');
		$mail->addAddress($email);
		$mail->isHTML(true);
		$mail->Subject = $subject;
		$mail->Body    = $message;
		$mail->CharSet = 'UTF-8';

		// Send the email
		$mail->send();

		echo json_encode(['success' => true, 'message' => 'Verification email sent successfully.']);
	} catch (Exception $e) {
		echo json_encode([
			'success' => false,
			'error'   => 'Mailer Error: ' . $mail->ErrorInfo
		]);
	}
} catch (Exception $e) {
	http_response_code(500); // Internal Server Error
	echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
	exit;
}