<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

//echo  $_GET['filename_news'];

    require 'config.php';

//include('../commun/connection_bdd.php');

    $html         = ( get_magic_quotes_gpc() ) ? stripslashes($_POST['html']) : $_POST['html'];
    $html = str_replace('border: 1px dotted red;', '', $html);
    $titre         = ( get_magic_quotes_gpc() ) ? stripslashes($_POST['titre']) : $_POST['titre'];
    //$option       = ( $_POST['option']=='' ) ? $_POST['option'] : 'template';

    /*
     *  QUANDO SI SALVA LA SORGENTE ADESSO SI PUO AVERE ACCESSO A TUTTI I PARAMETRI 'data'
     *  DEL DIV CON ID='tosave';
     */

    $config = array();
    if (isset($_POST['data'])) {
        foreach ($_POST['data'] as $param=>$value) {    $config[$param] = $value; }
    }

    /*
     * IN $config TROVI I VALORI DELLE VARIABILI PER INDICE
     */

    if($_POST['file'])
        $filename     = dirname(__FILE__).'/tmp/'.$_POST['file'];
    else
        $filename     = dirname(__FILE__).'/tmp/'.time().'.html';
    $templateFile = file_get_contents('template.html');
    // saving the file
    //$templateFile = str_replace('{title}', $title, $templateFile);
    $templateFile = str_replace('{body}', $html, $templateFile);

    if (  file_put_contents($filename, $templateFile) ) {
         echo str_replace(dirname(__FILE__), 'http://'.$_SERVER['HTTP_HOST'].$path ,$filename);
         
    }

    $filename = basename($filename);

    include '../db.php';

    $sth  = $pdo->prepare('SELECT * FROM newsletter WHERE filename = :filename');
    //$sth ->execute([':filename' => $filename]);

    
    //if($sth->fetchAll()) {
    //    $stmt = $pdo->prepare("UPDATE newsletter SET titre = :titre WHERE filename = :filename");
    //    $stmt->bindParam(':filename', $filename);
    //    $stmt->bindParam(':titre', $titre);
    //    $stmt->execute();
    //}
    //else {
        
        $stmt = $pdo->prepare("DELETE FROM newsletter WHERE filename = :filename ");
        $stmt->bindParam(':filename', $filename);
        $stmt->execute();
        
        $stmt = $pdo->prepare("INSERT INTO newsletter (filename, titre) VALUES (:filename, :titre)");
        $stmt->bindParam(':filename', $filename);
        $stmt->bindParam(':titre', $titre);
        $stmt->execute();
    //}
    
	    