<?php
/**
 * Ajax called script to alert editors or editor via email
 * @author Rihards Siliņš
 * @version 2 07/10/2016
 */
$cms_root_path = "../../../";
require_once($cms_root_path . "includes/compatibility_includer.php");

if (empty($_POST['page_id']) || !is_numeric($_POST['page_id'])) {
    header("HTTP/1.0 400 Bad Request");
    $error_message = "page_id missing from alert editor request.";
    ContentManagerPanel::addMessage($error_message);
    die($error_message);
}

$page = ContentManagerPanel::loadPage($_POST['page_id'], false);
if (empty($page->id)) {
    header("HTTP/1.0 409 Conflict");
    $error_message = "The page you attempted to alert about was not found.";
    ContentManagerPanel::addMessage($error_message);
    die($error_message);
}

$message = "";
if (!empty($_POST['message'])) {
    $message = $_POST['message'];
}

$user_id = "";
if (!empty($_POST['user_id'])) {
    $user_id = $_POST['user_id'];
}

$user_name = "";
if (!empty($_POST['user_name'])) {
    $user_name = $_POST['user_name'];
}
// Set text and link based on alert type.
if (isset($_POST['type']) && $_POST['type'] == "decline") {
    $updated_datetime = date_create_from_format("Y-m-d H:i:s", $page->updated);
    if (!empty($updated_datetime)) {
        $time_string = "on <strong>".$updated_datetime->format("H:i jS F Y")."</strong> ";
    }
    $title = "Your submitted change to the <strong>";
    $title .= clean_page($page->title)."</strong> " . $time_string;
    $title .= "page has been declined by reviewer <strong>";
    $title .= clean_page($_SESSION['content_manager']['username'])."</strong>.";
    if (!empty($message)) {
        $title .= "Due to - '".clean_page($message)."'.";
    }

    $cms_admin_link = SITE_URL . "/cms/admin/content_manager/?page=" . $page->draft_for_page_id . "#tab=3";
    $subject = "Your submitted change has been declined!";
} else {
    $title = "";
    $cms_admin_link = SITE_URL . "/cms/admin/content_manager/";
    $subject = "";
}

$content_manager_panel = new ContentManagerPanel();
$email = $content_manager_panel->getUserEmail($user_id);

//set header
$email_header  = "From: " . config('site.contact_email') . ",\r\n";
$email_header .= "Reply-To:" . config('site.from_email') . "\r\n";
$email_header .= "Return-Path: " . config('site.contact_email') . "\r\n";
$email_header .= "MIME-Version: 1.0" . "\r\n";
$email_header .= "Content-type:text/html;charset=utf-8" . "\r\n";

$options = [
    "email_title" => $title,
    "cms_admin_link" => $cms_admin_link,
    "subject" => $subject
];
// Generate email template using generic content manager panel alert template
$email_body = $twig->render('emails/cms/cm_panel_alert.twig', $options);

mail($email, $options['subject'], $email_body, $email_header);

mail(DEV_EMAIL, 'COPY: ' . $options['subject'], $email_body, $email_header);
