<?php
ob_start();
session_start();

require_once '../includes/constants.php';
require_once '../includes/functions.php';
require_once '../includes/session.php';
require_once '../includes/allstripslashes.php';

$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

$partners = new partners;
$partners->connection($host, $user, $pass, $db);

// Get POST/GET data securely
$flag = $_POST['flag'] ?? $_GET['flag'] ?? '';
$B1 = $_POST['B1'] ?? '';
$event = $_POST['eventcompo'] ?? $_GET['event'] ?? '';
$from = trim($_POST['fromtxt'] ?? $_GET['from'] ?? '');
$sub = trim($_POST['subjecttxt'] ?? $_GET['sub'] ?? '');
$body = trim($_POST['bodytxt'] ?? $_GET['body'] ?? '');
$header = trim($_POST['headertxt'] ?? $_GET['header'] ?? '');
$footer = trim($_POST['footertxt'] ?? $_GET['footer'] ?? '');
$to = trim($_POST['to'] ?? $_GET['to'] ?? '');
$getst = $_POST['statusradio'] ?? $_GET['status'] ?? '';

$status = ($getst === "active") ? "yes" : "no";

// Auto submit from event selection
if (!$B1 && $flag === "0") {
    if ($event === "ChooseEvent") {
        $_SESSION['BODY'] = $_SESSION['HEADER'] = $_SESSION['FOOTER'] = '';
        $msg = "Please select an Event!";
    } else {
        $_SESSION['BODY'] = $_SESSION['HEADER'] = $_SESSION['FOOTER'] = '';

        $stmt = $mysqli->prepare("
            SELECT a.adminmail_from, a.adminmail_subject, a.adminmail_message, a.adminmail_header, a.adminmail_footer, e.event_status
            FROM partners_adminmail a
            JOIN partners_event e ON a.adminmail_eventname = e.event_name
            WHERE a.adminmail_eventname = ?
        ");
        $stmt->bind_param("s", $event);
        $stmt->execute();
        $stmt->bind_result($from, $sub, $body, $header, $footer, $status);

        if ($stmt->fetch()) {
            $_SESSION['BODY'] = $body;
            $_SESSION['HEADER'] = $header;
            $_SESSION['FOOTER'] = $footer;
        }
        $stmt->close();

        header("Location: index.php?Act=email&from=" . urlencode($from) . "&sub=" . urlencode($sub) . "&header=" . urlencode($header) . "&body=" . urlencode($body) . "&footer=" . urlencode($footer) . "&event=" . urlencode($event) . "&status=" . urlencode($status) . "&msg=&to=" . urlencode($to));
        exit;
    }
}

// Validate input fields
$errors = [
    empty($from),
    empty($sub),
    empty($header),
    empty($body),
    empty($footer)
];

if (in_array(true, $errors)) {
    $_SESSION['HEADER'] = $header;
    $_SESSION['BODY'] = $body;
    $_SESSION['FOOTER'] = $footer;
    $msg = "Invalid Entry...Please do not empty any fields";
    header("Location: index.php?Act=email&from=" . urlencode($from) . "&sub=" . urlencode($sub) . "&event=" . urlencode($event) . "&status=" . urlencode($status) . "&msg=" . urlencode($msg) . "&to=" . urlencode($to));
    exit;
}

if ($event === "ChooseEvent") {
    $msg = "Please select an Event!";
    header("Location: index.php?Act=email&from=" . urlencode($from) . "&sub=" . urlencode($sub) . "&event=" . urlencode($event) . "&status=" . urlencode($status) . "&msg=" . urlencode($msg) . "&to=" . urlencode($to));
    exit;
}

if ($from !== '[from]' && !$partners->is_email($from)) {
    $msg = "From field should be a valid E-mail Id!";
    header("Location: index.php?Act=email&from=" . urlencode($from) . "&sub=" . urlencode($sub) . "&event=" . urlencode($event) . "&status=" . urlencode($status) . "&msg=" . urlencode($msg) . "&to=" . urlencode($to));
    exit;
}

// Test mail sending
if ($flag === "1") {
    if (!$partners->is_email($to)) {
        $msg = "Please Enter a valid E-mail Id on Test Field!";
        header("Location: index.php?Act=email&from=" . urlencode($from) . "&sub=" . urlencode($sub) . "&event=" . urlencode($event) . "&status=" . urlencode($status) . "&msg=" . urlencode($msg) . "&to=" . urlencode($to));
        exit;
    }

    $res_admin = $mysqli->query("SELECT admin_mailheader, admin_mailfooter, admin_email FROM partners_admin LIMIT 1");
    $admin = $res_admin->fetch_assoc();
    $admin_email = $admin['admin_email'] ?? '[admin@example.com]';
    $adminheader = stripslashes($admin['admin_mailheader'] ?? '');
    $adminfooter = stripslashes($admin['admin_mailfooter'] ?? '');

    $today = date("Y-m-d");

    $headers = "Content-Type: text/html; charset=iso-8859-1\r\n";
    $headers .= "From: " . str_replace("[from]", $admin_email, $from) . "\r\n";

    $body1 = "
    <table border='0' cellpadding='0' cellspacing='0' width='90%'>
        <tr><td align='center'>
            <table width='80%' cellpadding='0' cellspacing='0'>
                <tr><td align='center'>{$adminheader}</td></tr>
                <tr><td align='left'>{$header}</td></tr>
                <tr><td align='left'>&nbsp;</td></tr>
                <tr><td align='left'>{$body}</td></tr>
                <tr><td align='left'>&nbsp;</td></tr>
                <tr><td align='left'>{$footer}</td></tr>
                <tr><td align='center'>{$adminfooter}</td></tr>
            </table>
        </td></tr>
    </table>";

    // Replace placeholders
    $placeholders = [
        "[aff_firstname]" => "Affiliate FirstName",
        "[aff_lastname]" => "Affiliate LastName",
        "[aff_company]" => "Affiliate Company",
        "[aff_email]" => "Affiliate Email",
        "[aff_loginlink]" => "Affiliate Url",
        "[aff_password]" => "Affiliate Password",
        "[mer_firstname]" => "Merchant FirstName",
        "[mer_lastname]" => "Merchant LastName",
        "[mer_company]" => "Merchant Company",
        "[mer_email]" => "Merchant Email",
        "[mer_loginlink]" => "Merchant Url",
        "[mer_password]" => "Merchant Password",
        "[from]" => $admin_email,
        "[commission]" => "Commission Earned",
        "[program]" => "Program Name",
        "[type]" => "Transaction type",
        "[date]" => "Transaction Date",
        "[today]" => $today
    ];
    $body1 = strtr($body1, $placeholders);

    mail($to, $sub, $body1, $headers);

    $msg = "Mail has been sent to $to";
    header("Location: index.php?Act=email&from=" . urlencode($from) . "&sub=" . urlencode($sub) . "&event=" . urlencode($event) . "&status=" . urlencode($status) . "&msg=" . urlencode($msg) . "&to=" . urlencode($to));
    exit;
}

// Update or Insert message template
$stmt_check = $mysqli->prepare("SELECT 1 FROM partners_adminmail WHERE adminmail_eventname = ?");
$stmt_check->bind_param("s", $event);
$stmt_check->execute();
$stmt_check->store_result();

if ($stmt_check->num_rows > 0) {
    $stmt_update = $mysqli->prepare("UPDATE partners_adminmail SET adminmail_from=?, adminmail_subject=?, adminmail_header=?, adminmail_footer=?, adminmail_message=? WHERE adminmail_eventname=?");
    $stmt_update->bind_param("ssssss", $from, $sub, $header, $footer, $body, $event);
    $stmt_update->execute();
    $stmt_update->close();
} else {
    $stmt_insert = $mysqli->prepare("INSERT INTO partners_adminmail (adminmail_eventname, adminmail_from, adminmail_subject, adminmail_message, adminmail_header, adminmail_footer) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt_insert->bind_param("ssssss", $event, $from, $sub, $body, $header, $footer);
    $stmt_insert->execute();
    $stmt_insert->close();
}
$stmt_check->close();

// Update event status
$stmt_status = $mysqli->prepare("UPDATE partners_event SET event_status = ? WHERE event_name = ?");
$stmt_status->bind_param("ss", $status, $event);
$stmt_status->execute();
$stmt_status->close();

$msg = "Message updated";
header("Location: index.php?Act=email&from=" . urlencode($from) . "&sub=" . urlencode($sub) . "&event=" . urlencode($event) . "&status=" . urlencode($status) . "&msg=" . urlencode($msg) . "&to=" . urlencode($to));
exit;
?>
