<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="content-wrapper">
	<section class="content-header">
		<?php echo $pagetitle; ?>
		<?php echo $breadcrumb; ?>
	</section>
	<section class="content">
		<div class="row">
			<div class="col-xs-12">
				<!--
				<button onclick="button_modal_add()" data-toggle="modal" data-target="#div_modal_add" class="btn btn-default"><i class="fa fa-plus"></i> 문제 등록</button>
				-->
				<button onclick="button_modal_add()" class="btn btn-default"><i class="fa fa-plus"></i> 문제 등록</button>
			</div>
		</div>
		<div class="row">
			<div class="col-md-12">
				<div class="box">
					<div class="box-body">
						<table id="table_question" class="table table-striped table-hover">
							<thead>
								<tr>
									<th>인덱스</th>
									<th>미션</th>
									<th>문제</th>
									<th>상태</th>
									<th>상세</th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ($questions as $question){ ?>
								<tr>
									<td><?= $question->index ?></td>
									<td><?= $question->level ?></td>
									<td><?= $question->question ?></td>
									<td><?= $question->is_active == 1 ? '<button class="btn btn-xs btn-success" disabled>활성</button>' : '<button class="btn btn-xs btn-danger" disabled>비활성</button>'?></td>
									<td><?= '<button onclick="button_modal(\''.$question->uid.'\', \''.$question->level.'\', \''.$question->question.'\', \''.(json_decode($question->answers)[0]->a).'\', \''.(json_decode($question->answers)[0]->c).'\', \''.(json_decode($question->answers)[1]->a).'\', \''.(json_decode($question->answers)[1]->c).'\', \''.(json_decode($question->answers)[2]->a).'\', \''.(json_decode($question->answers)[2]->c).'\', \''.$question->explain.'\', \''.$question->is_active.'\')" class="btn btn-xs btn-default">확인</button>' ?></td>
								</tr>
								<?php } ?>
							</tbody>
						</table>
					</div>
				</div>
			</div>
		</div>
	</section>
</div>
<div id="div_modal_add" class="modal fade" role="dialog">
	<div>
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal">&times;</button>
				<h4 class="modal-title">문제 등록</h4>
			</div>
			<div class="modal-body">
				<label>미션</label>
				<input id="input_level_add" class="form-control" type="number" placeholder="미션 번호를 입력하세요.">
				<br>
				<label>문제</label>
				<textarea id="input_question_add" class="form-control" rows="4" placeholder="문제를 입력하세요."></textarea>
				<br>
				<label>답안(정답에 체크)</label>
				<div class="row" style="padding: 0px 15px 15px 15px;">
					<div class="col-12">
						<input type="radio" id="radio0_add" name="answer_add" value="0">&nbsp;
						<label>
							<input id="input_a0_add" class="form-control" placeholder="첫번째 답안">
						</label>
					</div>
					<div class="col-12">
						<input type="radio" id="radio1_add" name="answer_add" value="1">&nbsp;
						<label>
							<input id="input_a1_add" class="form-control" placeholder="두번째 답안">
						</label>
					</div>
					<div class="col-12">
						<input type="radio" id="radio2_add" name="answer_add" value="2">&nbsp;
						<label>
							<input id="input_a2_add" class="form-control" placeholder="세번째 답안">
						</label>
					</div>
				</div>
				<label>해설</label>
				<textarea id="input_explain_add" class="form-control" rows="8" placeholder="해설을 입력하세요."></textarea>
			</div>
			<div class="modal-footer">
				<button onclick="button_add()" class="btn btn-success">새로운 문제 등록</button>
			</div>
		</div>
	</div>
</div>
<div id="div_modal" class="modal fade" role="dialog">
	<div>
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal">&times;</button>
				<h4 class="modal-title">문제 정보</h4>
			</div>
			<div class="modal-body">
				<label>고유값</label>
				<input id="input_uid" class="form-control" disabled>
				<br>
				<label>미션</label>
				<input id="input_level" type="number" class="form-control">
				<br>
				<label>문제</label>
				<textarea id="input_question" class="form-control" rows="4"></textarea>
				<br>
				<label>답안(정답에 체크)</label>
				<div class="row" style="padding: 0px 15px 15px 15px;">
					<div class="col-12">
						<input type="radio" id="radio0" name="answer" value="0">&nbsp;
						<label>
							<input id="input_a0" class="form-control">
						</label>
					</div>
					<div class="col-12">
						<input type="radio" id="radio1" name="answer" value="1">&nbsp;
						<label>
							<input id="input_a1" class="form-control">
						</label>
						</div>
					<div class="col-12">
						<input type="radio" id="radio2" name="answer" value="2">&nbsp;
						<label>
							<input id="input_a2" class="form-control">
						</label>
					</div>
				</div>
				<label>해설</label>
				<textarea id="input_explain" class="form-control" rows="8"></textarea>
			</div>
			<div id="div_modal_footer" class="modal-footer">
			</div>
		</div>
	</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animsition/3.2.1/js/animsition.min.js"></script>
<script>
$(document).ready(function (){
	$(document).on('hide.bs.modal','#div_modal', function () {
		$('#div_modal_footer').empty();
		$('#div_modal_body_mission').empty();
		$('#div_modal_footer_mission').empty();
	});

	var table_question = new DataTable('#table_question', {
		columnDefs: [{
			targets: 2,
			render: DataTable.render.ellipsis(40),
		}],
		pageLength: 25,
		layout: {
			topStart: {
				pageLength: {
					menu: [10, 25, 100]
				}
			}
		}
	});
});

