<!-- DataTables -->
<link rel="stylesheet" href="<?php echo $this->config->item('admin_assets_folder'); ?>plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="<?php echo $this->config->item('admin_assets_folder'); ?>plugins/datatables-responsive/css/responsive.bootstrap4.min.css">
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">

	<!-- Content Header (Page header) -->
	<section class="content-header">
		<div class="container-fluid">
			<div class="row mb-2">
				<div class="col-sm-6">
					<h1><?php echo $meta_title; ?></h1>
				</div>
				<div class="col-sm-6">
					<ol class="breadcrumb float-sm-right">
						<li class="breadcrumb-item"><a href="<?php echo base_url().$this->config->item('admin_folder').'/'.'dashboard'; ?>">Home</a></li>
						<li class="breadcrumb-item active"><?php echo $meta_title; ?></li>
					</ol>
				</div>
			</div>
		</div><!-- /.container-fluid -->
	</section>

	<section class="content">
		<div class="container-fluid">
			<div class="row">
				<div class="col-12">
					<div class="card">
						<div class="card-header">
							<h3 class="card-title"><?php echo $meta_title; ?></h3>

							<div class="card-tools">
								<form action="<?php echo base_url().$this->config->item('admin_folder').'/media/export_all_images'; ?>" method="POST" name="export_images_data" id="export_images_data" class="form">
                                    <input type="hidden" name="type" value="export_images" />
                                </form>
                                <button class="btn btn-success pull-right" style="display: none;" id="export_images">Export Media</button>

                                <button class="btn btn-danger pull-right mr-3" style="display: none;" data-toggle="modal" data-target="#import_media_zip">Import Media</button>

							</div>
						</div>
						<!-- /.card-header -->

						<div class="card-body table-responsive">

    							<?php
                                    $this->load->view($this->config->item('admin_folder')."/media/media_add");
                                ?>

							<table class="table table-hover table-bordered text-wrap" id="<?php echo $page_name; ?>">
								<thead>
									<tr>
										<th>#</th>
                                        <th>Media</th>
                                        <th>URL</th>
                                        <th>Caption</th>
                                        <th>Title</th>
                                        <th>ALT</th>
                                        <th>Actions</th>
									</tr>
								</thead>
								<tbody>

								</tbody>
							</table>
						</div>
						<!-- /.card-body -->
					</div>
					<!-- /.card -->
				</div>
			</div>
		</div>
	</section>

</div>
<!-- /.content-wrapper -->


<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <form name="form_submit" action="javascript:;" method="POST" id="form_submit" data-parsley-validate="">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Edit media</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    
                    <input type="hidden" name="id" id="id" value="">

                    <div class="form-group">
                        <label class="col-form-label" for="caption">Caption</label>
                        <input type="text" class="form-control" id="caption" name="caption" data-parsley-errors-container="#caption_error" placeholder="Caption" />
                        <p class="error"><small id="caption_error"></small></p>
                    </div>

                    <div class="form-group">
                        <label class="col-form-label" for="title">Title tag</label>
                        <input type="text" class="form-control" id="title" name="title" data-parsley-errors-container="#caption_error" placeholder="Title tag" />
                        <p class="error"><small id="title_error"></small></p>
                    </div>

                    <div class="form-group">
                        <label class="col-form-label" for="alt">ALT tag</label>
                        <input type="text" class="form-control" id="alt" name="alt" data-parsley-errors-container="#caption_error" placeholder="ALT tag" />
                        <p class="error"><small id="alt_error"></small></p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Save</button>
                </div>
            </div>
        </div>
    </form>
</div>

<!-- DataTables -->
<script src="<?php echo $this->config->item('admin_assets_folder'); ?>plugins/datatables/jquery.dataTables.min.js"></script>
<script src="<?php echo $this->config->item('admin_assets_folder'); ?>plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="<?php echo $this->config->item('admin_assets_folder'); ?>plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
<script src="<?php echo $this->config->item('admin_assets_folder'); ?>plugins/datatables-responsive/js/responsive.bootstrap4.min.js"></script>

