<?php
/**
 * Loading the builderjs editor for editing newsletter contents.
 *
 *  @author Imran Khan <imran.khan@interspire.com>
 */

if (!isset($_GET['IDTI'])) {
    die('Invalid request');
}


// Make sure that the IEM controller does NOT redirect request.
if (!defined('IEM_NO_CONTROLLER')) {
	define('IEM_NO_CONTROLLER', true);
}

/**
* Require base sendstudio functionality. This connects to the database, sets up our base paths and so on.
*/
require_once 'index.php';

// Get Contact Lists Custom Fields for Builderjs Editor > Insert Contact List Custom Fields
require_once(SENDSTUDIO_BASE_DIRECTORY . DIRECTORY_SEPARATOR . 'functions/showcustomfields.php');
$clcf = new ShowCustomFields();
$contactlist_cf = $clcf->getContactListWithCustomFieldsBuilderJS();

// Get Surveys for Builderjs Editor > Insert Survey
require_once(SENDSTUDIO_BASE_DIRECTORY . DIRECTORY_SEPARATOR . 'addons' . DIRECTORY_SEPARATOR . 'surveys/api/surveys.php');
$survey_api = new Addons_survey_api();
$survey_data = $survey_api->GetSurveysListBuilderJS('');

// Get Dynamic Content Tags for Builderjs Editor > Insert DCT
require_once(SENDSTUDIO_BASE_DIRECTORY . DIRECTORY_SEPARATOR . 'addons' . DIRECTORY_SEPARATOR . 'dynamiccontenttags/api/dynamiccontenttag.php');
$dct_api = new DynamicContentTag_Api_Tag();
$dct_data = $dct_api->GetDynamicContentTagsListBuilderJS('');
                

$type = isset($_GET['type']) ? $_GET['type'] : 'newsletters';
$ElementId = isset($_GET['ElementId']) ? $_GET['ElementId'] : '';
$ImageDirTypeId = $_GET['IDTI'] ?? 0;
?>
<!doctype html>
<html>

