<?php

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

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

$app->checkToken();

// update template data
$subject = $_POST['subject'];
$name = $_POST['name'];
$doctype = stripslashes($_POST['doctype']);
$html_header = stripslashes($_POST['html_header']);
$body_attribs = stripslashes($_POST['body_attribs']);
$content_html = stripslashes($_POST['content_html']);
$content_txt = $_POST['content_txt'];
$thumb_filename = $_POST['thumb'];
$files = isset($_POST['files']) ? $_POST['files'] : 0 ;
$id = (int)$_POST['id'];
$date_modify = date("Y-m-d H:i:s", time());

$sql = "
    UPDATE 
        ".PREF."_template 
    SET 
        subject = :subject,
        name = :name,
        doctype = :doctype,
        html_header = :html_header,
        body_attribs = :body_attribs,
        content_html = :content_html,
        content_txt = :content_txt,
        date_modify = :date_modify,
        thumb_filename = :thumb_filename
    WHERE 
        id = :id
";
$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(':date_modify', $date_modify, PDO::PARAM_STR);
$stmt->bindParam(':thumb_filename', $thumb_filename, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

$sql = " DELETE FROM ".PREF."_template_att_conn WHERE id_template = :id ";
$stmt = $db->prepare($sql);              
$stmt->bindParam(':id', $id, PDO::PARAM_INT);   
$stmt->execute();

if ($files != 0) {
    foreach ($files as $file) {
        $sql = "
            INSERT INTO ".PREF."_template_att_conn (
                id_template,
                id_att
            ) VALUES (
                :id_template,
                :id_att
            )
        ";
        $stmt = $db->prepare($sql);
        $stmt->bindParam(':id_template', $id, PDO::PARAM_STR);    
        $stmt->bindParam(':id_att', $file,	PDO::PARAM_STR);
        $stmt->execute();
    }
}

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