<?php
include("postget.php");
include_once("common.php");
$pagetitle = _SEND_MESSAGE;

checklevel(2, $_REQUEST['clientid']);



if ($config[56][1] == 1) {
    $disabled = " disabled ";
    $mensaje = " " . _CHANGE_NOT_ALLOWED_IN_DEMO_MODE;
} else {
    $disabled = " ";
    $mensaje = "";
}



if ($sendmessage != "" . _SEND . "" AND $sendmessage != "" . _SEND_AND_SAVE . "") {
    if ($_SESSION['hd_clientid']) {
        $thisclient = 1;
    }

    include("head_template.php");
    ?>
    <script language="javascript" type="text/javascript" src="tiny_mce/tiny_mce.js"></script>
    <script language="javascript" type="text/javascript">
        tinyMCE.init({
            mode : "textareas",
            theme : "advanced",
            plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

            theme_advanced_buttons1 : "undo,redo,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontselect,fontsizeselect",
            theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,image,cleanup,code,|,insertdate,inserttime,|,forecolor,backcolor",
            theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
            theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,blockquote,pagebreak,|,insertfile,insertimage",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar_location : "bottom",
            theme_advanced_resizing : true,
            elements : 'abshosturls',
            relative_urls : false,
            remove_script_host : false,
            extended_valid_elements : "input[id|name|type|size|value],textarea[cols|rows]"


        });
    </script>
    <?php
    echo '
<div class="container">
	<div class="row">

';
    ?>

    <table class="table table-bordered">

        <tr><td valign="baseline">
                <b>
    <?php
    $loaded = 1;
    if ($message == '') {
        $loaded = 0;
        echo _LOAD_FROM . ": </b></td><td colspan='5'>";
        $query = "SELECT * FROM hd_messages";
        $message = mysql_query($query, $db_link);
        echo "<form id='loadmessage' method='POST' ACTION=sendmessages.php?clientid=" . $_SESSION['hd_clientid'] . ">";
        echo "<select name=message>";
        while ($rowsmessages = mysql_fetch_array($message)) {
            echo "<option value = '$rowsmessages[subject]|||$rowsmessages[body]'>$rowsmessages[subject]</option>";
        }
        echo "</select>
		<input type=submit name=loadmessage value=" . _LOAD . " class='btnform'>
		</form>";
    }
    ?>

            </td></tr>

        <form id="message" method="POST">

            <tr><td><b><?php echo _SEND . " " . _TO . ": " ?></b></td>
                <td><fieldset>
                        <label class="radio">

                            <input type="radio" name="typeclient1" value=0 checked>
                            <span class="metro-radio"><?php echo lang('_ONLY') . " " . lang('-_THIS_CLIENT') ?>: </span>
                        </label>

                            <input type="text" name="clientid" value="<?php echo ($_SESSION['hd_clientid']) ? $_SESSION['hd_clientid'] : @_CLIENT_ID ?>" onfocus="if (this.value=='<?php echo @_CLIENT_ID ?>') this.value='';" onblur="if(this.value=='') this.value='<?php echo _CLIENT_ID ?>';" size="10">
                            <br>
                        <label class="radio">
                            <input type="radio" name="typeclient1" value=3>
                            <span class="metro-radio"><?php echo @_ALL ?></span>
                        </label>
                            </fieldset>
                            </td>



                            </tr>



                            <tr><td>
                                    <b><?php echo _ENTER_SUBJECT ?>:</b></td><td colspan="5">
    <?php
    if ($loaded == 0) {
        print("<input name='form_subject' type='text' value='' size='110'>");
    } else {
        $message = stripslashes($message);
        $message = explode("|||", $message);
        print("<input name='form_subject' type='text' value='" . $message[0] . "' size='110'>");
    }
    ?>
                                </td></tr>

                            <tr><td>
                                    <b><?php echo _ENTER_MESSAGE ?>:</b></td><td colspan="5">
    <?php
    if ($loaded == 0) {
        print("<textarea name='form_message' cols='110' rows='15' ></textarea>");
    } else {
        print("<textarea name='form_message' cols='110' rows='15' >" . $message[1] . "</textarea>");
    }
    ?>

                                </td></tr>

                            <tr><td></td><td colspan="5">
    <?php print("
		<b>%URL%</b> = " . $config[1][1] . "&nbsp;&nbsp;&nbsp;&nbsp;
		<b>%UNSUBSCRIBE%</b> = " . _UNSUBSCRIBE_LINK . "<br>
		<b>%USER%</b> = " . _USER_ID . "&nbsp;&nbsp;&nbsp;&nbsp;
		<b>%ALIAS%</b> = " . _ALIAS . "&nbsp;&nbsp;&nbsp;&nbsp;
		<b>%PASS%</b> = " . _PASSWORD . "
		"
    );
    ?>

                                </td></tr>

                            <tr><td></td><td colspan="5">
                                    <input type=submit name=sendmessage value='<?php echo _SEND ?>' <?php echo $disabled ?>>
                                    <input type=submit name=sendmessage value='<?php echo _SEND_AND_SAVE ?>' <?php echo $disabled ?>><?php echo $mensaje ?>
                                </td></tr>
                            </table></form>
    <?php
    echo '
</div>
</div>
';

    include("foot_template.php");
} else {

    if ($form_subject == "" or $form_message == "") {
        print("" . _ERROR . "<br><a href=sendmessages.php>" . _RETURN . "</a>");
        exit;
    }



    $queryINICIAL = "SELECT email, first, last, clientid, reseller, clientalias, password, preflang FROM hd_clients WHERE email <> ''";

    if ($typeclient1 == 0) {
        $query1 = "AND clientid=" . $_SESSION['hd_clientid'] . "";
    } elseif ($typeclient1 == 1) {
        $query1 = "AND reseller=0";
    } elseif ($typeclient1 == 2) {
        $query1 = "AND reseller=1";
    } else {
        $query1 = "";
    }

    if ($typeclient2 == 1) {
        $query2 = "AND active=1";
    } elseif ($typeclient2 == 2) {
        $query2 = "AND active=0";
    } else {
        $query2 = "AND active>=0";
    }


    $query4 = "AND promotionalmailing='1'";

    $query = $queryINICIAL . " " . $query1 . " " . $query4;

    $result = mysql_query($query, $db_link);
    $cuentamensajes = 0;
    $cuentaerrores = 0;
    while ($rowmail = mysql_fetch_array($result)) {

        $bodymail = "<table border='0' cellspacing='1'>";

        $bodymail.="<tr>";
        $bodymail.="<td>";
        $bodymail.="<font size=2>";

        $bodymail.= $form_message;

        $bodymail.="</font>";
        $bodymail.="</td>";
        $bodymail.="</tr>";
        $bodymail.="</table>";

        $bodymail = stripslashes($bodymail);

        $bodymail = str_replace('%URL%', '<a href="' . $config[1][1] . '">' . $config[1][1] . '</a>', $bodymail);
        $bodymail = str_replace('%USER%', $rowmail[clientid], $bodymail);
        $bodymail = str_replace('%ALIAS%', $rowmail[clientalias], $bodymail);
        $bodymail = str_replace('%PASS%', decrypt($rowmail[password]), $bodymail);

        $bodymail = str_replace('%UNSUBSCRIBE%', '<a href="' . $config[1][1] . '/unsubscribe.php?user=' . $rowmail[clientid] . '&code=' . substr(time(), 1, 4) . '' . $rowmail[password] . '">' . lang('_unsubscribe_message', $rowmail[preflang]) . '</a>', $bodymail);

        if ($config[59][1] == 1) {
            if (email2queue($rowmail[email], $form_subject, $bodymail, $mreplyto, '')) {
                $cuentamensajes++;
                logevent("" . _MESSAGE_SENT . ": " . $form_subject . "", $rowmail[clientid], "system");
                // print("<br>"._MESSAGE_SENT." "._TO." ".$rowmail[first]." ".$rowmail[last]);
                print('.');
            } else {
                $cuentaerrores++;
                print("<br><font color='red'>" . _MESSAGE_COULD_NOT_BE_SENT . " " . _TO . " " . $rowmail[first] . " " . $rowmail[last] . "</font>");
            }
        } else {
            //			if(mail($rowmail[email],$form_subject,$bodymail,$headers."From:$mfrom\nReply-To:$mreplyto"))	{
            if (mail2client($form_subject, $bodymail, 'adminSINcopia', $rowmail[email], 1)) {
                $cuentamensajes++;
                logevent("" . _MESSAGE_SENT . ": " . $form_subject . "", $rowmail[clientid], "system");
                // print("<br>"._MESSAGE_SENT." "._TO." ".$rowmail[first]." ".$rowmail[last]);
                print('.');
            } else {
                $cuentaerrores++;
                print("<br><font color='red'>" . _MESSAGE_COULD_NOT_BE_SENT . " " . _TO . " " . $rowmail[first] . " " . $rowmail[last] . "</font>");
            }
        }
    }


    /////// GUARDAR EL MENSAJE EN hd_messages
    if ($sendmessage == "" . _SEND_AND_SAVE . "") {
        $query = "SELECT * FROM hd_messages";
        $message = mysql_query($query, $db_link);
        $edited == 0;
        // quitar las \ si las tiene
        $form_subject = stripslashes($form_subject);
        $form_message = stripslashes($form_message);
        // insertar las \
        $form_subject = addslashes($form_subject);
        $form_message = addslashes($form_message);
        while ($rowsmessages = mysql_fetch_array($message)) {

            if (trim($rowsmessages[subject]) == trim($form_subject)) {
                $query = "UPDATE hd_messages SET body='$form_message' WHERE subject='$form_subject'";
                if (!mysql_query($query, $db_link)) {
                    print("<br><br>" . mysql_error() . "");
                } else {
                    print("<br><br>" . _MESSAGE_EDITED . "");
                }
                $edited = 1;
                break;
            }
        }
        if ($edited == 0) {

            $query = "INSERT INTO hd_messages (subject,body) VALUES ('$form_subject','$form_message')";
            if (!mysql_query($query, $db_link)) {
                print("<br><br>" . mysql_error() . "");
            } else {
                print("<br><br>" . _MESSAGE_SAVED . "");
            }
        }
    }

    // eliminar mensajes que comienzan por *
    $query = "DELETE FROM hd_messages WHERE body='*'";
    mysql_query($query, $db_link);

    messagetop($cuentamensajes . ' ' . lang('_MESSAGES_SENT'), $cuentaerrores . ' ' . lang('_ERRORS'), 'main.php', 2);
}
?>