<div id="page-wrapper">
	<div class="container-fluid">
		<!-- Flot Charts -->
		<div class="row">
			<div class="col-lg-12">
				<h2 class="page-header"><?php echo T('Редактирование контента'); ?></h2>
			</div>
		</div>
		<!-- /.row -->
        <style media="screen">
            .gg {
                color: #468847;
                background-color: #dff0d8;
                border: 1px solid #d6e9c6;
            }
            button[name="content_delete"],
            button[name="content_add"] {
                text-align:center;
                font-weight:bold;
                float: right;
            }

            button[name="content_add"] {
                float: left;
            }
        </style>
		<?php echo flash_show('adg_media'); ?>

		<div class="row">
			<div class="col-lg-12">
				<div id="settings">
					<div class="bs-example bs-example-tabs">
						<ul id="myTab" class="nav nav-tabs">
							<?php
								$count = get_value("SELECT COUNT(*) FROM `content` WHERE `category` = ".escape_db('media'));
								$content = get_list('content', '`category` = '.escape_db('media'));
							?>
							<?php $i = 0; foreach ($content as $item) { ?>
                                <?php $media_data[$item['name']] = json_decode($item['data'], true); ?>
							    <li style="width: calc(100% / <?php echo (int)$count; ?>);" class="<?php echo !$i ? 'active' : ''; ?>"><a href="#media_<?php echo $item['name']; ?>" data-toggle="tab"><?php echo T($media_data[$item['name']]['title']); ?></a></li>
                            <?php $i++; } ?>
						</ul>
						<br>
						<div id="myTabContent" class="tab-content">
							<!-- Список планов -->
                            <?php $i = 0; foreach ($media_data as $name => $data) { ?>
    							<div class="tab-pane fade <?php echo !$i ? 'active in' : ''; ?>" id="media_<?php echo escape($name); ?>">
    								<div class="panel panel-primary">
    									<div class="panel-heading">
    										<h3 class="panel-title">
    											<i class="fa fa-bar-chart-o"></i>
    											<?php echo T($data['title']); ?>
    											<span style="float: right;">
    												<i class="fa fa-question-circle" aria-hidden="true" data-toggle="tooltip" data-placement="left"
    												   title="<?php echo $data['description']; ?>"></i>
    											</span>
    										</h3>
    									</div>
    									<div class="panel-body">
                                            <?php $j = 0; foreach ($data['data'] as $key => $kItem) { ?>
                                                <div class="col-md-12 category">
                                                    <?php if (is_string($key)) { ?>
                                                        <div class="col-md-12">
                                                            <div class="col-md-11">
                                                                <input class="form-control gg" name="t" style="text-align:center;font-weight:bold;" value="<?php echo escape($key); ?>"><br>
                                                            </div>
                                                            <div class="col-md-1">
                                                                <button type="button" name="category_delete" class="btn btn-danger" style="text-align:center;font-weight:bold;float:right;"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
                                                            </div>
                                                        </div>
                                                    <?php } ?>
                                                    <?php if (is_array($kItem)) { ?>
                                                        <?php $m = 0; foreach ($kItem as $q => $a) { ?>
                                                            <?php $t_l = is_string($q); ?>
                                                            <div class="col-md-12 qa">
                                                                <?php if (is_string($q)) { ?>
                                                                    <div class="col-md-3">
                                                                        <textarea name="q" class="form-control" style="height:75px;"><?php echo escape($q); ?></textarea>
                                                                    </div>
                                                                <?php } ?>
                                                                <div class="col-md-<?php echo is_string($q) ? 8 : 11; ?>">
                                                                    <textarea name="a" class="form-control" style="height:75px;"><?php echo escape($a); ?></textarea><br>
                                                                </div>
                                                                <div class="col-md-1">
                                                                    <button type="button" class="btn btn-danger"  name="content_delete" value="Удалить" ><i class="fa fa-trash-o" aria-hidden="true"></i></button>
                                                                    <button type="button" class="btn btn-success" name="content_add"    value="Добавить"><i class="fa fa-plus"    aria-hidden="true"></i></button>
                                                                </div>
                                                            </div>
                                                        <?php $m++; } ?>
                                                    <?php } ?>
                                                </div>
                                            <?php $j++; } ?>
                                            <div class="col-md-12" id="save_<?php echo escape($name); ?>">
												<p class="message_a" style="text-align:center;font-weight:bold;"></p>
                                                <div class="col-md-12">
                                                    <div class="col-md-12">
                                                        <button type="button" name="update" data-type="<?php echo escape($name); ?>" class="btn btn-default" style="width:100%;"><?php echo T('ОБНОВИТЬ'); ?></button>
                                                    </div>
                                                </div>
                                            </div>
    									</div>
    								</div>
    							</div>
                            <?php $i++; } ?>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<script type="text/javascript">
    $(document).on('click', "button[name='content_add']", function () {
        var b = $(this).parent().children('textarea[name="q"]'),
			_button = [], input = [];

		/* кнопки управления */
        _button = {
			'delete' : button('content_delete', 	'danger',  	fa_fa('trash-o')),
        	'add'	 : button('content_add',    	'success', 	fa_fa('plus'))
		};

		/* ключ - значение */
        input = {
			'key'	: b ? col(tarea('q'), 3) : '',
        	'value' : col(tarea('a', true), b ? 8 : 11)
		};

        $(this).parent().parent().after(col(arr2str (input) + arr2str (_button, 1), 12, 'md', 'qa'));
    });

	function arr2str (AssocArray, size=false) {
    	var s = "";
    	for (var i in AssocArray) { s += AssocArray[i]; }
    	return size ? col(s, size) : s;
	}

	function fa_fa (key) {
		return '<i class="fa fa-' + key + '" aria-hidden="true"></i>';
	}

	function button (name, _class, value) {
		return '<button type="button" class="btn btn-' + _class + '" name="' + name + '">' + value + '</button>';
	}

	function col (value, size=12, type='md', _class="") {
		return '<div class="col-' + type + '-' + size + ' ' + _class +'">' + value + '</div>';
	}

	function tarea (name, br=false) {
		return "<textarea name='" + name + "' class='form-control' style='height:75px;'></textarea>" + (br ? "<br>" : "");
	}

    $(document).on('click', "button[name='content_delete']", function () {
        if (confirm('Удалить вопрос?')) $(this).parent().parent().remove();
    });

    $(document).on('click', "button[name='category_delete']", function () {
        var gg = $(this).parent().parent().children("div").children(".gg").val();
        if (confirm('Удалить раздел "' + gg + '"? Весь контент раздела так же будет удален!')) $(this).parent().parent().parent().remove();
    });

    $(document).on('click', "button[name='update']", function () {
        var gg = $(this).closest('.panel-body').find(".category");
        var arr = {};

        $.each(gg, function (index, value) {
            var temp = $(value).find('.gg').val();
            var k = temp ? temp : index;
            var _arr = $(value).find('.qa');
            if (_arr) arr[k] = {};
            $.each(_arr, function (key, item) {
                var _temp = $(item).find('textarea[name="q"]').val();
                var q = _temp ? _temp : key;
                arr[k][q] = $(item).find('textarea[name="a"]').val();
            });
        });

		var content_type = $(this).data('type');

		console.log(arr);

		$.post('/handlers/adg/edit_content.php', {'needle': JSON.stringify({ data : arr , content_name : content_type })}, function (res) {
	        var message = $("#save_" + content_type + " > .message_a");
	        message.css('color', res['error'] ? 'red' : 'green');
	        message.html(res['message']);
	    });
    });
</script>
