{{ header }}{{ column_left }}
<div id="content">
	<div class="page-header">
		<div class="container-fluid">
			<h1>{{ heading_title }}</h1>
			<ol class="breadcrumb">
				{% for breadcrumb in breadcrumbs %}
					<li class="breadcrumb-item"><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
				{% endfor %}
			</ol>
		</div>
	</div>
	<div class="container-fluid">
		<div class="card">
			<div class="card-header"><i class="fa-solid fa-list"></i> {{ text_edit }}</div>
			<div class="card-body">
				<div class="row">
					<div class="col-lg-3 col-md-3 col-sm-12">
						<div class="list-group mb-3">
							<div class="list-group-item">
								<h4 class="list-group-item-heading">{{ text_store }}</h4>
							</div>
							<div class="list-group-item">
								<select name="store_id" id="input-store" class="form-select">
									<option value="0">{{ text_default }}</option>
									{% for store in stores %}
										<option value="{{ store.store_id }}">{{ store.name }}</option>
									{% endfor %}
								</select>
							</div>
						</div>
						<div class="list-group">
							<div class="list-group-item">
								<h4 class="list-group-item-heading">{{ text_template }}</h4>
							</div>
							<div id="path"></div>
						</div>
					</div>
					<div class="col-lg-9 col-md-12">
						<div class="alert alert-info"><i class="fa-solid fa-info-circle"></i> {{ text_twig }}</div>
						<div id="recent">
							<fieldset>
								<legend>{{ text_history }}</legend>
								<div id="history"></div>
							</fieldset>
						</div>
						<div id="code" style="display: none;">
							<ul class="nav nav-tabs"></ul>
							<div class="tab-content"></div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