<head>
    <title>IEM | Block Editor</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="<?php echo SENDSTUDIO_APPLICATION_URL; ?>/admin/includes/js/builderjs/builder.css">
	<script src="<?php echo SENDSTUDIO_APPLICATION_URL; ?>/admin/includes/js/builderjs/builder.js"></script>
    <script>
        function popup_to_opener_content(act) {
			if($("#builder_iframe").contents().find("body")[1]){
				$("#builder_iframe").contents().find("body")[1].remove();
			} 
			 if($("#builder_iframe").contents().find("head")[1]){
			 
				$("#builder_iframe").contents().find("head")[0].remove();
			}
            document.getElementById("editable").click();
			$("div.loadding-indicator").show(1000);
            var insert_contents = $("#builder_iframe").contents().find("html")[0].outerHTML;
            
			insert_contents = this.cleanupHtml(insert_contents);
            insert_contents = insert_contents.toLowerCase().includes("DOCTYPE html".toLowerCase()) || (insert_contents = "<!DOCTYPE html>" + insert_contents);
            window.opener.document.getElementById('builder_iframe').contentWindow.document.body.innerHTML = insert_contents;

            //console.log(insert_contents);
            window.opener.document.getElementById('<?php echo $ElementId ?>').value = insert_contents;
            
            $("div.loadding-indicator").hide(1000);

            if (act == 'exit') { window.close(); }
        }

        function openerContent() {
            document.getElementById('builder_iframe').contentWindow.document.body.outerHTML =  window.opener.document.getElementById('<?php echo $ElementId ?>').value;
            //document.getElementById('builder_iframe').contentWindow.document.body.querySelectorAll("meta,title,link,style").forEach((e) => e.remove());
            //var inner_data = document.getElementById('builder_iframe').contentWindow.document.body.innerHTML;
            //document.getElementById('builder_iframe').contentWindow.document.body.innerHTML = inner_data.replace(/^\s*$(?:\r\n?|\n)/gm, "");
        }

        function cleanupHtml(e) {
            var e = e
                .replace(/element-selected/g, "")
                .replace(/builder-outline-move-hook/g, "")
                .replace(/builder-outline-selected-controls/g, "")
                .replace(/(<link([^>]+)builder\-helper([^>]+)>)/gi, "")
                .replace(/(<script([^>]+)builder\-helper([^>]+)>\<\/script>)/gi, "")
                .replace(/<link[^>]+tinymce\/skins[^>]+>/g, "").replace(/^\s*$(?:\r\n?|\n)/gm, "");

            return e;
        }

        function window_close() {
            if (confirm("Do you want to close this Window?") == true) {
                window.close();
            }
        }
    </script>

    <script>
        var clcf_tags = [
            <?php echo $contactlist_cf; ?>    
        ];

        var cf_tags = [
            {
                type: 'menuitem',
                text: "Contact List Name",
                onAction: function () {
                    tinymce.activeEditor.insertContent("%%listname%%");
                }
            },
            {
                type: 'menuitem',
                text: "Contacts Email Address",
                onAction: function () {
                    tinymce.activeEditor.insertContent("%%emailaddress%%");
                }
            },
            {
                type: 'menuitem',
                text: "Email Confirmation Link",
                onAction: function () {
                    tinymce.activeEditor.insertContent("%%confirmlink%%");
                }
            },
            {
                type: 'menuitem',
                text: "Subscribe Date",
                onAction: function () {
                    tinymce.activeEditor.insertContent("%%subscribedate%%");
                }
            },
            {
                type: 'menuitem',
                text: "Todays Date",
                onAction: function () {
                    tinymce.activeEditor.insertContent("%%todaysdate%%");
                }
            },
            {
                type: 'menuitem',
                text: "Link to Web Version of this Email",
                onAction: function () {
                    tinymce.activeEditor.insertContent("%%webversion%%");
                }
            },
            {
                type: 'menuitem',
                text: "Company Name",
                onAction: function () {
                    tinymce.activeEditor.insertContent("%%companyname%%");
                }
            },
            {
                type: 'menuitem',
                text: "Company Address",
                onAction: function () {
                    tinymce.activeEditor.insertContent("%%companyaddress%%");
                }
            },
            {
                type: 'menuitem',
                text: "Company Phone Number",
                onAction: function () {
                    tinymce.activeEditor.insertContent("%%companyphone%%");
                }
            },
            {
                type: 'menuitem',
                text: "Contact's IP Address",
                onAction: function () {
                    tinymce.activeEditor.insertContent("%%ipaddress%%");
                }
            }
        ];

        var survey_tags = [
            <?php echo $survey_data; ?>
        ];

		var tags = [];

        var dct_tags = [
            <?php echo $dct_data; ?>
        ];

        // new builder
        var editor = new Editor({
            emailMode: true,
            strict: true,
            id: '<?php echo $ElementId ?>',
            showInlineToolbar: true, // default == true
            root: '<?php echo SENDSTUDIO_APPLICATION_URL; ?>/admin/includes/js/builderjs/',
            urlBack: window.location.origin,
            uploadAssetUrl: 'remote.php',
            uploadAssetMethod: 'POST',
            uploadTemplateUrl: 'upload.php',
            uploadTemplateCallback: function (response) {
                window.location = response.url;
            },
            /*
                Disable features: 
                change_template|export|save_close|footer_exit|help
            */
            disableFeatures: ['change_template', 'export', 'save_close', 'footer_exit', 'help'],
            saveUrl: '', // You can try with other sample server scripts like: save-to-mysql.php or save-to-aws-s3.php
            saveMethod: 'POST',
            data: {
                token: 'CSRF_TOKEN',
                type: '<?php echo $type ?>',
                what: 'uploadbuilderjsimage',
                app_url: '<?php echo SENDSTUDIO_APPLICATION_URL; ?>',
                ImageDirTypeId: '<?php echo $ImageDirTypeId ?>',
            },
            /*
                Dynamic Contents feature:
                cf_tags: Custom Fields, clcf_tags: Contact Lists Custom Fields, dct_tags: Dynamic Content Tags, survey_tags: Survey Tags
            */
            tags:tags,
			cf_tags: cf_tags,
            clcf_tags: clcf_tags,
            dct_tags: dct_tags,
            survey_tags: survey_tags,
            changeTemplateCallback: function (url) {
                window.location = url;
            },
            export: {
                url: ''
            },
            backgrounds: [
            ]
        });

        // loading text 
	    editor.load('<div style="padding:20%;"> <h1>Loading... </h1> </div>');
        
        //console.log(editor);

        jQuery(document).ready(function () {
            editor.init();
            setTimeout(openerContent, 3000);
        });
    </script>
 
    <style>
        .lds-dual-ring {
            display: inline-block;
            width: 80px;
            height: 80px;
        }

        .lds-dual-ring:after {
            content: " ";
            display: block;
            width: 30px;
            height: 30px;
            margin: 4px;
            border-radius: 80%;
            border: 2px solid #aaa;
            border-color: #007bff transparent #007bff transparent;
            animation: lds-dual-ring 1.2s linear infinite;
        }

        @keyframes lds-dual-ring {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }
		
        [builder-element=CellElement]:empty::after {
            content: "Drag items here";
        }

    </style>
</head>

<body class="overflow-hidden">
    <div style="text-align: center;border: x solid red;
            height: 100vh;
            vertical-align: middle;
            padding: auto;
            display: flex;">
        <div style="margin:auto" class="lds-dual-ring"></div>
    </div>
</body>

</html>