<?php
/**
 *  Copyright (C) 2021  Double Bastion LLC
 *
 *  This file is part of Roundpin, which is licensed under the
 *  GNU Affero General Public License Version 3.0. The license terms
 *  are detailed in the "LICENSE.txt" file located in the root directory.
 */

session_start();

 // header('Set-Cookie: PHPSESSID= ' . session_id() . '; SameSite=strict; Secure=true; HttpOnly=true;');

if (isset($_POST['s_ajax_call']) && ($_POST['s_ajax_call'] == $_SESSION['validate_s_access'])) {

    define('ACCESSCONST', TRUE);

    require('db-connect.php');

    $username = $_POST['username'];
    $roundpinhost =  $_POST['roundpinhost'];
    $sendername = $_POST['sendername'];
    $senderextension = $_POST['senderextension'];
    $receiveremail = $_POST['receiveremail'];
    $texttosend = $_POST['texttosend'];

    // Get the email address of the user who sends the message, from the 'app_users' table
    $queryprm = $mysqli->prepare("SELECT username, emailaddress FROM app_users WHERE username = ?");
    $queryprm->bind_param("s", $username);
    $queryprm->execute();
    $queryprmres = $queryprm->get_result()->fetch_assoc();
    $senderemail = $queryprmres["emailaddress"];


    if (filter_var($receiveremail, FILTER_VALIDATE_EMAIL)) {

        $subject = "New group message from Roundpin";
        $message = $texttosend . "<br><br>________________<br><br>Instant message to group, sent as email by ". $sendername ." (Extension ". $senderextension .") from Roundpin on '". $roundpinhost ."'.<br>";

        $messagefin = chunk_split(base64_encode($message));

        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";
        $headers .= "Content-Transfer-Encoding: base64" . "\r\n";

        // Set the email sender
        $headers .= "From: " . $senderemail . "\r\n";
        $headers .= "Reply-To: " . $senderemail . "\r\n";

        if (mail($receiveremail, $subject, $messagefin, $headers)) {
            $messagetosend = 'success';
        } else { $messagetosend = "Error while sending the email!"; }

    } else { $messagetosend = "The email address is not valid!"; }

    $response = array('result' => $messagetosend);
    echo json_encode($response);

} else {
    header("Location: ../login.php");
}

?>