<!-- daterange picker -->
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<style type="text/css">
	.bootbox-confirm .modal-header{display: none;}
</style>

<!-- 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"><a href="<?php echo base_url().$this->config->item('admin_folder').'/'.'products/index'; ?>">Products</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">
					<form name="form_submit" action="javascript:;" method="POST" id="form_submit" data-parsley-validate="">
                        <input type="hidden" name="id" id="id" value="<?php echo isset($products->id) && !empty($products->id) ? $products->id : ''; ?>">
                        <input type="hidden" name="display_order" id="display_order" value="<?php echo isset($products->display_order) && !empty($products->display_order) ? $products->display_order : ''; ?>">

                        <div class="row">
							<div class="col-sm-8">
								<div class="card">
									<div class="card-header">
										Basic details
									</div>
									<div class="card-body">

										<div class="form-group">
											<label class="col-form-label" for="title">Product Title<span class="required">*</span></label>
									        <input type="text" class="form-control" id="title" name="title" required value="<?php echo isset($products->title) && $products->title != '' ? $products->title : ''; ?>" data-parsley-errors-container="#title_error" placeholder="" />
									        <p class="error"><small id="title_error"></small></p>
										</div>


										<div class="form-group">
											<label class="col-form-label" for="slug">Slug<span class="required">*</span></label>
									        <input type="text" class="form-control" id="slug" name="slug" required value="<?php echo isset($products->slug) && $products->slug != '' ? $products->slug : ''; ?>" data-parsley-errors-container="#slug_error" placeholder="" />
									        <p class="error"><small id="slug_error"></small></p>
										</div>



									</div>
								</div>

							</div>

							<div class="col-sm-4">

								<div class="card">
									<div class="card-header">
										Status
									</div>
									<div class="card-body">
										<div class="form-group">
											<label class="col-form-label" for="is_active">Status<span class="required">*</span></label>
											<select class="form-control" name="is_active" required data-parsley-errors-container="#is_active_error">
												<option value="">----Select----</option>
												<option value="1" <?php echo isset($products->is_active) && $products->is_active == 1 ? "selected" : ""; ?>>Active</option>
												<option value="0" <?php echo isset($products->is_active) && $products->is_active == 0 ? "selected" : ""; ?>>In-active</option>
											</select>
											<p class="error"><small id="is_active_error"></small></p>
										</div>

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

							
							
						</div>

                        <div class="form-group row margin-top text-center">
                            <div class="col-12">
                                <button class="btn btn-primary" id="submit_btn" type="submit">Save</button>
                            </div>
                        </div>
                    </form>
					<!-- /.card -->

					<?php
						if(isset($products->id) && !empty($products->id)){
					?>
							<div class="row">
								<div class="col-sm-12">

									<div class="card">
										<div class="card-header">
											Documents

											<div class="card-tools">

												<button type="button" data-toggle="modal" class="btn btn-primary" data-target="#add_folder_modal">Add New Folder</button>

												<button type="button" class="btn btn-warning md-trigger" id="add_new_document" data-value="hide">Add New Document</button>
											</div>
										</div>
										<div class="card-body">
											<?php
												$this->load->view($this->config->item('admin_folder').'/products/upload_files');
											?>

											<div id="fileSystem"></div>

										</div>
									</div>
								</div>
							</div>
					<?php
						}
					?>

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

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

<input type="hidden" class="parent_id" id="parent_id" value="<?php echo isset($_GET['doc_ref']) && $_GET['doc_ref'] != '' ? $_GET['doc_ref'] : '' ?>" />

