<?php

include_once './dbconn.php';

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

function sendApprovalEmail($email, $idCardUrl, $name) {
    // Instantiation and passing `true` enables exceptions
    $mail = new PHPMailer\PHPMailer\PHPMailer(true);

    try {
        //Server settings
        $mail->isSMTP();                                            // Send using SMTP
        $mail->Host       = 'mail.healthassur.com';                       // Set the SMTP server to send through
        $mail->SMTPAuth   = false;                                   // Enable SMTP authentication
        $mail->Username   = 'registration@healthassur.com';           // SMTP username
        $mail->Password   = 'P@55W0rd2023';                            // SMTP password
        $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
        $mail->Port       = 465;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

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

        // Content
        $mail->isHTML(true);                                  // Set email format to HTML
        $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>Your registration is successful. Here is your e-ID card:</p>
        <a class="button" href="' . $idCardUrl . '">Download e-ID card</a>
        <p>We are glad to have you onboard!</p>
    </div>
</body>
</html>';

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

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

// Check if selected IDs are received via POST
if(isset($_POST['selected']) && is_array($_POST['selected'])) {
    // Array to store IDs of successfully approved items
    $approvedIds = [];

    // Loop through selected IDs and process each one
    foreach ($_POST['selected'] as $id) {
        // Fetch data of the user associated with the current ID
        $sql = "SELECT * FROM `web_app_enrollee_data` WHERE id = '$id'";
        $result = mysqli_query($conn, $sql);
        $row = mysqli_fetch_assoc($result);
        
        // Extract required data
        $name = $row['first_name'] .' '. $row['surname'];
        $idNumber = $row['hmo_id'];
        $client = $row['company_name'];
        $gender = $row['gender'];
        $plan = $row['type_of_plan'];
        $imageUrl = $row['Passport_link'];

        // Call e-ID card generation API
        $data = array(
            'name' => $name,
            'id_number' => $idNumber,
            'client' => $client,
            'validity' => $gender,
            'plan' => $plan,
            'image_url' => $imageUrl
        );

        $options = array(
            'http' => array(
                'header' => "Content-type: application/json\r\n",
                'method' => 'POST',
                'content' => json_encode($data)
            )
        );

        $context = stream_context_create($options);
        $result = file_get_contents('https://healthassur.com/enrollment/data/idcard.php', false, $context);

        // Check if the request was successful
        if ($result !== false) {
            $idCardUrl = json_decode($result, true)['file_url'];
            $current_date = date("Y-m-d H:i:s");
            $name = $row['first_name'] .' '. $row['surname'];
            
            // Send approval email with e-ID card URL
            if (sendApprovalEmail($row['email_address'], $idCardUrl, $name)) {
                // Update status to 'Approved' for the current ID
                $sql = "UPDATE web_app_enrollee_data 
                        SET status = 'Approved',
                            newchanges = 'yes',
                            approval_date = '$current_date',
                            changedate = '$current_date'
            
                        WHERE id = '$id'";
                if ($conn->query($sql) === TRUE) {
                    $approvedIds[] = $id; // Add ID to the list of successfully approved items
                } else {
                    // Handle error
                    // You can log the error or perform other actions as needed
                    echo "Error updating record: " . $conn->error;
                }
            } else {
                // Handle email sending failure
                // You can log the failure or perform other actions as needed
            }
        } else {
            // Handle API request failure
            // You can log the failure or perform other actions as needed
        }
    }

    // Update response on successful bulk approval
    if (!empty($approvedIds)) {
        $response['success'] = true;
        $response['approvedItems'] = $approvedIds;
    }
} else {
    // If no selected IDs received, handle the situation accordingly
    $response['message'] = "No selected items received for bulk approval.";
}

// Close connection
$conn->close();

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

?>