<script>

    $('#exampleModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget) // Button that triggered the modal
        var id = button.data('id') // Extract info from data-* attributes
        var caption = button.data('caption') // Extract info from data-* attributes
        var title = button.data('title') // Extract info from data-* attributes
        var alt = button.data('alt') // Extract info from data-* attributes
        // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
        // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
        var modal = $(this);
        modal.find('.modal-body input#id').val(id);
        modal.find('.modal-body input#caption').val(caption);
        modal.find('.modal-body input#title').val(title);
        modal.find('.modal-body input#alt').val(alt);
    });

	var mediadatatable =$('#<?php echo $page_name; ?>').DataTable({
      	"paging": true,
      	"lengthChange": false,
      	"searching": true,
      	"ordering": false,
      	"info": true,
      	"autoWidth": false,
		"pageLength": 10,
		"processing": true, //Feature control the processing indicator.
		"serverSide": true,
      	"columnDefs": [
		   { "orderable": false, "width": 150, "targets": [0,1,2,3,4,5,6] }
		],
        fixedColumns: true,
		"ajax": {
            url : "<?php echo base_url().$this->config->item('admin_folder').'/media/ajax_load_data'; ?>",
            type : 'POST',
            global : false
        },
        'responsive': true
    });
</script>


<?php
    $this->load->view($this->config->item('admin_folder')."/media/media_assets");
?>


<div class="modal fade" id="import_media_zip" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Upload new images</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body p-4">

                <ul class="list-group">
                    <li class="list-group-item">Put all images in a folder</li>
                    <li class="list-group-item">Zip the folder</li>
                    <li class="list-group-item">Folder has to be under 5 MB</li>
                </ul>

                <form enctype='multipart/form-data' id="import_media_zip_data" name="import_media_zip_data" class="mt-4" action="javascript:;" method="post">
                    <div class="row">
                        <div class="col-md-6">
                            <input type="file" style="" name="file" id="file" accept=".zip">
                        </div>
                        <div class="col-md-6">
                            <input type="submit" id="submit" name="submit" class="btn btn-info" onclick="import_media_zip('<?php echo base_url().$this->config->item("admin_folder"); ?>/media/import_zip_images');" value="Upload" />
                        </div>
                        <div class="col-md-12">
                            <div id="media_upload_error" class="mt-4 text-danger"></div>
                        </div>
                    </div>
                </form>

            </div>
        </div>
    </div>
</div>

<input type="hidden" id="media_index" value="1">

<script type="text/javascript">
    $("#export_images").on("click", function(){
        var form = $('#export_images_data');
        form.submit();
    });

    function import_media_zip(uri){
        var formData = new FormData($("#import_media_zip_data")[0]);
        $("#media_upload_error").html("");
        $.ajax({
            type: "POST",
            dataType: "json",
            url: uri,
            data: formData,
            //async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function(response) {
                var msg=response["message"];
                if(response["status"] == true){

                    setTimeout(function() {
                        toastr.options = {
                            "closeButton": true,
                            "progressBar": false,
                            "showMethod": "fadeIn",
                            "hideMethod": "fadeOut",
                            "timeOut": 4000,
                            "preventDuplicates": true,
                            "newestOnTop": true,
                            "showEasing": "swing",
                            "hideEasing": "linear",
                            "positionClass": "toast-bottom-right"
                        };
                        toastr.success(msg, 'Success');
                    }, 200);

                    window.location.href = '<?php base_url().$this->config->item("admin_folder").'/media/index'; ?>';
                }else{
                    $("#media_upload_error").html(msg);
                }
            },
            error: function() {
               $("#media_upload_error").html("Failed to upload images");

            }
        });
    }


    $('#form_submit').parsley().on('field:validated', function() {
        var ok = $('.parsley-error').length === 0;
        $('.bs-callout-info').toggleClass('hidden', !ok);
        $('.bs-callout-warning').toggleClass('hidden', ok);
    })
    .on('form:submit', function() {
        var formData = new FormData($("#form_submit")[0]);
        var base_url = '<?php echo base_url().$this->config->item('admin_folder'); ?>';
        var id = $("#id").val();
        var url = base_url+"/media/edit/"+id;

        $.ajax({
            type: "POST",
            dataType: "json",
            url: url,
            data: formData,
            //async: false,
            global : false,
            cache: false,
            contentType: false,
            processData: false,
            beforeSend:function(){
                $("#submit_btn").addClass("disabled");
                $("#submit_btn").attr("disabled");
                $("#submit_btn").html("Saving...");
            },
            success: function(result) {

                $("#submit_btn").removeClass("disabled");
                $("#submit_btn").removeAttr("disabled");
                $("#submit_btn").html("Save");

                if(result["status"] === false){
                    bootbox.alert("<p style='color:red'>"+result['message']+"</p>", function() {});
                }else{

                    bootbox.alert(result['message'], function() {
                        mediadatatable.draw();
                        $('#exampleModal').modal('toggle');
                    });

                }
            },
            error: function() {
                $("#submit_btn").removeClass("disabled");
                $("#submit_btn").removeAttr("disabled");
                $("#submit_btn").html("Save");

                bootbox.alert("<p style='color:red'>Failed to save the details</p>", function() {});
            }
        });
    });
</script>