<?
require_once('../include/user.php');
require_once('../include/authenticate.php');
require_once('../include/mysql.php');
require_once('../include/functions.php');
require_once('../Rmail/Rmail.php');
require_once('../include/fb.php');

ob_start();
session_start();

$_SESSION['panel_view_url'] = $_SERVER['REQUEST_URI'];

// SETUP MYSQL HANDLERS
$mysqldb1 = new mysql($host, $user, $pswd, $db);
$mysqldb1->connect();
$mysqldb1->select();
$mysqldb2 = new mysql($host, $user, $pswd, $db);
$mysqldb2->connect();
$mysqldb2->select();

// SETUP GENERAL VARIABLES
$url = $_SERVER['REQUEST_URI'];
$date = date('Y-m-d H:i:s', time());
$error = $_GET['error'];
$log = '';

// GENERATE AND EMAIL NEWSLETTER

if ($_POST['from'] == '') {
    $_POST['from'] = $admin_email;
}

if (isset($_POST['test'])) {

    $query = "SELECT content FROM newsletter WHERE id=".$_POST['newsletter_id'];
    fb($query);
    $mysqldb1->query($query);
    $newsletter = $mysqldb1->fetchArray();

    $html = file_get_contents('../../newsletter/newsletter.php');
    $html = str_replace('#FIRST_NAME#', '', $html);
    $html = str_replace('#CONTENT#', html_entity_decode($newsletter['content']), $html);
    $html = str_replace('../..', 'http://'.$domain, $html);
    $html = str_replace('#UNSUBSCRIBE#', '', $html);

    $emailer = new Rmail();
    $emailer->setPriority('high');
    $emailer->setFrom($domain.' <'.$_POST['from'].'>');
    $emailer->setSubject($_POST['subject']);
    $emailer->setHTML($html);

    $mailed = $emailer->send(array($_POST['from']));

    $result .= $contact['email'];
    if ($mailed) {
        $result .= $_POST['from'].'...sent<br/>';
    } else {
        $result .= $_POST['from'].'...error!<br/>';
    }

    //fb($result);
}

