<?php
require_once "front_common/header.php";

$db = new DbHandler();

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

    $email = $_POST['email'];
    $code = md5(uniqid(rand()));
    $status = "enabled";

    if ($response = !$db->isSubscribed($email)) {

        $response = $db->subscribeUser($email, $code, $status);

        require_once 'libs/mailer/class.phpmailer.php';

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = "ssl";
        $mail->Host = "creat.co.ke";
        $mail->Port = 465;
        $mail->Username = "uncommon@creat.co.ke";
        $mail->Password = "O6+VLDzLe+jv";
        $mail->SMTPKeepAlive = true;
        $mail->SMTPDebug = 0;
        $mail->SetFrom(EMAIL, WEB_NAME);
        $mail->AddReplyTo(EMAIL, WEB_NAME);


        $message = "Hello " . $email . ", Thank you for subscribing to our newsletter. 
                                    Click the link below to unsubscribe to our newsletter "
            . "<a href=" . URL . "unsubscribe.php?email=$email&code=$code>Unsubscribe</a>";

        $subject = "SEARCHBIZNA Newsletter subscription";
        try {
            $mail->addAddress($email);
            $mail->MsgHTML($message);
            $mail->Subject = $subject;
            $mail->Send();

            $response['error'] = false;

            $response["message"] = '<div class="alert alert-success" style="text-align:center;">
                    <a href="subscribe.php" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                    <strong>Success!</strong> You have been to added to our newsletter. 
                                
                  </div>';
            ?>

            <script>
                window.setTimeout(function () {
                    // Move to a new location or you can do something else
                    window.location.href = "index.php";
                }, 2000);

            </script>

            <?php

        } catch (Exception $e) {
            $response["error"] = true;
            $response["message"] = $e->getMessage();
        }

    } else {
        $response['error'] = true;

        $response["message"] = '<div class="alert alert-danger" style="text-align:center;">
                    <a href="subscribe.php" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                    <strong>Sorry!</strong> A user with this email address is already subscribed. 
                                
                  </div>';

    }

}

?>

<div class="body-overlay"></div>
<section class="section-padding">
    <div class="well-lg">
        <div class="container no-padding">
            <div class="container" style="margin-top: 10px!important;">
                <?php if (isset($response['message'])) echo $response["message"]; ?>
            </div>
        </div>
    </div>
</section>

<?php
require_once "front_common/footer.php";
?>
<!-- // End Footer  -->
