<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: POST");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

session_start();

//Load Composer's autoloader
require __DIR__.'/../../vendor/autoload.php';

require __DIR__.'/classes/CNetcupMailer.php';


require __DIR__.'/classes/Database.php';
require __DIR__.'/classes/lib.php';

$db_connection = new Database();
$conn = $db_connection->dbConnection();

$returnData = new CMsg(0);

if ($_SERVER["REQUEST_METHOD"] != "POST") 
{
    $returnData = new CMsg(0, 404, 'Page Not Found! REQUEST_METHOD');
    echo $returnData->jsonarray();
    return;
}

if (
    !isset($_POST['fromEmail'])
    || !isset($_POST['toEmail'])
    || !isset($_POST['qr_id'])
    || !isset($_POST['name'])
    || !isset($_POST['msg'])
    || empty(trim($_POST['fromEmail']))
    || empty(trim($_POST['toEmail']))
    || empty(trim($_POST['qr_id']))
    || empty(trim($_POST['name']))
    || empty(trim($_POST['msg']))
) 
{
    $fields = ['fields' => ['fromEmail', 'toEmail', 'qr_id', 'name', 'msg']];
    $returnData = new CMsg(0, 422, 'Please Fill in all Required Fields!', $fields);
    echo $returnData->jsonarray();
    return;
}

// IF THERE ARE NO EMPTY FIELDS THEN-
$fromEmail = trim($_POST['fromEmail']);
$toEmail = trim($_POST['toEmail']);
$qr_id = trim($_POST['qr_id']);
$name = trim($_POST['name']);
$msg = trim($_POST['msg']);

if (!filter_var($fromEmail, FILTER_VALIDATE_EMAIL))
{
    $returnData = new CMsg(0, 422, 'Invalid Email Address!', 'fromEmail');
    echo $returnData->jsonarray();
    return;
}

if (!filter_var($toEmail, FILTER_VALIDATE_EMAIL))
{
    $returnData = new CMsg(0, 422, 'Invalid Email Address!', 'toEmail');
    echo $returnData->jsonarray();
    return;
}

$subject = 'Tier gefunden: ' . $name .'         ID: '. $qr_id;

// $headers = 
//     array(
//         'From' => $fromEmail,
//         'Cc' => $fromEmail,
//         'Bcc' => 'dog@hope-fly.de'
//     );

$headers = 'From: ' . $fromEmail . "\r\n";
$headers .= 'Cc: ' . $fromEmail . "\r\n";
$headers .= 'Bcc: ' . 'dog@hope-fly.de' . "\r\n\r\n";

//var_dump($headers);


$mail = new CNetcupMailer();


try {
    //Server settings

    //Recipients
    $mail->setFrom($fromEmail);
    $mail->addAddress($toEmail);     //Add a recipient
    $mail->addReplyTo($fromEmail);
    $mail->addCC($fromEmail);
    $mail->addBCC('dog@hope-fly.de');

    //Attachments

    //Content
    $mail->Subject = $subject;
    $mail->Body    = $msg;

    if ($mail->send()) 
    {
        $result = new CMsg(1, 200, "Email send successfully.");
        $storeResult = storeEmail();
    }
    else
    {
        $result = new CMsg(0, 500, "Sorry, there was an error sending your email.");
    }
    echo $result->jsonarray();
} 
catch (Exception $e) 
{
    $err =  "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    $err .= "\r\n" . $e->getMessage();
    $result = new CMsg(0, 500, $err);
    echo $result->jsonarray();
}

function storeEmail()
{
    global $qr_id, $conn, $msg, $fromEmail;

    $dogRes = getDogByQrId($qr_id, $conn);

    if($dogRes->success)
    {
        $sql = "INSERT INTO contact_emails (dogs_id, from_email, msg) VALUES (?,?,?)";
        $conn->prepare($sql)->execute([$dogRes->data['id'], $fromEmail, $msg]); // throw PDO::exception when failed
    }
    else
    {
        throw new Exception("qr_id: " . $qr_id . " :: " . $dogRes->message);
    }
    return $dogRes;
}
?>