<div class="modal text-left fade" id="add_folder_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel6" aria-hidden="true">
	<div class="modal-dialog" role="document">
		<form action="javascript:;" method="POST" name="add_folder_form" id="add_folder_form">
			<div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title">Add new folder</h5>
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">×</span>
					</button>
				</div>
				<div class="modal-body">

					<div class="form-body">
						<div class="row">

							<div class="col-sm-12 folder_breadcrumb"></div>

							<div class="col-md-12">
								<div class="form-group">
									<label for="folder_name">Folder name</label>
									<input type="text" class="form-control" id="add_folder_name"  name="folder_name" required />
								</div>
							</div>

							<div class="col-md-12">
								<div class="form-group">
									<label for="folder_name">Has Lock</label>
									<select class="form-control" id="add_has_lock"  name="has_lock">
										<option value="0">No</option>
										<option value="1">Yes</option>
									</select>
								</div>
							</div>

						</div>
					</div>

				</div>

				<div class="modal-footer">
					<button type="submit" class="btn btn-danger">Submit</button>
					<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
				</div>
			</div>
		</form>
	</div>
</div>

<div class="modal text-left fade" id="edit_folder_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel6" aria-hidden="true">
	<div class="modal-dialog" role="document">
		<form action="javascript:;" method="POST" name="edit_folder_form" id="edit_folder_form">
			<div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title">Edit folder name</h5>
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">×</span>
					</button>
				</div>
				<div class="modal-body">

					<div class="form-body">
						<div class="row">

							<div class="col-sm-12 folder_breadcrumb"></div>

							<div class="col-md-12">
								<div class="form-group">
									<label for="edit_folder_name">Folder name</label>
									<input type="text" class="form-control" id="edit_folder_name"  name="edit_folder_name" required />
									<input type="hidden" name="folder_id" id="folder_id" value="" />
								</div>
							</div>

							<div class="col-md-12">
								<div class="form-group">
									<label for="folder_name">Has Lock</label>
									<select class="form-control" id="edit_has_lock"  name="edit_has_lock">
										<option value="0">No</option>
										<option value="1">Yes</option>
									</select>
								</div>
							</div>

						</div>
					</div>

				</div>

				<div class="modal-footer">
					<button type="submit" class="btn btn-danger">Update</button>
					<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
				</div>
			</div>
		</form>
	</div>
</div>

<div class="modal text-left fade" id="edit_file_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel6" aria-hidden="true">
	<div class="modal-dialog" role="document">
		<form action="javascript:;" method="POST" name="edit_file_form" id="edit_file_form">
			<div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title">Edit file</h5>
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">×</span>
					</button>
				</div>
				<div class="modal-body">

					<div class="form-body">
						<div class="row">

							<div class="col-sm-12 folder_breadcrumb"></div>

							<div class="col-md-12">
								<div class="form-group">
									<label for="edit_file_name">File name</label>
									<div class="form-control" id="edit_file_name"></div>
									<input type="hidden" name="folder_id" id="file_id" value="" />
								</div>
							</div>

							<div class="col-md-12">
								<div class="form-group">
									<label for="edit_file_has_lock">Has Lock</label>
									<select class="form-control" id="edit_file_has_lock"  name="edit_has_lock">
										<option value="0">No</option>
										<option value="1">Yes</option>
									</select>
								</div>
							</div>

						</div>
					</div>

				</div>

				<div class="modal-footer">
					<button type="submit" class="btn btn-danger">Update</button>
					<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
				</div>
			</div>
		</form>
	</div>
</div>



<script type="text/javascript">

	$('#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+"/products/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() {
                        location.href = result['redirect_url'];
                        
                   	});

                }
            },
            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>