<link href="view/javascript/codemirror/lib/codemirror.css" rel="stylesheet"/>
<link href="view/javascript/codemirror/theme/monokai.css" rel="stylesheet"/>
<script type="text/javascript" src="view/javascript/codemirror/lib/codemirror.js"></script>
<script type="text/javascript" src="view/javascript/codemirror/mode/xml/xml.js"></script>
<script type="text/javascript" src="view/javascript/codemirror/mode/htmlmixed/htmlmixed.js"></script>
<script type="text/javascript"><!--
$('#input-store').on('change', function (e) {
    var element = this;

    $.ajax({
        url: 'index.php?route=design/theme.path&user_token={{ user_token }}&store_id=' + $(element).val(),
        dataType: 'json',
        beforeSend: function () {
            $(element).prop('disabled', true);
        },
        complete: function () {
            $(element).prop('disabled', false);
        },
        success: function (json) {
            html = '';

            if (json['directory']) {
                for (i = 0; i < json['directory'].length; i++) {
                    html += '<a href="' + json['directory'][i]['path'] + '" class="list-group-item list-group-item-action directory">' + json['directory'][i]['name'] + ' <i class="fa-solid fa-arrow-right fa-fw float-end"></i></a>';
                }
            }

            if (json['file']) {
                for (i = 0; i < json['file'].length; i++) {
                    html += '<a href="' + json['file'][i]['path'] + '" class="list-group-item list-group-item-action file">' + json['file'][i]['name'] + ' <i class="fa-solid fa-arrow-right fa-fw float-end"></i></a>';
                }
            }

            $('#path').html(html);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
    });
});

$('#input-store').trigger('change');

$('#path').on('click', 'a.directory', function (e) {
    e.preventDefault();

    var element = this;

    $.ajax({
        url: 'index.php?route=design/theme.path&user_token={{ user_token }}&store_id=' + $('#input-store').val() + '&path=' + $(element).attr('href'),
        dataType: 'json',
        beforeSend: function () {
            $(element).find('i').removeClass('fa-arrow-right');
            $(element).find('i').addClass('fa-circle-notch fa-spin');
        },
        complete: function () {
            $(element).find('i').removeClass('fa-circle-notch fa-spin');
            $(element).find('i').addClass('fa-arrow-right');
        },
        success: function (json) {
            html = '';

            if (json['directory']) {
                for (i = 0; i < json['directory'].length; i++) {
                    html += '<a href="' + json['directory'][i]['path'] + '" class="list-group-item list-group-item-action directory">' + json['directory'][i]['name'] + ' <i class="fa-solid fa-arrow-right fa-fw float-end"></i></a>';
                }
            }

            if (json['file']) {
                for (i = 0; i < json['file'].length; i++) {
                    html += '<a href="' + json['file'][i]['path'] + '" class="list-group-item list-group-item-action file">' + json['file'][i]['name'] + ' <i class="fa-solid fa-arrow-right fa-fw float-end"></i></a>';
                }
            }

            if (json['extension']) {
                if (json['extension']['directory']) {
                    for (i = 0; i < json['extension']['directory'].length; i++) {
                        html += '<a href="' + json['extension']['directory'][i]['path'] + '" class="list-group-item list-group-item-action directory">' + json['extension']['directory'][i]['name'] + ' <i class="fa-solid fa-arrow-right fa-fw float-end"></i></a>';
                    }
                }

                if (json['extension']['file']) {
                    for (i = 0; i < json['extension']['file'].length; i++) {
                        html += '<a href="' + json['extension']['file'][i]['path'] + '" class="list-group-item list-group-item-action file">' + json['extension']['file'][i]['name'] + ' <i class="fa-solid fa-arrow-right fa-fw float-end"></i></a>';
                    }
                }
            }

            if (json['back']) {
                html += '<a href="' + json['back']['path'] + '" class="list-group-item list-group-item-action directory">' + json['back']['name'] + ' <i class="fa-solid fa-arrow-left fa-fw float-end"></i></a>';
            }

            $('#path').html(html);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
    });
});

var editor = [];

$('#path').on('click', 'a.file', function (e) {
    e.preventDefault();

    var element = this;

    // Check if the file has an extension
    var pos = $(element).attr('href').lastIndexOf('.');

    if (pos != -1) {
        var tab_id = $('#input-store').val() + '-' + $(element).attr('href').slice(0, pos).replace(/\//g, '-').replace(/_/g, '-');
    } else {
        var tab_id = $('#input-store').val() + '-' + $(element).attr('href').replace(/\//g, '-').replace(/_/g, '-');
    }

    if (!editor['#tab-' + tab_id]) {
        editor['#tab-' + tab_id] = $.ajax({
            url: 'index.php?route=design/theme.template&user_token={{ user_token }}&store_id=' + $('#input-store').val() + '&path=' + $(element).attr('href'),
            dataType: 'json',
            beforeSend: function () {
                $(element).find('i').removeClass('fa-arrow-right');
                $(element).find('i').addClass('fa-circle-notch fa-spin');
            },
            complete: function () {
                $(element).find('i').removeClass('fa-circle-notch fa-spin');
                $(element).find('i').addClass('fa-arrow-right');
            },
            success: function (json) {
                if (json['code']) {
                    $('#code').show();
                    $('#recent').hide();

                    $('.nav-tabs').append('<li class="nav-item"><a href="#tab-' + tab_id + '" data-bs-toggle="tab" class="nav-link">' + $(element).attr('href').split('/').join(' / ') + '&nbsp;&nbsp;<i class="fa-solid fa-minus-circle"></i></a></li>');

                    html = '<div class="tab-pane" id="tab-' + tab_id + '">';
                    html += '  <textarea name="code" id="input-code" rows="10" class="form-control"></textarea>';
                    html += '  <input type="hidden" name="store_id" value="' + $('#input-store').val() + '" id="input-' + tab_id + '-store"/>';
                    html += '  <input type="hidden" name="path" value="' + $(element).attr('href') + '" id="input-' + tab_id + '-path"/>';
                    html += '  <br/>';
                    html += '  <div class="float-end">';
                    html += '    <button type="button" class="btn btn-primary"><i class="fa-solid fa-floppy-disk"></i> {{ button_save|escape('js') }}</button>';
                    html += '    <button class="btn btn-danger"><i class="fa-solid fa-recycle"></i> {{ button_reset|escape('js') }}</button>';
                    html += '  </div>';
                    html += '</div>';

                    $('.tab-content').append(html);

                    $('.nav-tabs a[href=\'#tab-' + tab_id + '\']').tab('show');

                    // Initialize codemirrror
                    var codemirror = CodeMirror.fromTextArea(document.querySelector('.tab-content .active textarea'), {
                        mode: 'text/html',
                        lineNumbers: true,
                        lineWrapping: true,
                        autofocus: true,
                        theme: 'monokai'
                    });

                    codemirror.setValue(json['code']);
                    codemirror.setSize('100%', '500px');
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    } else {
        $('.nav-tabs a[href=\'#tab-' + tab_id + '\']').tab('show');
    }
});

$('#code .nav-tabs').on('click', 'i.fas.fa-minus-circle', function (e) {
    e.preventDefault();

    // 1. Remove tab functionality
    $(this).parent().removeAttr('data-bs-toggle');

    var remove = $(this).parent().attr('href');

    // 2. Remove entry in the editor array
    if (editor[remove]) {
        delete editor[remove];
    }

    // 3. Remove the tab
    $(this).parent().parent().remove();

    // 4. Remove the tab panel
    $(remove).remove();

    if ($(this).parent().hasClass('active')) {
        $('.nav-tabs li:last-child a').tab('show');
    }

    if (!$('#code > ul > li').length) {
        $('#code').hide();
        $('#recent').show();
    }
});

$('.tab-content').on('click', '.btn-primary', function (e) {
    var element = this;

    var editor = $('.tab-content .active .CodeMirror')[0].CodeMirror;

    $.ajax({
        url: 'index.php?route=design/theme.save&user_token={{ user_token }}&store_id=' + $('.tab-content .active input[name=\'store_id\']').val() + '&path=' + $('.tab-content .active input[name=\'path\']').val(),
        type: 'post',
        data: 'code=' + encodeURIComponent(editor.getValue()),
        dataType: 'json',
        beforeSend: function () {
            $(element).button('loading');
        },
        complete: function () {
            $(element).button('reset');
        },
        success: function (json) {
            $('.alert-dismissible').remove();

            if (json['error']) {
                $('#alert').prepend('<div class="alert alert-danger alert-dismissible"><i class="fa-solid fa-circle-exclamation"></i> ' + json['error'] + '  <button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>');
            }

            if (json['success']) {
                $('#alert').prepend('<div class="alert alert-success alert-dismissible"><i class="fa-solid fa-check-circle"></i> ' + json['success'] + '  <button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>');

                $('#history').load('index.php?route=design/theme.history&user_token={{ user_token }}');
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
    });
});

$('.tab-content').on('click', '.btn-danger', function (e) {
    if (confirm('{{ text_confirm }}')) {
        var element = this;

        $.ajax({
            url: 'index.php?route=design/theme.reset&user_token={{ user_token }}&store_id=' + $('.tab-content .active #input-store').val() + '&path=' + $('.tab-content .active input[name=\'path\']').val(),
            dataType: 'json',
            beforeSend: function () {
                $(element).button('loading');
            },
            complete: function () {
                $(element).button('reset');
            },
            success: function (json) {
                $('.alert-dismissible').remove();

                if (json['error']) {
                    $('#alert').prepend('<div class="alert alert-danger alert-dismissible"><i class="fa-solid fa-circle-exclamation"></i> ' + json['error'] + '  <button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>');
                }

                if (json['success']) {
                    $('#alert').prepend('<div class="alert alert-success alert-dismissible"><i class="fa-solid fa-check-circle"></i> ' + json['success'] + '  <button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>');
                }

                var codemirror = $('.tab-content .active .CodeMirror')[0].CodeMirror;

                codemirror.setValue(json['code']);
                codemirror.setSize('100%', '500px');
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    }
});

$('#history').on('click', '.pagination a', function (e) {
    e.preventDefault();

    $('#history').load(this.href);
});

$('#history').load('index.php?route=design/theme.history&user_token={{ user_token }}');

$('#history').on('click', '.btn-primary', function (e) {
    e.preventDefault();

    var element = this;

    // Check if the file has an extension
    var tab_id = $(element).parent().parent().find('input[name=\'store_id\']').val() + '-' + $(element).parent().parent().find('input[name=\'path\']').val().replace(/\//g, '-').replace(/_/g, '-');

    if (!editor['#tab-' + tab_id]) {
        $.ajax({
            url: 'index.php?route=design/theme.template&user_token={{ user_token }}&store_id=' + $(element).parent().parent().find('input[name=\'store_id\']').val() + '&path=' + $(element).parent().parent().find('input[name=\'path\']').val(),
            dataType: 'json',
            beforeSend: function () {
                $(element).button('loading');
            },
            complete: function () {
                $(element).button('reset');
            },
            success: function (json) {
                if (json['code']) {
                    $('#code').show();
                    $('#recent').hide();

                    $('.nav-tabs').append('<li class="nav-item"><a href="#tab-' + tab_id + '" data-bs-toggle="tab" class="nav-link">' + $(element).parent().parent().find('input[name=\'path\']').val().split('/').join(' / ') + '&nbsp;&nbsp;<i class="fa-solid fa-minus-circle"></i></a></li>');

                    html = '<div class="tab-pane" id="tab-' + tab_id + '">';
                    html += '  <textarea name="code" rows="10"></textarea>';
                    html += '  <input type="hidden" name="store_id" value="' + $(element).parent().parent().find('input[name=\'store_id\']').val() + '" />';
                    html += '  <input type="hidden" name="path" value="' + $(element).parent().parent().find('input[name=\'path\']').val() + '.twig" />';
                    html += '  <br/>';
                    html += '  <div class="float-end">';
                    html += '    <button type="button" class="btn btn-primary"><i class="fa-solid fa-floppy-disk"></i> {{ button_save|escape('js') }}</button>';
                    html += '    <button class="btn btn-danger"><i class="fa-solid fa-recycle"></i> {{ button_reset|escape('js') }}</button>';
                    html += '  </div>';
                    html += '</div>';

                    $('.tab-content').append(html);

                    $('.nav-tabs a[href=\'#tab-' + tab_id + '\']').tab('show');

                    // Initialize codemirrror
                    var codemirror = CodeMirror.fromTextArea(document.querySelector('.tab-content .active textarea'), {
                        mode: 'text/html',
                        lineNumbers: true,
                        lineWrapping: true,
                        autofocus: true,
                        theme: 'monokai'
                    });

                    codemirror.setValue(json['code']);
                    codemirror.setSize('100%', '500px');
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    } else {
        $('.nav-tabs a[href=\'#tab-' + tab_id + '\']').tab('show');
    }
});

$('#history').on('click', '.btn-danger', function (e) {
    e.preventDefault();

    if (confirm('{{ text_confirm }}')) {
        var element = this;

        $.ajax({
            url: $(element).attr('href'),
            dataType: 'json',
            beforeSend: function () {
                $(element).button('loading');
            },
            complete: function () {
                $(element).button('reset');
            },
            success: function (json) {
                $('.alert-dismissible').remove();

                if (json['error']) {
                    $('#history').before('<div class="alert alert-danger alert-dismissible"><i class="fa-solid fa-circle-exclamation"></i> ' + json['error'] + ' <button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>');
                }

                if (json['success']) {
                    $('#history').before('<div class="alert alert-success alert-dismissible"><i class="fa-solid fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>');

                    $('#history').load('index.php?route=design/theme.history&user_token={{ user_token }}');
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    }
});
//--></script>
{{ footer }}
