<?php
// Use __DIR__ to construct absolute paths relative to this file
require_once __DIR__ . '/../../phpmailer/Exception.php';
require_once __DIR__ . '/../../phpmailer/PHPMailer.php';
require_once __DIR__ . '/../../phpmailer/SMTP.php';

// Import PHPMailer 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);
$email = $input['email'] ?? null;
$host = $input['host'] ?? 'score-now.com'; // Default host if not provided

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

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

if ($result->num_rows > 0) {
	// Email exists, generate a reset token
	$token = bin2hex(random_bytes(50));
	
	// Store the token in the database with expiration time (1 hour)
	$updateQuery = $conn->prepare("UPDATE user SET token = ?, token_expiration = DATE_ADD(NOW(), INTERVAL 1 HOUR) WHERE email = ?");
	$updateQuery->bind_param("ss", $token, $email);
	$updateQuery->execute();
	$updateQuery->close();
	
	// Prepare reset password email content
	$resetLink = "https://".$host."/sign-up.html?token=$token";
	$subject = "Password Reset Request";
	$message = "
		<!DOCTYPE html>
		<html lang='en'>
		<head>
			<meta charset='UTF-8'>
			<meta name='viewport' content='width=device-width, initial-scale=1.0'>
			<title>Password Reset Request</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 h1 {
					font-size: 24px;
					margin: 10px 0 0;
					color: #333333;
				}
				.content {
					margin: 20px 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;
				}
			</style>
		</head>
		<body>
			<div class='container'>
				<div class='header'>
					<h1>Password Reset Request</h1>
				</div>
				<div class='content'>
					<p>You have requested to reset your password. Click the link below to proceed:</p>
					<div class='button'>
						<a href='" . $resetLink . "' target='_blank'>Reset Password</a>
					</div>
					<p>If the button above does not work, copy and paste the following link into your browser:</p>
					<p><a href='" . $resetLink . "' target='_blank'>" . $resetLink . "</a></p>
					<p>If you did not request a password reset, please ignore this email.</p>
				</div>
				<div class='footer'>
					<p>&copy; 2025 Score Now. All rights reserved.</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@emp-control.de';   // Replace with your Gmail address
		$mail->Password   = 'srjt aquu wvcv exbr';       // Replace with your Gmail App Password
		$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
		$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' => 'Password reset link sent']);
	} catch (Exception $e) {
		echo json_encode(['success' => false, 'error' => 'Mailer Error: ' . $mail->ErrorInfo]);
	}
} else {
	// Email not found in database
	echo json_encode(['success' => false, 'message' => 'Email not found']);
}
?>