<?php if (! defined('BASEPATH')) { exit('No direct script access allowed'); }

class Pagebuilder extends Admin_Controller
{
    public function __construct()
    {
        $this->theme = 'pagebuilder';
        parent::__construct();
    }
    
    public function index()
    {
        Template::set_view('editor_view');
                
        Template::render();
    }
    
    public function sanitizeFileName($fileName)
    {
        define('MAX_FILE_LIMIT', 1024 * 1024 * 2);//2 Megabytes max html file size

        {
        //sanitize, remove double dot .. and remove get parameters if any
        $fileName = __DIR__ . '/' . preg_replace('@\?.*$@', '', preg_replace('@\.{2,}@', '', preg_replace('@[^\/\\a-zA-Z0-9\-\._]@', '', $fileName)));
        return $fileName;
        }
    
        $html = "";
        if (isset($_POST['startTemplateUrl']) && !empty($_POST['startTemplateUrl'])) {
            $startTemplateUrl = sanitizeFileName($_POST['startTemplateUrl']);
            $html = file_get_contents($startTemplateUrl);
        } elseif (isset($_POST['html'])) {
            $html = substr($_POST['html'], 0, MAX_FILE_LIMIT);
        }
    
        $fileName = sanitizeFileName($_POST['fileName']);
    
        if (file_put_contents($fileName, $html)) {
            echo $fileName;
        } else {
            echo 'Error saving file '  . $fileName;
        }
    }

    public function upload()
    {
        //This script is used by image upload input to save the imge on the server and return the image url to be set as image src attribute.

        define('UPLOAD_FOLDER', __DIR__ . '/');
        define('UPLOAD_PATH', '/');

        move_uploaded_file($_FILES['file']['tmp_name'], UPLOAD_FOLDER . $_FILES['file']['name']);

        echo UPLOAD_PATH . $_FILES['file']['name'];
    }
    
    public function load_template(){
        $uri = $this->uri->segment_array();
    
        if (count($uri) >= 4) 
        {
            $local = '/demo';
            for ($i = 3;$i <= count($uri);$i++) 
            {
                $local.= "/" . $uri[$i];
            }
        }
        
        /*Assets::add_module_css('pagebuilder', array(
            'editor.css',
            ));
    
         Assets::add_module_js('pagebuilder', array('jquery.min',
 'bootstrap.min',
        ));*/

       $this->load->view($uri[1].$local);
       //Template::render();
        //Template::load_view($uri[1].$local, '', '', '', $data['html']);
        
      //  echo $data['html']; 
        
        //return $data['html'];
    }
    
    
    
    

    
    
    
}