@extends('layouts.app')
@section('title', 'Page Management')
@section('content')

<!-- Content Header (Page header) -->
<section class="content-header">
  <h1>
    Manajemen Halaman
    <small>Listing halaman website</small>
  </h1>
  <ol class="breadcrumb">
    <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
    <li class="active">Page Management</li>
  </ol>
</section>

<!-- Main content -->
<section class="content">
	<!-- Info boxes -->
	<div class="row">
		<div class="col-md-12">
			<div class="box">
				<div class="box-header with-border">
					<h3 class="box-title"><i class="fa fa-list"></i> Page Management</h3>
				</div>
				<div class="box-body">
					<a href="{{route('pages.create')}}" class="btn btn-sm btn-success modal-show" title="Form Tambah Halaman"><i class="fa fa-plus"> Tambah</i></a>
          <hr>
          <div class="table-responsive">
  					<table id="datatables" class="table table-striped table-bordered table-hover">
  						<thead>
  							<tr>
                                <th>No</th>
                                <th>Action</th>
  								<th>Nama Halaman</th>
  								<th>Slug</th>
  								<th>Status</th>
  								<th>Tanggal Dibuat</th>
  								<th>Tanggal Update</th>
  							</tr>
  						</thead>
  						<tbody>
  						</tbody>
  					</table>
          </div>
				</div>
			</div>
		</div>
	</div>
</section>

@endsection