<script>
	var data = <?php echo json_encode(array("doc_ref" => '')); ?>;
	var p_id = '<?php echo isset($products->id) && !empty($products->id) ? $products->id : ""; ?>';

	if(p_id){
		loadFolderContent();
	}

    function loadFolderContent() {

		var base_url = '<?php echo base_url().$this->config->item('admin_folder'); ?>';
        var id = $("#id").val();
        var url = base_url+"/products/list_contents";

        var parent_id = $("#parent_id").val();

        data['doc_ref'] = parent_id;
        window.history.pushState("", "", modifyUrl(data));

        $.ajax({
            type: "POST",
            dataType: "json",
            url: url,
            data: {
            	product_id: id,
            	parent_id: parent_id,
            },
            //async: false,
            global : false,
            beforeSend:function(){

            },
            success: function(result) {

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

                   	$(".sortable" ).sortable({
                   		update: function(event, ui) {
							save_sorting()
						}
                   	});
					$(".sortable" ).disableSelection();
                   	
                }
            },
            error: function() {
		        bootbox.alert("<p style='color:red'>Failed to load the documents.</p>", function() {});
            }
        });

    }

    function modifyUrl(data){
        var str = '';
        var i = 0;
        $.each(data, function(a, b) {
            var and = (i>0) ? '&' : '';
            if(a != ''){
                str += and+a+'='+b;
                i++;
            }
        });
        return  window.location.protocol+'//'+window.location.hostname+window.location.pathname+'?'+str
    }


	//-------------------------------------Add Folder-----------------------------------------------

    $('#add_folder_form').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($("#add_folder_form")[0]);
        var base_url = '<?php echo base_url().$this->config->item('admin_folder'); ?>';
        var url = base_url+"/products/add_folder/";

        var id = $("#id").val();
        var parent_id = $("#parent_id").val();

        formData.append("product_id", id);
        formData.append("parent_id", parent_id);

        $.ajax({
            type: "POST",
            dataType: "json",
            url: url,
            data: formData,
            //async: false,
            global : false,
            cache: false,
            contentType: false,
            processData: false,
            beforeSend:function(){
            },
            success: function(result) {

            	$("#add_folder_form")[0].reset();
            	

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

		        bootbox.alert("<p style='color:red'>Failed to create folder</p>", function() {});
            }
        });
    });

    $(document).on("click", ".click-folder", function(){
    	var parent_id = $(this).attr("data-id");
    	$(".parent_id").val(parent_id);
    	loadFolderContent();
    });

    $(document).on("click", ".breadcrumb-folder", function(){
    	var parent_id = $(this).attr("data-id");
    	$(".parent_id").val(parent_id);
    	loadFolderContent();
    });

    //-------------------------------------------------------------------------------------------------------

    $(document).on("click", ".edit-folder", function(){
    	var folder_name = $(this).attr("data-folder-name");
    	var has_locak = $(this).attr("data-has-lock");
    	var folder_id = $(this).attr("data-id");

    	$("#edit_folder_name").val(folder_name);
    	$("#folder_id").val(folder_id);

    	$('#edit_has_lock option[value="'+has_locak+'"]').prop('selected', true);

    	$('#edit_folder_modal').modal('toggle');
    });

    $('#edit_folder_form').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($("#edit_folder_form")[0]);
        var base_url = '<?php echo base_url().$this->config->item('admin_folder'); ?>';
        var url = base_url+"/products/edit_folder/";

        var id = $("#id").val();
        var parent_id = $("#parent_id").val();

        formData.append("product_id", id);
        formData.append("parent_id", parent_id);

        $.ajax({
            type: "POST",
            dataType: "json",
            url: url,
            data: formData,
            //async: false,
            global : false,
            cache: false,
            contentType: false,
            processData: false,
            beforeSend:function(){
            },
            success: function(result) {

            	if(result["status"] === false){
           			bootbox.alert("<p style='color:red'>"+result['message']+"</p>", function() {});
            	}else{
            		$('#edit_folder_modal').modal('toggle');
                   	loadFolderContent();
                   	$("#edit_folder_form")[0].reset();
                }
            },
            error: function() {

		        bootbox.alert("<p style='color:red'>Failed to update folder name</p>", function() {});
            }
        });
    });

    $(document).on("click", ".delete-folder", function(){

    	var base_url = '<?php echo base_url().$this->config->item('admin_folder'); ?>';
        var url = base_url+"/products/delete_folder/";

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

    	bootbox.confirm({
            title: 'Delete Action!!',
            message: "Are you sure you want to delete this folder?",
            buttons: {
                'cancel': {
                    label: 'Cancel',
                    className: 'btn-default'
                },
                'confirm': {
                    label: 'Continue',
                    className: 'btn-success pull-right'
                }
            },
            callback: function(result) {

                if (result) {

			        $.ajax({
			            type: "POST",
			            dataType: "json",
			            url: url,
			            data: {
			            	folder_id: folder_id
			            },
			            beforeSend:function(){
			            },
			            success: function(result) {
			            	

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

					        bootbox.alert("<p style='color:red'>Failed to delete folder</p>", function() {});
			            }
			        });

			    }
			}

		});
    });

    function save_sorting(){
    	var oSortable = $(".sortable").sortable("toArray");
    	
    	var base_url = '<?php echo base_url().$this->config->item('admin_folder'); ?>';
        var url = base_url+"/products/sort_folder/";

    	$.post(url, { sortable : oSortable }, function(data){
           	$("#sorting_message").html("Sorting order updated.");
           	$("#sorting_message").removeClass("d-none");

           	setTimeout(function(){
           		$("#sorting_message").addClass("d-none");
           		loadFolderContent();
           	}, 3000);
        });
    }

    $(document).on("click", ".delete-file", function(){

    	var base_url = '<?php echo base_url().$this->config->item('admin_folder'); ?>';
        var url = base_url+"/products/delete_file/";

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

    	bootbox.confirm({
            title: 'Delete Action!!',
            message: "Are you sure you want to delete this file?",
            buttons: {
                'cancel': {
                    label: 'Cancel',
                    className: 'btn-default'
                },
                'confirm': {
                    label: 'Continue',
                    className: 'btn-success pull-right'
                }
            },
            callback: function(result) {

                if (result) {

			        $.ajax({
			            type: "POST",
			            dataType: "json",
			            url: url,
			            data: {
			            	folder_id: folder_id
			            },
			            beforeSend:function(){
			            },
			            success: function(result) {
			            	

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

					        bootbox.alert("<p style='color:red'>Failed to delete folder</p>", function() {});
			            }
			        });

			    }
			}

		});
    });

    $(document).on("click", ".edit-file", function(){
    	var folder_name = $(this).attr("data-folder-name");
    	var has_locak = $(this).attr("data-has-lock");
    	var folder_id = $(this).attr("data-id");

    	$("#edit_file_name").html(folder_name);
    	$("#file_id").val(folder_id);

    	$('#edit_file_has_lock option[value="'+has_locak+'"]').prop('selected', true);

    	$('#edit_file_modal').modal('toggle');
    });

    $('#edit_file_form').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($("#edit_file_form")[0]);
        var base_url = '<?php echo base_url().$this->config->item('admin_folder'); ?>';
        var url = base_url+"/products/edit_file/";

        var id = $("#id").val();
        var parent_id = $("#parent_id").val();

        formData.append("product_id", id);
        formData.append("parent_id", parent_id);

        $.ajax({
            type: "POST",
            dataType: "json",
            url: url,
            data: formData,
            //async: false,
            global : false,
            cache: false,
            contentType: false,
            processData: false,
            beforeSend:function(){
            },
            success: function(result) {

            	if(result["status"] === false){
           			bootbox.alert("<p style='color:red'>"+result['message']+"</p>", function() {});
            	}else{
            		$('#edit_file_modal').modal('toggle');
                   	loadFolderContent();
                   	$("#edit_file_form")[0].reset();
                }
            },
            error: function() {

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

    $(document).on("click", ".copyButton", function(){
    	var textToCopy = $(this).attr("data-url");
    	navigator.clipboard.writeText(textToCopy).then(function() {
	        console.log('URL copied successfully');
	    }, function(err) {
	        console.error('Unable to copy text: ', err);
	    });
    });

</script>