@inject('users', 'App\Models\User')

@extends('layouts/contentNavbarLayout')

@section('title', 'Manage Organizations')

@section('page-style')
<link href="https://cdn.datatables.net/2.1.8/css/dataTables.bootstrap5.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="{{ asset('css/custom.css') }}">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/3.0.3/css/responsive.dataTables.css">
<link href="https://cdn.datatables.net/buttons/3.2.0/css/buttons.dataTables.css" rel="stylesheet">
@endsection
      
@section('content')

@if ($errors->addOrganization->any())
<!--<div class="alert alert-danger alert-dismissible fade show" role="alert">
	<ul class="m-0 list-unstyled">
            @foreach ($errors->addOrganization->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>-->
@endif

    <div class="card card-datatable table-responsive">
	
        <div class="card-header">
			<div id="custom-dt-toolbar">
				<div class="row">
					<div class="col-md-6">
						<div class="dt-toolbar-left">
							<h5 class="card-title mb-0">Manage Organizations</h5>
						</div>
					</div>
					
					<div class="col-md-6">
						<div class="dt-toolbar-right">
							<button class="btn btn-secondary create-new btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#addModal">
								<span><i class="bx bx-plus bx-sm me-sm-2"></i> 
								<span class="d-none d-sm-inline-block">Add Organization</span>
								</span>
							</button>
						</div>
					</div>
					
					</div>
				</div>
		</div><!--/.header-->
		
        <div class="card-body p-0">
            <table class="datatables-basic table table-bordered table-striped border-top dataTable" style="width:100%">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
						<th>Admin</th>
						<th>Status</th>
						<th>Created At</th>
                        <th width="40%">Action(s)</th>
                    </tr>
                </thead>
					<tbody>
                                @foreach ($organizations as $organization)
                                <tr>
                                    <td>{{ $organization->id }}</td>
                                    <td>{{ $organization->name }}</td>
									<td>{{ $users->where('id',$organization->admin)->pluck('name')->first() ?? '-' }}</td>
									<td>
										@if($organization->status==1)
											{{ 'Active'}}
										@else
											{{ 'Inactive' }}
									    @endif
									</td>
									<th>{{ $organization->created_at->format('d/m/Y') }}</th>
                                    <td>
                                        @can('update organization')
                                        <a  href="#" title="Edit" alt="Edit" class="edit" data-id="{{ $organization->id }} " data-name="{{ $organization->name }}" data-admin="{{ $organization->admin }}">
                                            <i class="bx bx-edit  bx-sm me-sm-1 text-primary"></i>
                                        </a>
										@if($organization->status==0)
										<a href="{{ url('admin/organizations/activate/'.$organization->id) }}" class="activate" title="Activate" data-id="{{ $organization->id }}"><i class="bx bx-lock-open bx-sm me-sm-1 text-success"></i>
										</a>
										@endif
										@if($organization->status==1)
										<a href="{{ url('admin/organizations/deactivate/'.$organization->id) }}" class="deactivate" title="Deactivate" data-id="{{ $organization->id }}"><i class="bx bx-lock bx-sm me-sm-1 text-danger"></i>
										</a>
										@endif
                                        @endcan

                                        @can('delete organization')
                                        <a href="{{ url('admin/organizations/'.$organization->id.'/delete') }}" title="Delete" alt="Delete" class="delete">
                                            <i class="bx bx-trash  bx-sm me-sm-1 text-danger"></i>
                                        </a>
                                        @endcan
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
            </table>
        </div>
    </div>
	
          <!-- Add Modal -->
          <div class="modal fade" id="addModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog" role="document">
              <div class="modal-content">
                <form action="{{ url('admin/organizations') }}" method="POST" class="needs-validation" novalidate>
				@csrf
                <div class="modal-header">
                  <h5 class="modal-title" id="editModalLabel1">Add Organization</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  <div class="row">
                    <div class="col-md-12 mb-3">
                      <label for="addOrganization" class="form-label">Name</label>
                      <input type="text" name="name" class="form-control" placeholder="Organization Name" value="{{ old('name')}}" required>
					  <span class="text-danger alert-sm">{{ $errors->addOrganization->first('name') }}</span>
					      <div class="invalid-feedback">Organization name is required.</div>
                    </div>
                  </div>	
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Close</button>
                  <button type="submit" class="btn btn-primary">Save changes</button>
                </div>
			  </form>
              </div>
            </div>
          </div>
	  
          <!-- Edit Modal -->
          <div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog" role="document">
              <div class="modal-content">
			  <form action="{{ url('admin/organizations/updateorganization') }}" method="POST" class="needs-validation" novalidate>
				@csrf
                <div class="modal-header">
                  <h5 class="modal-title" id="editModalLabel1">Edit Organization</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
				<input type="hidden" name="organizationid"  class="form-control edit_organizationid">
                  <div class="row">
                    <div class="col-md-12 mb-3">
                      <label for="editName" class="form-label">Name</label>
                      <input type="text" name="edit_name" class="form-control edit_name" placeholder="Enter Name" value="{{ old('edit_name')}}" required>
					  <span class="text-danger alert-sm">{{ $errors->editOrganization->first('edit_name') }}</span>
					      <div class="invalid-feedback">Organization name is required.</div>
                    </div>
					</div>
					
					<div class="row">
                    <div class="col-md-12 mb-3">
                      <label for="editAdmin" class="form-label">Organization Admin</label>
                      <select name="admin" id="admin"  class="form-select edit_admin">
							@foreach ($orgadmins as $admin)
							 <option value="" selected disabled hidden>--Select Admin--</option>
								<option 
								value="{{ $admin->id }}">{{ $admin->name }}</option>
							@endforeach
						</select>
					  @error('admin')<span class="text-danger alert-sm">{{ $message }}</span> @enderror
					      <div class="invalid-feedback"></div>
                    </div>
                  </div>	
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Close</button>
                  <button type="submit" class="btn btn-primary">Save changes</button>
                </div>
				</form>
              </div>
            </div>
			</div>
	  
	  <!-- End Offcanvas -->
      <div class="col-lg-3 col-md-6">
        <div class="mt-4">
          <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasEnd" aria-labelledby="offcanvasEndLabel">
            <div class="offcanvas-header">
              <h5 id="offcanvasEndLabel" class="offcanvas-title">Offcanvas End</h5>
              <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
            </div>
            <div class="offcanvas-body my-auto mx-0 flex-grow-0">
              <p class="text-center">Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.</p>
              <button type="button" class="btn btn-primary mb-2 d-grid w-100">Continue</button>
              <button type="button" class="btn btn-outline-secondary d-grid w-100" data-bs-dismiss="offcanvas">Cancel</button>
            </div>
          </div>
        </div>
      </div>
	  
	  @if($errors->addOrganization->any())
    <script>
        $(document).ready(function() {
            $('#addModal').modal('show');
        });
    </script>
	@endif
	
	@if($errors->editOrganization->any())
    <script>
        $(document).ready(function() {
            $('#editModal').modal('show');
        });
    </script>
	@endif
	
@endsection

@section('page-script')
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>  
<script src="https://cdn.datatables.net/2.1.8/js/dataTables.js"></script>
<script src="https://cdn.datatables.net/2.1.8/js/dataTables.bootstrap5.js"></script>
<script src="https://cdn.datatables.net/responsive/3.0.3/js/dataTables.responsive.js"></script>
<script src="https://cdn.datatables.net/responsive/3.0.3/js/responsive.dataTables.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/3.2.0/js/dataTables.buttons.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/3.2.0/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/3.2.0/js/buttons.print.min.js"></script>

<script type="text/javascript">
(function () {
  'use strict';
  window.addEventListener('load', function () {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function (form) {
      form.addEventListener('submit', function (event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();

  $(function () {
     $.noConflict();   
    var table = $('.dataTable').DataTable({
		order:[],
		dom: 'Bfrltip',
		lengthMenu: [[10, 25, 50, 100, 500, 1000, -1], [10, 25, 50, 100, 500, 1000, "All"]],
		language: {
			"emptyTable": "No data available in table",
			"lengthMenu": "Show _MENU_ entries",
		},
		responsive: true,
		buttons: [
					{
						extend: 'collection',
						text: "<i class='bx bx-download bx-sm me-sm-1'></i> Export",
						className: 'export_btns btn btn-outline-primary me-4',
						buttons: [
							{
								extend: 'csv',
								text: '<i class="bx bx-file me-1"></i> CSV',
								titleAttr: 'CSV'
							},
							{
								extend: 'excel',
								text: '<i class="bx bxs-file-export me-1"></i> Excel',
								titleAttr: 'Excel'
							},
							{
								extend: 'pdf',
								text: '<i class="bx bxs-file-pdf me-1"></i> PDF',
								titleAttr: 'PDF'
							},
						]
					},
					/*{
						extend: 'colvis',
						text: 'Display',
					}*/
				],
    });
	$('.export_btns').detach().prependTo('.dt-toolbar-right');
    $(".export_btns").addClass("dropdown-toggle");

	$('.dataTable').on('click', '.edit', function (e) {
	  e.preventDefault();
		$(".edit_organizationid").val($(this).data('id'));
		$(".edit_name").val($(this).data('name'));
		$(".edit_admin").val($(this).data('admin'));
		let modal = bootstrap.Modal.getOrCreateInstance($('#editModal')); // Returns a Bootstrap modal instance //modal.show //modal.hide
		modal.show();
  });
  
  $('.dataTable').on('click', '.deactivate', function (e) {
	  e.preventDefault();
	  var href = $(this).attr('href');
      Swal.fire({
        title: 'Deactivate organization?',
        text: "Organization members will will not be able to login",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, deactivate!'
      }).then((result) => {
        if (result.isConfirmed) {
          window.location.href = href;
        }
      });
  });
  
  $('.dataTable').on('click', '.activate', function (e) {
	  e.preventDefault();
	  var href = $(this).attr('href');
      Swal.fire({
        title: 'Activate organization?',
        text: "Organization members  will be able to login",
        icon: 'success',
        showCancelButton: true,
        confirmButtonColor: '#71dd37',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, activate!'
      }).then((result) => {
        if (result.isConfirmed) {
          window.location.href = href;
        }
      });
  });
	
  });
  
</script>
@endsection 