<!-- daterange picker -->
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="<?php echo $this->config->item('admin_assets_folder'); ?>plugins/summernote/summernote-bs4.min.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').'/'.'distributors/index'; ?>">Distributors</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($distributors->id) && !empty($distributors->id) ? $distributors->id : ''; ?>">

                        <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="first_name">First name<span class="required">*</span></label>
									        <input type="text" class="form-control" id="first_name" name="first_name" required value="<?php echo isset($distributors->first_name) && $distributors->first_name != '' ? $distributors->first_name : ''; ?>" data-parsley-errors-container="#first_name_error" placeholder="" />
									        <p class="error"><small id="first_name_error"></small></p>
										</div>


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

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

										<div class="form-group">
											<label class="col-form-label" for="mobile_number">Mobile number</label>
									        <input type="text" class="form-control" id="mobile_number" name="mobile_number" value="<?php echo isset($distributors->mobile_number) && $distributors->mobile_number != '' ? $distributors->mobile_number : ''; ?>" data-parsley-errors-container="#mobile_number_error" placeholder="" />
									        <p class="error"><small id="mobile_number_error"></small></p>
										</div>

										<?php
											$required = "required";
											$required_text = '<span class="required">*</span>';
											if(isset($distributors->id) && !empty($distributors->id)){
												$required = "";
												$required_text = "";
											}
										?>

										<div class="form-group">
								            <label for="password">Password<?php echo $required_text; ?></label>
								            <div class="input-group">
								                <input type="password" class="form-control" id="password" placeholder="Enter password" name="password" value="" autocomplete="off" <?php echo $required; ?> />
								                <div class="input-group-append">
								                    <span class="input-group-text" id="togglePassword">
								                        <i class="fas fa-eye" onclick="togglePasswordVisibility()"></i>
								                    </span>
								                </div>
								                <div class="input-group-append">
								                	<button type="button" class="btn btn-danger" onclick="generatePassword()">Generate Random Password</button>
								                </div>
								            </div>
								            <?php
								            	if(isset($distributors->id) && !empty($distributors->id)){
								            ?>
								            		<i style="font-size: 11px;" class="text-muted text-small">Leave the password field empty if you don't wish to update the current password.</i>
								            <?php
								            	}
								            ?>

								            <div class="custom-control custom-checkbox">
												<input class="custom-control-input custom-control-input-danger" type="checkbox" id="send_email" name="send_email">
												<label for="send_email" class="custom-control-label">Send the password to the distributor's email.</label>
											</div>
								        </div>
								        

										<div class="form-group">
											<label class="col-form-label" for="company_name">Company name</label>
									        <input type="text" class="form-control" id="company_name" name="company_name" value="<?php echo isset($distributors->company_name) && $distributors->company_name != '' ? $distributors->company_name : ''; ?>" data-parsley-errors-container="#company_name_error" placeholder="" />
									        <p class="error"><small id="company_name_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($distributors->is_active) && $distributors->is_active == 1 ? "selected" : ""; ?>>Active</option>
												<option value="0" <?php echo isset($distributors->is_active) && $distributors->is_active == 0 ? "selected" : ""; ?>>In-active</option>
											</select>
											<p class="error"><small id="is_active_error"></small></p>
										</div>

										<div class="form-group">
											<label class="col-form-label" for="expiry_date">Expiry Date</label>
									        <input type="date" class="form-control" id="expiry_date" name="expiry_date" value="<?php echo isset($distributors->expiry_date) && $distributors->expiry_date != '' ? Date("Y-m-d", strtotime($distributors->expiry_date)) : ''; ?>" data-parsley-errors-container="#expiry_date_error" placeholder="" />
									        <p class="error"><small id="expiry_date_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 -->
				</div>
			</div>
		</div>
	</section>

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

<script src="<?php echo $this->config->item('admin_assets_folder'); ?>plugins/summernote/summernote-bs4.min.js"></script>


<script type="text/javascript">

	/*$(document).ready(function(){
		$( ".sortable" ).sortable({
			update: function(event, ui) {
				console.log("1 - update on load");
			}
		});
		$( ".sortable" ).disableSelection();
	});*/

	$('.summernote').summernote({
		codemirror: { // codemirror options
			theme: 'monokai'
		},
		toolbar: [
		    // [groupName, [list of button]]
		    ['style', ['style']],
		    ['style', ['bold', 'italic', 'underline', 'clear']],
		    ['font', ['strikethrough', 'superscript', 'subscript']],
		    ['fontsize', ['fontsize']],
		    ['color', ['color']],
		    ['para', ['ul', 'ol', 'paragraph']],
		    ['insert', ['link', 'picture', 'video']],
		    ['view', ['fullscreen', 'codeview', 'help']],
		    ['height', ['height']]
		  ]
	});

	$('#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+"/distributors/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() {});
            }
        });
    });

    function togglePasswordVisibility() {
        var passwordInput = document.getElementById("password");
        var toggleIcon = document.getElementById("togglePassword").querySelector("i");
        
        if (passwordInput.type === "password") {
            passwordInput.type = "text";
            toggleIcon.classList.remove("fa-eye");
            toggleIcon.classList.add("fa-eye-slash");
        } else {
            passwordInput.type = "password";
            toggleIcon.classList.remove("fa-eye-slash");
            toggleIcon.classList.add("fa-eye");
        }
    }

    function generatePassword() {
        var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        var password = "";
        for (var i = 0; i < 8; i++) {
            password += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        document.getElementById("password").value = password;
    }
</script>

<?php
	if(isset($distributors->id) && !empty($distributors->id)){

	}else{
?>
		<script type="text/javascript">
			togglePasswordVisibility();
			generatePassword();
		</script>
<?php
	}
?>