function button_toggle_is_active(uid){
	if(confirm('문제의 상태를 변경할까요? 상태는 언제든지 다시 복구할 수 있습니다.')){
		$.ajax({
			url: '<?= base_url() ?>admin/questions/toggle_is_active',
			type: 'POST',
			data: {
				uid: uid,
			},
			success: function (res){
				console.log(res);
				if(res > 0){
					alert('상태 변경에 성공했습니다.');
					location.reload();
				}else{
					alert('상태 변경에 실패했습니다.');
				}
			},
			error: function (data, status, err){
				console.log(err);
			}
		});
	}
}

function replaceSpecial(text){
	var res_text = text.replaceAll('"', '');
	res_text = res_text.replaceAll("'", '');
	res_text = res_text.replaceAll('(', '');
	res_text = res_text.replaceAll(')', '');
	return res_text;
}

function button_set_question(uid){
	var correct = $('input:radio[name="answer"]:checked').val();
	var level = $('#input_level').val();
	var question = $('#input_question').val();
	question = replaceSpecial(question);
	var answers = [{
		'a': $('#input_a0').val(),
		'c': (correct == 0 ? '1' : '0'),
	},{
		'a': $('#input_a1').val(),
		'c': (correct == 1 ? '1' : '0'),
	},{
		'a': $('#input_a2').val(),
		'c': (correct == 2 ? '1' : '0'),
	}];
	var explain = $('#input_explain').val();
	explain = replaceSpecial(explain);
	if((parseInt(level) <= 0) || (question.length <= 0) || (explain.length <= 0)){
		alert('미션은 0보다 커야하며 문제 및 해설에는 내용이 존재해야 합니다.');
		return;
	}
	if(confirm('문제의 정보를 변경할까요? 언제든지 다시 변경할 수 있습니다.')){
		$.ajax({
			url: '<?= base_url() ?>admin/questions/set_question',
			type: 'POST',
			data: {
				uid: uid,
				level: level,
				question: question,
				answers: JSON.stringify(answers),
				explain: explain,
			}, success: function (res){
				console.log(res);
				if(res > 0){
					alert('정보 변경에 성공했습니다.');
					location.reload();
				}else{
					alert('정보 변경에 실패했습니다.');
				}
			}, error: function (data, status, err){
				console.log(err);
			}
		});
	}
}

function button_modal(uid, level, question, a0, c0, a1, c1, a2, c2, explain, is_active){
	$('#input_uid').val(uid);
	$('#input_level').val(level);
	$('#input_question').val(question);
	$('#input_a0').val(a0);
	$('#input_a1').val(a1);
	$('#input_a2').val(a2);
	if(c0 == '1'){
		$('#radio0').prop('checked', true);
	}
	if(c1 == '1'){
		$('#radio1').prop('checked', true);
	}
	if(c2 == '1'){
		$('#radio2').prop('checked', true);
	}
	$('#input_explain').val(explain);
	if(is_active == 1){
		$('#div_modal_footer').prepend(`<button onclick="button_toggle_is_active('${uid}')" class="btn btn-danger" style="float: left;">문제 삭제</button>`);
	}else{
		$('#div_modal_footer').prepend(`<button onclick="button_toggle_is_active('${uid}')" class="btn btn-warning" style="float: left;">문제 복구</button>`);
	}
	$('#div_modal_footer').append(`<button onclick="button_set_question('${uid}')" class="btn btn-success" style="float: right;">문제 정보 변경</button>`);
	//get_missions(uid);
	$('#div_modal').modal('show');
}

function button_modal_add(){
	$('#div_modal_add').modal('show');
}

function button_add(){
	var level = $('#input_level_add').val();
	var question = $('#input_question_add').val();
	question = replaceSpecial(question);
	var correct = $('input:radio[name=answer_add]:checked').val();
	var answers = [{
		'a': $('#input_a0_add').val(),
		'c': (correct == 0 ? '1' : '0'),
	},{
		'a': $('#input_a1_add').val(),
		'c': (correct == 1 ? '1' : '0'),
	},{
		'a': $('#input_a2_add').val(),
		'c': (correct == 2 ? '1' : '0'),
	}];
	var explain = $('#input_explain_add').val();
	explain = replaceSpecial(explain);
	if((parseInt(level) <= 0) || (question.length <= 0) || (explain.length <= 0) || (($('#input_a0_add').val()).length <= 0) || (($('#input_a1_add').val()).length <= 0) || (($('#input_a2_add').val()).length <= 0)){
		alert('미션은 0보다 커야하며 문제 및 해설에는 내용이 존재해야 합니다.');
		return;
	}
	if(confirm('문제를 새로 등록할까요? 문제는 언제든지 변경할 수 있습니다.')){
		$.ajax({
			url: '<?= base_url() ?>admin/questions/add_question',
			type: 'POST',
			data: {
				level: level,
				question: question,
				answers: JSON.stringify(answers),
				explain: explain,
			}, success: function (res){
				console.log(res);
				if(res > 0){
					alert('문제 등록에 성공했습니다.');
					location.reload();
				}else{
					alert('문제 등록에 실패했습니다.');
				}
			}, error: function (data, status, err){
				console.log(err);
			}
		});
	}
}
</script>
