<?php

include_once './dbconn.php';

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

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

    try {
        //Server settings
        $mail->isSMTP();                                            // Send using SMTP
        $mail->Host       = 'smtp-pulse.com';                       // Set the SMTP server to send through
        $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
        $mail->Username   = 'visuretechnigeria@gmail.com';           // SMTP username
        $mail->Password   = 'Tm7WikEGsA';                            // SMTP password
        $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
        $mail->Port       = 587;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

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

        // Content
        $mail->isHTML(true);                                  // Set email format to HTML
        $mail->Subject = 'Your request has been approved';
        $mail->Body    = 'Your request has been approved.';

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

if(isset($_GET['id']) && isset($_GET['email'])) {
    $id = $_GET['id'];
    $email = $_GET['email'];

    // Your approval logic here

    $sql = "SELECT * FROM web_app_enrollee_data WHERE id = '$id'";
    $result = mysqli_query($conn, $sql);
    $result_checker = mysqli_num_rows($result);
    if ($result_checker > 0) {
        while ($data = mysqli_fetch_assoc($result)) {
            $status = $data["status"];
        }
    }

    // SQL query to update data in the database
    $sql = "UPDATE web_app_enrollee_data 
            SET status = 'Approved'
            WHERE id = '$id'";

    // Execute the query
    if ($conn->query($sql) === TRUE) {
        // Send approval email
        sendApprovalEmail($email);
        
        // Redirect to index.php with a success message
        header("Location: ./index.php?approved");
        exit();
    } else {
        // Handle error
        echo "Error approving record: " . $conn->error;
    }
}

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

?>
