@extends('admin.layout.page-app')
@section('page_title', __('label.exam_questions'))
@section('tab_title', __('label.exam_questions'))

@section('content')
    @include('admin.layout.sidebar')

    <div class="right-content">
        @include('admin.layout.header')

        <div class="body-content">
            <!-- mobile title -->
            <h1 class="page-title-sm">{{__('label.exam_questions')}}</h1>

            <div class="border-bottom row">
                <div class="col-sm-10">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="{{ route('admin.dashboard') }}">{{__('label.dashboard')}}</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('admin.exam.index') }}">{{__('label.exams')}}</a></li>
                        <li class="breadcrumb-item active" aria-current="page">{{__('label.exam_questions')}}</li>
                    </ol>
                </div>
                <div class="col-sm-2 d-flex align-items-center justify-content-end">
					<a href="{{ route('admin.exam.index') }}" class="btn btn-default mw-120" style="margin-top:-14px">{{__('label.exams')}}</a>
				</div>
            </div>

            <ul class="nav nav-pills custom-tabs inline-tabs" id="pills-tab" role="tablist">
                <li class="nav-item">
                    <a class="nav-link active" id="add-question-tab" data-toggle="tab" href="#add-question" role="tab" aria-controls="add-question" aria-selected="true">{{__('label.add_question')}}</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="import-question-tab" data-toggle="tab" href="#import-question" role="tab" aria-controls="import-question" aria-selected="false">{{__('label.import_question')}}</a>
                </li>
            </ul>

            <div class="tab-content" id="pills-tabContent">
                <div class="tab-pane fade show active" id="add-question" role="tabpanel" aria-labelledby="add-question-tab">
                    <div class="card custom-border-card">
                        <h5 class="card-header">{{__('label.add_question')}}</h5>
                        <div class="card-body">
                            <form id="save_question" enctype="multipart/form-data">
                                <input type="hidden" name="id" value="">
                                <input type="hidden" name="exam_id" value="{{ $exam_id }}">
                                <div class="form-row">
                                    <div class="col-md-9">
                                        <div class="form-row">
                                            <div class="col-md-12">
                                                <div class="form-group">
                                                    <label>{{__('label.question')}}<span class="text-danger">*</span></label>
                                                    <textarea class="form-control" name="question" rows="1" placeholder="{{__('label.question_here')}}" autofocus></textarea>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>{{__('label.option_a')}}<span class="text-danger">*</span></label>
                                                    <input type="text" name="option_a" class="form-control" placeholder="{{__('label.option_a_here')}}">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>{{__('label.option_b')}}<span class="text-danger">*</span></label>
                                                    <input type="text" name="option_b" class="form-control" placeholder="{{__('label.option_b_here')}}">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>{{__('label.option_c')}}<span class="text-danger">*</span></label>
                                                    <input type="text" name="option_c" class="form-control" placeholder="{{__('label.option_c_here')}}">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>{{__('label.option_d')}}<span class="text-danger">*</span></label>
                                                    <input type="text" name="option_d" class="form-control" placeholder="{{__('label.option_d_here')}}">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label>{{__('label.correct_answer')}}<span class="text-danger">*</span></label>
                                                    <select name="correct_answer" class="form-control">
                                                        <option value="">{{__('label.select_answer')}}</option>
                                                        <option value="1">{{__('label.a')}}</option>
                                                        <option value="2">{{__('label.b')}}</option>
                                                        <option value="3">{{__('label.c')}}</option>
                                                        <option value="4">{{__('label.d')}}</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-9">
                                                <div class="form-group">
                                                    <label>{{__('label.note')}} <small>{{__('label.this_will_be_showing_with_review_section_only')}}</small></label>
                                                    <textarea class="form-control" name="note" rows="1" placeholder="{{__('label.note_here')}}"></textarea>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group ml-5">
                                            <label>{{__('label.image')}}</label>
                                            <div class="avatar-upload">
                                                <div class="avatar-edit">
                                                    <input type='file' name="image" id="imageUpload1" accept=".png, .jpg, .jpeg" />
                                                    <label for="imageUpload1" title="{{__('label.upload_file')}}"></label>
                                                </div>
                                                <div class="avatar-preview">
                                                    <img src="{{ asset('assets/imgs/upload_img.png') }}" id="imagePreview1">
                                                </div>
                                            </div>
                                            <label class="mt-3 text-gray">{{__('label.max_size_5mb')}}</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="border-top pt-3 text-right">
                                    <button type="button" class="btn btn-default mw-120" onclick="save_question()">{{__('label.save')}}</button>
                                    <input type="hidden" name="_token" value="{{ csrf_token() }}">
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="import-question" role="tabpanel" aria-labelledby="import-question-tab">
                    <div class="card custom-border-card">
                        <h5 class="card-header">{{__('label.import_question')}}</h5>
                        <div class="card-body">
                            <form id="import_question" enctype="multipart/form-data">
                                <input type="hidden" name="exam_id" value="{{ $exam_id }}">
                                <div class="form-row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>{{__('label.questions_file')}}<span class="text-danger">*</span></label>
                                            <input type="file" name="import_file" class="form-control" accept=".csv">
                                        </div>
                                    </div>
                                </div>
                                <div class="form-row mt-3">
                                    <div class="col-md-6">
                                        <button type="button" class="btn btn-default mw-120" onclick="import_question()"><i class="fa fa-upload mr-3"></i>{{__('label.upload_file')}}</button>
                                        <a class="btn btn-default ml-5" href="{{ route('admin.exam.question.export') }}"><i class="fa fa-download mr-3"></i>{{__('label.download_sample_file_here')}}</a>
                                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                                    </div>
                                </div>
                            </form>

                            <!-- Instructions -->
                            <div class="form-row mt-4">
                                <div class="col-md-12">
                                    <div class="alert alert-info">
                                        <strong class="h5">{{__('label.instructions')}} : </strong>
                                        <ul class="mt-3 h6">
                                            <li class="py-2">Only <code>.csv</code> files are allowed for Upload.</li>
                                            <li class="py-2">Image URLs should be direct and valid (e.g., <code>https://yourdomain.com/images/question1.png</code>).</li>
                                            <li class="py-2"><strong>Note</strong> and <strong>Image</strong> fields are optional — You can leave them blank if not Required.</li>
                                            <li class="py-2"><strong>Answer</strong> must be a number between <code>1</code> and <code>4</code> only — do not use letters like A, B, C, or D.</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Search && Table -->
            <div class="card custom-border-card mt-3">
                <div class="page-search mb-3">
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text" id="basic-addon1"><i class="fa-solid fa-magnifying-glass fa-xl"></i></span>
                        </div>
                        <input type="text" id="input_search" class="form-control" placeholder="{{__('label.search')}}" aria-label="Search" aria-describedby="basic-addon1">
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table table-striped text-center table-bordered" id="datatable">
                        <thead>
                            <tr>
                                <th>{{__('label.#')}}</th>
                                <th>{{__('label.image')}}</th>
                                <th>{{__('label.question')}}</th>
                                <th>{{__('label.option_a')}}</th>
                                <th>{{__('label.option_b')}}</th>
                                <th>{{__('label.option_c')}}</th>
                                <th>{{__('label.option_d')}}</th>                                
                                <th>{{__('label.status')}}</th>
                                <th>{{__('label.action')}}</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>

            <!-- Edit Model -->
            <div class="modal fade" id="EditModel" tabindex="-1" data-backdrop="static" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="exampleModalLabel">{{__('label.edit_question')}}</h5>
                            <button type="button" class="close text-dark" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <form id="update_question" enctype="multipart/form-data">
                                <input type="hidden" name="id" id="edit_id">
                                <div class="form-row">
                                    <div class="col-md-8">
                                        <div class="form-row">
                                            <div class="col-md-12">
                                                <div class="form-group">
                                                    <label>{{__('label.question')}}<span class="text-danger">*</span></label>
                                                    <textarea class="form-control" name="question" id="edit_question" rows="1" placeholder="{{__('label.question_here')}}"></textarea>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <div class="col-md-12">
                                                <div class="form-group">
                                                    <label>{{__('label.option_a')}}<span class="text-danger">*</span></label>
                                                    <input type="text" name="option_a" id="edit_option_a" class="form-control" placeholder="{{__('label.option_a_here')}}">
                                                </div>
                                            </div>
                                            <div class="col-md-12">
                                                <div class="form-group">
                                                    <label>{{__('label.option_b')}}<span class="text-danger">*</span></label>
                                                    <input type="text" name="option_b" id="edit_option_b" class="form-control" placeholder="{{__('label.option_b_here')}}">
                                                </div>
                                            </div>
                                            <div class="col-md-12">
                                                <div class="form-group">
                                                    <label>{{__('label.option_c')}}<span class="text-danger">*</span></label>
                                                    <input type="text" name="option_c" id="edit_option_c" class="form-control" placeholder="{{__('label.option_c_here')}}">
                                                </div>
                                            </div>
                                            <div class="col-md-12">
                                                <div class="form-group">
                                                    <label>{{__('label.option_d')}}<span class="text-danger">*</span></label>
                                                    <input type="text" name="option_d" id="edit_option_d" class="form-control" placeholder="{{__('label.option_d_here')}}">
                                                </div>
                                            </div>
                                            <div class="col-md-12">
                                                <div class="form-group">
                                                    <label>{{__('label.correct_answer')}}<span class="text-danger">*</span></label>
                                                    <select name="correct_answer" id="edit_correct_answer" class="form-control">
                                                        <option value="">{{__('label.select_answer')}}</option>
                                                        <option value="1">{{__('label.a')}}</option>
                                                        <option value="2">{{__('label.b')}}</option>
                                                        <option value="3">{{__('label.c')}}</option>
                                                        <option value="4">{{__('label.d')}}</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-12">
                                                <div class="form-group">
                                                    <label>{{__('label.note')}} <small>{{__('label.this_will_be_showing_with_review_section_only')}}</small></label>
                                                    <textarea class="form-control" name="note" id="edit_note" rows="1" placeholder="{{__('label.note_here')}}"></textarea>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-group ml-5">
                                            <label>{{__('label.image')}}<span class="text-danger">*</span></label>
                                            <div class="avatar-upload">
                                                <div class="avatar-edit">
                                                    <input type='file' name="image" id="imageUpload2" accept=".png, .jpg, .jpeg" />
                                                    <label for="imageUpload2" title="{{__('label.upload_file')}}"></label>
                                                </div>
                                                <div class="avatar-preview">
                                                    <img src="" id="imagePreview2">
                                                </div>
                                            </div>
                                            <label class="mt-3 text-gray">{{__('label.max_size_5mb')}}</label>
                                            <input type="hidden" name="old_image" id="edit_old_image">
                                        </div>
                                    </div>
                                </div>
                                <div class="border-top pt-3 text-right">
                                    <button type="button" class="btn btn-default mw-120" onclick="update_question()">{{__('label.update')}}</button>
                                    <button type="button" class="btn btn-cancel mw-120" data-dismiss="modal">{{__('label.close')}}</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('pagescript')
    <script>
        function save_question(){

			var Demo_Mode = '<?php echo Demo_Mode(); ?>';
            if(Demo_Mode == 1){

				$("#dvloader").show();
				var formData = new FormData($("#save_question")[0]);
				$.ajax({
					type:'POST',
					url:'{{ route("admin.exam.question.save") }}',
					data:formData,
					cache:false,
					contentType: false,
					processData: false,
					success:function(resp){
						$("#dvloader").hide();
						get_responce_message(resp, 'save_question', '{{ route("admin.exam.question.index", [$exam_id]) }}');
					},
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        $("#dvloader").hide();
                        toastr.error(errorThrown, textStatus);
                    }
				});
			} else {
                showError();
            }
		}

        $(document).ready(function() {
            var table = $('#datatable').DataTable({
                ...dataTableDefaults,
                ajax:
                    {
                    url: "{{ route('admin.exam.question.index', [$exam_id]) }}",
                    data: function(d){
                        d.input_search = $('#input_search').val();
                    },
                },
                columns: [
                    { data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false },
                    {
                        data: 'image',
                        name: 'image',
                        orderable: false,
                        searchable: false,
                        render: function(data, type, full, meta) {
                            return "<a href='" + data + "' target='_blank'><img src='" + data + "' class='img-thumbnail' style='height:60px; width:60px'></a>";
                        },
                    },
                    {
                        data: 'question',
                        name: 'question',
                        width: '25%',
                        render: function(data) {
                            return data ? '<div style="text-align: left; font-size: 14px;">' + data + '</div>' : "-";
                        }
                    },
                    {
                        data: 'option_a',
                        name: 'option_a',
                        width: '10%',
                        orderable: false,
                        searchable: false,
                        render: function(data, type, row) {
                            const correct = parseInt(row.correct_answer);
                            const isCorrect = correct === 1 ? 'class="green-color font-weight-bold"' : '';
                            return `<div style="text-align: left;" ${isCorrect}>${row.option_a || '-'}</div>`;
                        }
                    },
                    {
                        data: 'option_b',
                        name: 'option_b',
                        width: '10%',
                        orderable: false,
                        searchable: false,
                        render: function(data, type, row) {
                            const correct = parseInt(row.correct_answer);
                            const isCorrect = correct === 2 ? 'class="green-color font-weight-bold"' : '';
                            return `<div style="text-align: left;" ${isCorrect}>${row.option_b || '-'}</div>`;
                        }
                    },
                    {
                        data: 'option_c',
                        name: 'option_c',
                        width: '10%',
                        orderable: false,
                        searchable: false,
                        render: function(data, type, row) {
                            const correct = parseInt(row.correct_answer);
                            const isCorrect = correct === 3 ? 'class="green-color font-weight-bold"' : '';
                            return `<div style="text-align: left;" ${isCorrect}>${row.option_c || '-'}</div>`;
                        }
                    },
                    {
                        data: 'option_d',
                        name: 'option_d',
                        width: '10%',
                        orderable: false,
                        searchable: false,
                        render: function(data, type, row) {
                            const correct = parseInt(row.correct_answer);
                            const isCorrect = correct === 4 ? 'class="green-color font-weight-bold"' : '';
                            return `<div style="text-align: left;" ${isCorrect}>${row.option_d || '-'}</div>`;
                        }
                    },
                    {
                        data: 'status',
                        name: 'status',
                        orderable: false,
                        searchable: false
                    },
                    {
                        data: 'action',
                        name: 'action',
                        orderable: false,
                        searchable: false
                    },
                ]
            });

            $('#input_search').keyup(function(){
                table.draw();
            });
        });

        $(document).on("click", ".edit_exam_question", function() {
            var id = $(this).data('id');
            var question = $(this).data('question');
            var image = $(this).data('image');
            var option_a = $(this).data('option_a');
            var option_b = $(this).data('option_b');
            var option_c = $(this).data('option_c');
            var option_d = $(this).data('option_d');
            var correct_answer = $(this).data('correct_answer');
            var note = $(this).data('note');

            $(".modal-body #edit_id").val(id);
            $(".modal-body #edit_question").val(question);
            $(".modal-body #imagePreview2").attr("src", image);
            $(".modal-body #edit_old_image").val(image);
            $(".modal-body #edit_option_a").val(option_a);
            $(".modal-body #edit_option_b").val(option_b);
            $(".modal-body #edit_option_c").val(option_c);
            $(".modal-body #edit_option_d").val(option_d);
            $(".modal-body #edit_correct_answer").val(correct_answer);
            $(".modal-body #edit_note").val(note);
        });
		function update_question(){

			var Demo_Mode = '<?php echo Demo_Mode(); ?>';
            if(Demo_Mode == 1){

                $("#dvloader").show();
                var formData = new FormData($("#update_question")[0]);
                
                var Edit_Id = $("#edit_id").val();
                var url = '{{ route("admin.exam.question.update", ":id") }}';
                    url = url.replace(':id', Edit_Id);

                $.ajax({
                    type: 'POST',
                    url: url,
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
					success:function(resp){
						$("#dvloader").hide();
                        get_responce_message(resp, 'update_question', '{{ route("admin.exam.question.index", [$exam_id]) }}');
					},
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        $("#dvloader").hide();
                        toastr.error(errorThrown, textStatus);
                    }
				});
			} else {
                showError();
            }
		}

        function change_status(id) {

            var Demo_Mode = '<?php echo Demo_Mode(); ?>';
            if(Demo_Mode == 1){

                $("#dvloader").show();
                var url = `{{ route('admin.exam.question.show', '') }}/${id}`;

                $.ajax({
                    type: "GET",
                    url: url,
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    success: function(resp) {
                        $("#dvloader").hide();

                        if (resp.status == 200) {
                            if (resp.status_code == 1) {
                                $('#' + id).text('{{__("label.show")}}').removeClass('hide-btn').addClass('show-btn');
                            } else {
                                $('#' + id).text('{{__("label.hide")}}').removeClass('show-btn').addClass('hide-btn');
                            }
                            toastr.success(resp.success);
                        } else {
                            toastr.error(resp.errors);
                        }
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        $("#dvloader").hide();
                        toastr.error(errorThrown, textStatus);
                    }
                });
            } else {
                showError();
            }
        };

        function import_question(){

			var Demo_Mode = '<?php echo Demo_Mode(); ?>';
            if(Demo_Mode == 1){

				$("#dvloader").show();
				var formData = new FormData($("#import_question")[0]);
				$.ajax({
					type:'POST',
					url:'{{ route("admin.exam.question.import.save") }}',
					data:formData,
					cache:false,
					contentType: false,
					processData: false,
					success:function(resp){
						$("#dvloader").hide();
						get_responce_message(resp, 'import_question', '{{ route("admin.exam.question.index", [$exam_id]) }}');
					},
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        $("#dvloader").hide();
                        toastr.error(errorThrown, textStatus);
                    }
				});
			} else {
                showError();
            }
		}
    </script>
@endsection