@push('scripts')
<script type="text/javascript">
$(document).ready(function(){
	var dataTable = $('#datatables').DataTable({
        "stateSave": true,
        "processing" : true,
        "serverSide" : true,
        "searching" : true,
        "ajax" : {
        "url": "{{ route('pages.json') }}",
        "dataType": "json",
        "type": "GET",
        "data": {
            _token: "{{csrf_token()}}"
        }
        },
        "columns": [
            { data: 'DT_RowIndex', name: 'DT_RowIndex' },
            { "data": "options" },
            { "data": "name" },
            { "data": "slug" },
            { "data": "status" },
            { "data": "created_at" },
            { "data": "updated_at" }
        ],
        "columnDefs": [
            { "width": "2%", "targets": 0 },
            { "width": "15%", "targets": 1 },
        ],
    });

    $('body').on('click', '.modal-show', function (event) {
        event.preventDefault();
        var me = $(this),
            url = me.attr('href'),
            title = me.attr('title');

        $('#modal-title').text(title);
        $('#modal-btn-save').removeClass('hide').text(me.hasClass('edit') ? 'Ubah' : 'Simpan');

        $.ajax({
        url: url,
        dataType: 'html',
        success: function(response){
            $('#modal-body').html(response);
        }
        });

        $('#modal').modal('show');
    });

    $('body').on('click', '.btn-komentar', function (event) {
        event.preventDefault();
        var me = $(this),
            url = me.attr('href'),
            title = me.attr('title');

        $('#modal-title').text(title);
        $('#modal-btn-save').removeClass('hide').text('Simpan');

        $.ajax({
        url: url,
        dataType: 'html',
        success: function(response){
            $('#modal-body').html(response);
        }
        });

        $('#modal').modal('show');
    });

    $('body').on('click', '.btn-show', function (event) {
        event.preventDefault();
        var me = $(this),
            url = me.attr('href'),
            title = me.attr('title');

        $('#modal-title').text(title);
        $('#modal-btn-save').addClass('hide');

        $.ajax({
        url: url,
        dataType: 'html',
        success: function(response){
            $('#modal-body').html(response);
        }
        });

        $('#modal').modal('show');
    });

    $('body').on('click', '#modal-btn-save', function(e){
        e.preventDefault();
        $('.preloader').fadeIn();
        clearTimeout(timeout);

        for ( instance in CKEDITOR.instances ) {
            CKEDITOR.instances[instance].updateElement();
        }
        var form = $('#modal-body form'),
            url = form.attr('action'),
            method = $('input[name=_method]').val() == undefined ? 'POST' : 'PUT';

        form.find('.help-block').remove();
        form.find('.form-group').removeClass('has-error');
        $.ajax({
            url: url,
            method: method,
            dataType: "JSON",
            data: form.serialize(),
            success: function(response){
                timeout = setTimeout(loaded, 1000);
                if(response.code === 200){
                    form.trigger('reset');
                    $('#modal').modal('hide');
                    $('#datatables').DataTable().ajax.reload();

                    swal({
                        type: 'success',
                        icon: 'success',
                        title: 'Berhasil!',
                        text: response.msg
                    });
                }else{
                    swal({
                        type: 'error',
                        icon: 'error',
                        title: 'Gagal!',
                        text: response.msg
                    })
                }
            },
            error: function(xhr){
                timeout = setTimeout(loaded, 1000);
                var res = xhr.responseJSON;
                if($.isEmptyObject(res) == false) {
                $.each(res.errors, function (key, value) {
                    $('#' + key)
                        .closest('.form-group')
                        .addClass('has-error')
                        .append('<span class="help-block"><strong>' + value + '</strong></span>');
                });
                }
            }
        });
    });

    $('body').on('change', '#status', function(e){
        e.preventDefault();

        var id = $(this).attr('data-id');

        swal({
            title: "Anda Yakin?",
            text: "Anda yakin untuk mengganti status halaman ini ?",
            icon: "warning",
            buttons: [
                'Tidak, batalkan!',
                'Ya, ganti!'
            ],
            dangerMode: true,
        }).then(function(isConfirm) {
            if (isConfirm) {
                $('.preloader').fadeIn();
                clearTimeout(timeout);
                $.ajax({
                    type: "POST", // Method pengiriman data bisa dengan GET atau POST
                    url: "{{ route('pages.update_status') }}", // Isi dengan url/path file php yang dituju
                    data: {
                        _token: "{{csrf_token()}}",
                        id: id,
                    }, // data yang akan dikirim ke file yang dituju
                    dataType: "json",
                    success: function(response){
                        timeout = setTimeout(loaded, 1000);
                        if(response.code === 200){
                            $('#datatables').DataTable().ajax.reload();
                            swal({
                                title: 'Berhasil!',
                                icon: 'success',
                                text: response.msg,
                            });
                        }else{
                            swal({
                                title: 'Gagal!',
                                icon: 'error',
                                text: response.msg,
                            });
                        }
                    },
                    error: function(xhr){
                        timeout = setTimeout(loaded, 1000);
                        swal({
                            title: 'Gagal!',
                            icon: 'error',
                            text: xhr.statusText,
                        });
                    }
                });
            } else {
                swal("Dibatalkan", "Status batal diupdate! :)", "error");
            }
        });
    });

    $('body').on('change', '.uploadfoto', function(e){
        e.preventDefault();
        $('.preloader').fadeIn();
        clearTimeout(timeout);

        var id = $(this).attr('data-id');
        var fileSelect = document.getElementById($(this).attr('id'));
        var token = $('#_token').val();
        var files = fileSelect.files[0];
        var formData = new FormData();
        formData.append('picture', files);
        formData.append('id', id);
        formData.append('_token', token);
        $.ajax({
            url: "{{route('pages.update_foto')}}",
            method: "POST",
            dataType: "JSON",
            data: formData,
            processData: false,
            contentType: false,
            success: function(response){
                timeout = setTimeout(loaded, 1000);
                if(response.code === 200){
                    $('#modal').modal('hide');
                    $('#datatables').DataTable().ajax.reload();
                    swal({
                        type: 'success',
                        icon: 'success',
                        title: 'Berhasil!',
                        text: response.msg
                    });
                }else{
                    swal({
                        type: 'error',
                        icon: 'error',
                        title: 'Gagal!',
                        text: response.msg
                    });
                }
            },
            error: function(xhr, status, error){
                timeout = setTimeout(loaded, 1000);
                $('#modal').modal('hide');
                $('#datatables').DataTable().ajax.reload();
                data = JSON.parse(xhr.responseText);
                $.each(data, function(key, item){
                    swal({
                        type: 'error',
                        icon: 'error',
                        title: 'Gagal!',
                        text: 'Gagal upload foto, '+item.picture+'!'
                    });
                });
            }
        })
    });

    $('body').on('click', '#hapusGambar', function(e){
        e.preventDefault();
        var id = $(this).attr('data-id');
        swal({
            title: "Anda Yakin?",
            text: "Anda yakin untuk menghapus gambar pages ini ?",
            icon: "warning",
            buttons: [
                'Tidak, batalkan!',
                'Ya, hapus!'
            ],
            dangerMode: true,
        }).then(function(isConfirm) {
            if(isConfirm){
                $('.preloader').fadeIn();
                clearTimeout(timeout);
                $.ajax({
                    url: "{{ route('pages.hapusGambar') }}",
                    method: "POST",
                    dataType: "JSON",
                    data: {
                    _token: "{{csrf_token()}}",
                    id: id
                    },
                    success: function(response){
                        timeout = setTimeout(loaded, 1000);
                        if(response.code === 200){
                            $('#modal').modal('hide');
                            $('#datatables').DataTable().ajax.reload();
                            swal({
                                type: 'success',
                                icon: 'success',
                                title: 'Berhasil!',
                                text: response.msg,
                            });
                        }else{
                            swal({
                                type: 'error',
                                icon: 'error',
                                title: 'Gagal!',
                                text: response.msg,
                            });
                        }
                    },
                    error: function(response){
                        timeout = setTimeout(loaded, 1000);
                        $('#modal').modal('hide');
                        $('#datatables').DataTable().ajax.reload();
                        swal({
                            type: 'error',
                            icon: 'error',
                            title: 'Gagal!',
                            text: response.msg,
                        });
                    }
                });
            } else {
                swal("Dibatalkan", "Proses dibatalkan! :)", "error");
            }
        });
    });

    $('body').on('click', '#destroy', function(e){
        e.preventDefault();
        var id = $(this).attr('data-id');
        swal({
            title: "Anda Yakin?",
            text: "Anda yakin untuk menghapus halaman ini ?",
            icon: "warning",
            buttons: [
                'Tidak, batalkan!',
                'Ya, hapus!'
            ],
            dangerMode: true,
        }).then(function(isConfirm) {
            if (isConfirm) {
                $('.preloader').fadeIn();
                clearTimeout(timeout);
                $.ajax({
                    type: "POST", // Method pengiriman data bisa dengan GET atau POST
                    url: "{{ route('pages.remove') }}", // Isi dengan url/path file php yang dituju
                    data: {
                        _token: "{{csrf_token()}}",
                        id: id,
                    }, // data yang akan dikirim ke file yang dituju
                    dataType: "json",
                    success: function(response){
                        timeout = setTimeout(loaded, 1000);
                        if(response.code === 200){
                            $('#datatables').DataTable().ajax.reload();
                            swal({
                                title: 'Berhasil!',
                                icon: 'success',
                                text: response.msg
                            });
                        }else{
                            swal({
                                title: 'Gagal!',
                                icon: 'error',
                                text: response.msg
                            });
                        }
                    },
                    error: function(response){
                        timeout = setTimeout(loaded, 1000);
                        swal({
                            title: 'Gagal!',
                            icon: 'error',
                            text: response.msg
                        });
                    }
                });
            } else {
                swal("Dibatalkan", "Halaman batal dihapus! :)", "error");
            }
        });
    });
});
</script>
@endpush
