<?php

include_once './dbconn.php';

require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require 'PHPMailer/src/Exception.php';

function sendApprovalEmail($email, $enrollmentLink, $name) {
    $mail = new PHPMailer\PHPMailer\PHPMailer(true);

    try {
        //Server settings
        $mail->isSMTP();
        $mail->Host       = 'mail.healthassur.com';
        $mail->SMTPAuth   = false;
        $mail->Username   = 'registration@healthassur.com';
        $mail->Password   = 'P@55W0rd2023';
        $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = 465;

        //Recipients
        $mail->setFrom('registration@healthassur.com', 'Health Assur Limited');
        $mail->addAddress($email);
        $mail->addReplyTo('registration@healthassur.com', 'Health Assur Limited');

        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Welcome to Health Assur';
        $mail->Body    = '<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px; background-color: #f9f9f9; text-align: center; }
        .header { text-align: center; margin-bottom: 20px; }
        .header img { max-width: 200px; height: auto; }
        h1 { font-size: 19px; color: #333; margin-bottom: 20px; }
        p { margin-bottom: 15px; }
        .button { display: inline-block; padding: 10px 20px; background-color: #007bff; color: #fff; text-decoration: none; border-radius: 5px; transition: background-color 0.3s; }
        .button:hover { background-color: #0056b3; }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <img src="https://healthassur.com/enrollment/images/Red-logo.png" alt="Health Assur Ltd Logo">
    </div>
    <h1>Dear ' . $name . ',</h1>
    <p>Thank you for choosing Health Assur Ltd.</p>
    <p>Kindly find your enrollment link for your HMO registration:</p>
    <a class="button" href="' . $enrollmentLink . '">Register Now</a>
    <p>If the button above is not working, copy and paste the link below into your browser:</p>
    <p><a href="' . $enrollmentLink . '">' . $enrollmentLink . '</a></p>
    <p>We are excited to have you onboard!</p>
</div>
</body>
</html>';

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

// Initialize response array
$response = ['success' => false];

if (isset($_POST['selected']) && is_array($_POST['selected'])) {
    $linksentIds = [];

    foreach ($_POST['selected'] as $id) {
        $sql = "SELECT * FROM `web_app_staff_list` WHERE id = '$id'";
        $result = mysqli_query($conn, $sql);
        $row = mysqli_fetch_assoc($result);

        // Check if row data is retrieved
        if (!$row) {
            continue; // Skip if no user data found for this ID
        }

        // Extract required data
        $name = $row['firstname'] . ' ' . $row['lastname'];
        $email = $row['email_address'];
        $enrollmentLink = $row['registration_link'];

        // Send approval email
        if (sendApprovalEmail($email, $enrollmentLink, $name)) {
            // Update status to 'Link Sent'
            $sql = "UPDATE web_app_staff_list SET status = 'Link Sent' WHERE id = '$id'";
            if ($conn->query($sql) === TRUE) {
                $linksentIds[] = $id;
            } else {
                echo "Error updating record: " . $conn->error;
            }
        }
    }

    if (!empty($linksentIds)) {
        $response['success'] = true;
        $response['sentItems'] = $linksentIds;
    }
} else {
    $response['message'] = "No selected items received for sending enrollment link.";
}

$conn->close();

header('Content-Type: application/json');
echo json_encode($response);

?>
