<?php

defined('_MAILING') or die('Restricted access');

if (DEMO_MODE) {
    header("Location: index.php?manage=templates&action=list");
    exit();
}

$app->checkToken();

$id = (int)$_POST['templateid'];
$templatename = $_POST['templatename'];

// get template data
$stmt = $db->prepare(" SELECT * FROM ".PREF."_template WHERE id = ? ");
$stmt->bindParam(1, $id, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetchAll();
$data = $row[0];
$name = $templatename;
$doctype = $data['doctype'];
$html_header = $data['html_header'];
$body_attribs = $data['body_attribs'];
$subject = $data['subject'];
$content_html = $data['content_html'];
$content_txt = $data['content_txt'];
$thumb_filename = $data['thumb_filename'];

// insert new template with old data + new template name
$sql = "
    INSERT INTO ".PREF."_template (
        subject,
        name,
        doctype,
        html_header,
        body_attribs,
        content_html,
        content_txt,
        thumb_filename
    ) VALUES (
        :subject,
        :name,
        :doctype,
        :html_header,
        :body_attribs,
        :content_html,
        :content_txt,
        :thumb_filename
    )
";
$stmt = $db->prepare($sql);
$stmt->bindParam(':subject', $subject, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':doctype', $doctype, PDO::PARAM_STR);
$stmt->bindParam(':html_header', $html_header, PDO::PARAM_STR);
$stmt->bindParam(':body_attribs', $body_attribs, PDO::PARAM_STR);
$stmt->bindParam(':content_html', $content_html, PDO::PARAM_STR);
$stmt->bindParam(':content_txt', $content_txt, PDO::PARAM_STR);
$stmt->bindParam(':thumb_filename', $thumb_filename, PDO::PARAM_STR);
$stmt->execute();

header("Location: index.php?manage=templates&action=list");