if (isset($_POST['send'])) {

    $query = "SELECT content FROM newsletter WHERE id=".$_POST['newsletter_id'];
    fb($query);
    $mysqldb1->query($query);
    $newsletter = $mysqldb1->fetchArray();

    $query = "
		SELECT 
			t1.* 
		FROM 
			contact AS t1 
		WHERE 
			(SELECT status FROM contact_category_link WHERE contact_category_id=".$_POST['contact_category_id']." AND contact_id=t1.id)=1 AND 
			t1.email!='' AND 
			t1.status='enabled' 
		ORDER BY 
			t1.last_name ASC";
    fb($query);
    $mysqldb1->query($query);
    while ($contact = $mysqldb1->fetchArray()) {

        $html = file_get_contents('../../newsletter/newsletter.php');
        $html = str_replace('#FIRST_NAME#', $contact['first_name'], $html);
        $html = str_replace('#CONTENT#', html_entity_decode($newsletter['content']), $html);
        $html = str_replace('../..', 'http://'.$domain, $html);
        $html = str_replace('#UNSUBSCRIBE#', '<a href="http://'.$domain.'/newsletter/unsubscribe.php?contact_category_id='.urlencode(encrypt($_POST['contact_category_id'], $domain)).'&contact_id='.urlencode(encrypt($contact['id'], $domain)).'" target="_blank">UNSUBSCRIBE<a>', $html);

        $emailer = new Rmail();
        $emailer->setPriority('high');
        $emailer->setFrom($domain.' <'.$_POST['from'].'>');
        $emailer->setSubject($_POST['subject']);
        $emailer->setHTML($html);

        $mailed = $emailer->send(array($contact['email']));

        $result .= $contact['email'];
        if ($mailed) {
            $result .= '...sent<br/>';
        } else {
            $result .= '...error!<br/>';
        }

    }
    //fb($result);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title><? print ucfirst($_GET['table']); ?> Manager</title>
        <meta name="robots" content="noindex, nofollow, noarchive" />
        <meta http-equiv="pragma" content="no-cache" />
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <!--STYLES-->
        <link type="text/css" rel="stylesheet" href="../styles/default/table.css"/>
        <!--/STYLES-->
        <!--JQUERY-->
        <link type="text/css" rel="stylesheet" href="../styles/smoothness/jquery.ui.css"/>
        <script type="text/javascript" src="../scripts/jquery.js"></script>
        <script type="text/javascript" src="../scripts/jquery.ui.js"></script>
        <script type="text/javascript" src="../scripts/jquery.imgpreview.js"></script>
        <!--/JQUERY-->
        <!--CUSTOM-->
        <script type="text/javascript" src="../scripts/jquery.cookie.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {

                $("#tabs").tabs( { cookie: { expires: 30 } } );

            });
        </script>
        <script type="text/javascript">
            function echeck(str) {

                var at = "@";
                var dot = ".";
                var lat = str.indexOf(at);
                var lstr = str.length;
                var ldot = str.indexOf(dot);

                if (str.indexOf(at) ==- 1) { return false; }
                if (str.indexOf(at) ==- 1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) { return false; }
                if (str.indexOf(dot) ==- 1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) { return false; }
                if (str.indexOf(at, (lat + 1)) !=- 1) { return false; }
                if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) { return false; }
                if (str.indexOf(dot, (lat + 2)) ==- 1) { return false; }
                if (str.indexOf(" ") !=- 1 ) { return false; }

                return true;
            }
        </script>
        <script type="text/javascript">
            function validate() {

                // newsletter_id
                if (document.getElementById("newsletter_id").value == 'select') {
                    alert("Please select a newsletter to send.");
                    document.getElementById("newsletter_id").focus();
                    return false;
                }

                // contact_category_id
                if (document.getElementById("contact_category_id").value == 'select') {
                    alert("Please select a contact category.");
                    document.getElementById("contact_category_id").focus();
                    return false;
                }

                // from
                if (echeck(document.getElementById("from").value) == false) {
                    alert("Please enter a valid email address.");
                    document.getElementById("from").focus();
                    return false;
                }

                // subject
                if (document.getElementById("subject").value.length < 1) {
                    alert("Please enter a valid subject.");
                    document.getElementById("subject").focus();
                    return false;
                }
            }
        </script>
        <!--/CUSTOM-->
    </head>
    <body>
        <div id="tabs" class="ui-tabs">
            <ul>
                <li><a href="#tabs-1">Newsletter Emailer</a></li>
            </ul>
            <!--EMAILER-->
            <div id="tabs-1" class="ui-tabs-hide">
                <form name="emailer_form" id="emailer_form" method="post" action="emailer.php" onsubmit="return validate();">
                    <table border="0" cellspacing="1" cellpadding="1">
                        <tr>
                            <td class="field_name">newsletter</td>
                            <td class="field">
                                <select name="newsletter_id" id="newsletter_id">
                                    <option value="select" selected="selected">select a newsletter</option>
                                    <?
                                    $mysqldb1->query("SELECT id, heading FROM newsletter ORDER BY id DESC");
                                    while ($option = $mysqldb1->fetchArray()) {
                                        if ($_POST['newsletter_id'] == $option['id']) {
                                            $selected = 'selected';
                                        } else {
                                            $selected = '';
                                        }
                                        print '<option value="'.$option['id'].'" '.$selected.'>'.$option['heading'].'</option>'."\n";
                                    }
                                    ?>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <td class="field_name">contact category</td>
                            <td class="field">
                                <select name="contact_category_id" id="contact_category_id">
                                    <option value="select" selected="selected">select a category</option>
                                    <?
                                    $mysqldb1->query("SELECT id, name AS name FROM contact_category ORDER BY name ASC");
                                    while ($option = $mysqldb1->fetchArray()) {
                                        if ($_POST['contact_category_id'] == $option['id']) {
                                            $selected = 'selected';
                                        } else {
                                            $selected = '';
                                        }
                                        print '<option value="'.$option['id'].'" '.$selected.'>'.$option['name'].'</option>'."\n";
                                    }
                                    ?>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <td class="field_name">from</td>
                            <td class="field"><input name="from" type="text" id="from" value="<? print $_POST['from']; ?>" size="30" /></td>
                        </tr>
                        <tr>
                            <td class="field_name">subject</td>
                            <td class="field"><input name="subject" type="text" id="subject" value="<? print $_POST['subject']; ?>" size="40" /></td>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                        </tr>
                        <tr>
                            <td align="left"><input type="submit" name="send" id="send" value="Send" /></td>
                            <td align="right"><input type="submit" name="test" id="test" value="Test" /></td>
                        </tr>
                        <?
                        if ($result != '') {
                            ?>
                        <tr>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                        </tr>
                        <tr>
                            <td><? print $result; ?></td>
                            <td>&nbsp;</td>
                        </tr>
                            <?

                        }
                        ?>
                    </table>
                </form>
            </div>
            <!--/EMAILER-->
        </div>
        <? require_once("../panel/dialog.php"); ?>
    </body>
</html>
<?
$mysqldb1->close();
$mysqldb2->close();
?>