<?php
include_once '../includes/constants.php';
include_once '../includes/functions.php';
include_once '../includes/session.php';
include_once '../includes/allstripslashes.php';

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

$select1 = $_POST['select1'] ?? 'All Affiliate';
$flag    = $_POST['flag'] ?? '';
$msg     = '';
$totmail = 0;
$emails  = [];

$adminheader = '';
$adminfooter = '';
$amt         = 0;

// Fetch mail header/footer/amount from admin settings
$adminResult = $mysqli->query("SELECT admin_mailheader, admin_mailfooter, admin_mailamnt FROM partners_admin LIMIT 1");
if ($adminResult && $adminResult->num_rows > 0) {
    $adminData   = $adminResult->fetch_assoc();
    $adminheader = stripslashes($adminData['admin_mailheader']);
    $adminfooter = stripslashes($adminData['admin_mailfooter']);
    $amt         = $adminData['admin_mailamnt'];
}

// Determine recipients
$login_flag = $select1 === 'All merchants' ? 'm' : 'a';
$stmt = $mysqli->prepare("SELECT login_email FROM partners_login WHERE login_flag = ?");
$stmt->bind_param("s", $login_flag);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $emails[] = stripslashes($row['login_email']);
}
$totmail = count($emails);

// Calculate total mail cost
$totamount = $totmail * $amt;

// Handle form submission
if ($flag === 'send' || $flag === 'Test Send To Me') {
    // Sanitize input
    $fromtxt     = trim(stripslashes($_POST['fromtxt'] ?? ''));
    $subjecttxt  = trim(stripslashes($_POST['subjecttxt'] ?? ''));
    $headertxt   = trim(stripslashes($_POST['headertxt'] ?? ''));
    $footertxt   = trim(stripslashes($_POST['footertxt'] ?? ''));
    $bodytxt     = trim(stripslashes($_POST['bodytxt'] ?? ''));
    $to1         = trim(stripslashes($_POST['to1'] ?? ''));

    // Validation
    $errors = [];
    if (empty($fromtxt) || empty($subjecttxt) || empty($headertxt) || empty($footertxt) || empty($bodytxt)) {
        $errors[] = "Don't leave any field blank.";
    }

    if (!filter_var($fromtxt, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "From field should be a valid email address.";
    }

    if ($flag === 'Test Send To Me' && !filter_var($to1, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Test email field should be a valid email address.";
    }

    // If no errors, proceed with sending
    if (empty($errors)) {
        function sendMail($to, $from, $subject, $header, $body, $footer, $adminheader, $adminfooter) {
            $headers = "MIME-Version: 1.0\r\n";
            $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
            $headers .= "From: $from\r\n";

            $fullBody = "
                <html><body>
                <table width='90%' border='0' cellpadding='0' cellspacing='0'>
                    <tr><td align='center'>
                        <table width='80%' border='0' cellpadding='10' cellspacing='0' style='border:1px solid #ccc;'>
                            <tr><td>$adminheader</td></tr>
                            <tr><td>$header</td></tr>
                            <tr><td>$body</td></tr>
                            <tr><td>$footer</td></tr>
                            <tr><td>$adminfooter</td></tr>
                        </table>
                    </td></tr>
                </table>
                </body></html>";

            mail($to, $subject, $fullBody, $headers);
        }

        if ($flag === 'send') {
            foreach ($emails as $email) {
                sendMail($email, $fromtxt, $subjecttxt, $headertxt, $bodytxt, $footertxt, $adminheader, $adminfooter);
            }
            $msg = "($totmail) E-mails successfully sent.";
        } elseif ($flag === 'Test Send To Me') {
            sendMail($to1, $fromtxt, $subjecttxt, $headertxt, $bodytxt, $footertxt, $adminheader, $adminfooter);
            $msg = "Test mail sent to $to1";
        }
    } else {
        $msg = implode("<br>", $errors);
    }
}
?>

<!-- HTML FORM START -->
<form name="f1" action="" method="post">
    <table width="80%" border="0" class="tablebdr">
        <tr>
            <td colspan="7" align="center" class="tdhead">
                <b>Select a mailing list:</b>
                <select name="select1" onchange="this.form.submit()">
                    <option value="All Affiliate" <?= $select1 === "All Affiliate" ? "selected" : "" ?>>All Affiliates</option>
                    <option value="All merchants" <?= $select1 === "All merchants" ? "selected" : "" ?>>All Merchants</option>
                </select>
            </td>
        </tr>
        <tr><td colspan="7" align="center" class="textred"><?= $msg ?></td></tr>
        <tr>
            <td colspan="7" class="grid1" align="center">
                <b>You can use HTML code in Header, Footer, and Body fields</b>
            </td>
        </tr>
        <tr>
            <td>From:</td>
            <td colspan="2"><input type="text" name="fromtxt" value="<?= htmlspecialchars($fromtxt ?? '') ?>" size="50" /></td>
        </tr>
        <tr>
            <td>Subject:</td>
            <td colspan="2"><input type="text" name="subjecttxt" value="<?= htmlspecialchars($subjecttxt ?? '') ?>" size="50" /></td>
        </tr>
        <tr>
            <td>Header:</td>
            <td colspan="2"><textarea name="headertxt" rows="4" cols="70"><?= htmlspecialchars($headertxt ?? '') ?></textarea></td>
        </tr>
        <tr>
            <td>Body:</td>
            <td colspan="2"><textarea name="bodytxt" rows="8" cols="70"><?= htmlspecialchars($bodytxt ?? '') ?></textarea></td>
        </tr>
        <tr>
            <td>Footer:</td>
            <td colspan="2"><textarea name="footertxt" rows="4" cols="70"><?= htmlspecialchars($footertxt ?? '') ?></textarea></td>
        </tr>
        <tr>
            <td>Test Send To:</td>
            <td colspan="2"><input type="text" name="to1" value="<?= htmlspecialchars($to1 ?? '') ?>" size="50" /></td>
        </tr>
        <tr>
            <td colspan="3" align="center">
                <input type="submit" name="flag" value="send" />
                <input type="submit" name="flag" value="Test Send To Me" />
            </td>
        </tr>
        <tr>
            <td colspan="3">Total Receivers: <?= $totmail ?></td>
        </tr>
        <tr>
            <td colspan="3">
                <b>Recipient List Preview:</b><br>
                <select size="6" multiple style="width: 100%;">
                    <?php foreach ($emails as $email): ?>
                        <option><?= htmlspecialchars($email) ?></option>
                    <?php endforeach; ?>
                </select>
            </td>
        </tr>
    </table>
</form>
<br />