<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="<?php echo base_url();?>public/assets/js/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js"></script>
<style>
.form-check-input[type="checkbox"] {
  border-radius: 0.25em;
  border-color: black;
}
.text-muted, .preview-list .preview-item .preview-item-content p .content-category {
  --bs-text-opacity: 1;
  color: rgba(53, 185, 16, 0.75) !important;
}
.doc-head-auto {
  background-color: #f0f0f0;
  pointer-events: none;
  opacity: 0.8;
}
.doc-head-auto-label {
  color: #666;
}
.permissions-card {
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 8px;
  padding: 15px;
  margin-top: 15px;
}
.permissions-card h6 {
  color: #495057;
  margin-bottom: 15px;
  font-weight: 600;
}
</style>


<div class="content-wrapper">
            <!-- Main content -->
	<section class="content pt-3">
		<div class="container-fluid">
			<div class="row">
				<div class="col-md-12">
					<div class="card card-outline card-primary">
						<form id="user_form" name="user_form" method="post" action="<?php echo base_url();?>user/saveUser" autocomplete="off">
	
						<div class="card-body">
							<div class="row">
								<div class="col-md-6">
									<div class="form-group">
										<label class="form-label" for="first_name">First Name <span class="text-danger">*</span></label>
										<input type="text" class="form-control" id="first_name" name="first_name" placeholder="Enter first name" required>
									</div>
								</div>
								<div class="col-md-6">
									<div class="form-group">
										<label class="form-label" for="last_name">Last Name <span class="text-danger">*</span></label>
										<input type="text" class="form-control" id="last_name" name="last_name" placeholder="Enter last name" required>
									</div>
								</div>
								<div class="col-md-6">
									<div class="form-group">
										<label class="form-label" for="email_id">Email Address <span class="text-danger">*</span></label>
										<input type="email" class="form-control" id="email_id" name="email_id" placeholder="Enter email address" required>
									</div>
								</div>
                <div class="col-md-6">
									<div class="form-group">
										<label class="form-label" for="mobile_number">Mobile Number <span class="text-danger">*</span></label>
										<input type="mobile_number" class="form-control" id="mobile_number" name="mobile_number" placeholder="Enter mobile number" required>
									</div>
								</div>
								<div class="col-md-6">
									<div class="form-group">
										<label class="form-label" for="password">Password <span class="text-danger">*</span></label>
										<input type="password" class="form-control" id="password" name="password" placeholder="Enter password" required>
									</div>
								</div>
								<div class="col-md-6">
									<div class="form-group">
										<label class="form-label" for="role">User Role <span class="text-danger">*</span></label>
										<select name="role" id="role" class="form-control" required>
										  <option value="">Select Role</option>
										  <?php foreach($role_list as $role) { ?>
											<option value="<?php echo $role['id'];?>"><?php echo $role['role_name'];?></option>
										  <?php } ?>
										</select>
									</div>
								</div>
								
								<!-- Company Selection (for Admin and User roles) -->
								<div class="col-md-12" id="company_row" style="display:none">
								  <label class="col-sm-3 col-form-label">Company</label>
								  <div class="col-sm-12">
									<p class="text-muted mb-2"><b>Select companies user can access.</b></p>
									<div class="row">
									  <?php $i = 0; ?>
									  <?php foreach ($company_list as $company): ?>
										<div class="col-md-4 mb-2">
										  <div class="form-check">
											<input type="checkbox" name="company[]" value="<?= $company['id']; ?>" class="form-check-input" id="company_<?= $i; ?>">
											<label class="form-check-label" for="company_<?= $i; ?>">
											  <?php echo $company['company_name']; ?>
											</label>
										  </div>
										</div>
										<?php $i++; ?>
									  <?php endforeach; ?>
									</div>
								  </div>
								</div>
            
								<!-- Authority Selection (for User role only) - Dynamically loaded based on selected companies -->
								<div class="col-md-12" id="authority_row" style="display:none">
								  <label class="col-sm-3 col-form-label">Authority</label>
								  <div class="col-sm-12">
									<p class="text-muted mb-2"><b>Select authorities user can access (only enabled authorities for selected companies are shown).</b></p>
									<div class="row" id="authority_container">
									  <div class="col-12 text-muted"><i class="fa fa-info-circle"></i> Please select at least one company first.</div>
									</div>
								  </div>
								</div>
								
								<!-- Document Heads (for User role - selectable based on authorities) -->
								<div class="col-md-12" id="type_row" style="display:none">
								  <label class="col-sm-3 col-form-label">Document Heads</label>
								  <div class="col-sm-12">
									<p class="text-muted mb-2" id="dochead_instruction"><b>Select document heads user can access (only document heads from selected authorities are shown).</b></p>
									<div class="row" id="doc_heads_container">
									  <div class="col-12 text-muted"><i class="fa fa-info-circle"></i> Please select at least one authority first.</div>
									</div>
								  </div>
								</div>

								<!-- User Permissions Section -->
								<div class="col-md-12" id="user_permissions_row" style="display:none">
								  <div class="permissions-card">
									<h6><i class="fa fa-shield-alt"></i> User Permissions</h6>
									<div class="row">
									  <div class="col-md-4 mb-2">
										<div class="form-check">
										  <input type="checkbox" name="can_view" value="1" class="form-check-input" id="can_view" checked disabled autocomplete="off">
										  <label class="form-check-label" for="can_view">
											<i class="fa fa-eye"></i> View
											<small class="text-muted d-block">Can view documents and reports</small>
										  </label>
										</div>
									  </div>
									  <div class="col-md-4 mb-2">
										<div class="form-check">
										  <input type="checkbox" name="can_add_edit" value="1" class="form-check-input" id="can_add_edit" autocomplete="off">
										  <label class="form-check-label" for="can_add_edit">
											<i class="fa fa-edit"></i> Add / Edit
											<small class="text-muted d-block">Can upload and modify documents</small>
										  </label>
										</div>
									  </div>
									  <div class="col-md-4 mb-2" id="delete_permission_col">
										<div class="form-check">
										  <input type="checkbox" name="can_delete" value="1" class="form-check-input" id="can_delete" autocomplete="off">
										  <label class="form-check-label" for="can_delete">
											<i class="fa fa-trash"></i> Delete
											<small class="text-muted d-block">Can delete documents</small>
										  </label>
										</div>
									  </div>
									</div>
								  </div>
								</div>
								
								<div class="col-md-12 mt-3">
									<button class="btn btn-primary">Create</button>
									<a class="btn btn-danger" href="<?php echo site_url();?>user">Cancel</a>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><!-- /.container-fluid -->
	</section>
	<!-- /.content -->
</div>

<script>
var $j = jQuery.noConflict();
$j(document).ready(function () {
  
  // Form Validation
  $j('#user_form').validate({
    errorClass: 'is-invalid',
    validClass: 'is-valid',
    errorElement: 'div',
    errorPlacement: function(error, element) {
      error.addClass('invalid-feedback');
      if (element.closest('.form-group').length) {
        error.insertAfter(element);
      } else {
        error.insertAfter(element);
      }
    },
    highlight: function(element) {
      $j(element).addClass('is-invalid').removeClass('is-valid');
    },
    unhighlight: function(element) {
      $j(element).removeClass('is-invalid').addClass('is-valid');
    },
    rules: {
      first_name: { required: true, normalizer: function (value) { return $j.trim(value); } },
      last_name: { required: true, normalizer: function (value) { return $j.trim(value); } },
      email_id: { required: true, email: true },
      password: { required: true, minlength: 6 },
      role: { required: true }
    },
    messages: {
      first_name: { required: "Please enter First Name." },
      last_name: { required: "Please enter Last Name." },
      email_id: { required: "Please enter your email address.", email: "Please enter a valid email address." },
      password: { required: "Please provide a password.", minlength: "Password must be at least 6 characters long." },
      role: { required: "Please Select Role" }
    },
    submitHandler: function (form) { form.submit(); }
  });

  // Force all permission checkboxes to unchecked on page load (new user = no permissions yet)
  function resetPermissionCheckboxes() {
    $j('#can_add_edit').prop('checked', false);
    $j('#can_delete').prop('checked', false);
  }
  
  // Reset on page load
  resetPermissionCheckboxes();
  setTimeout(resetPermissionCheckboxes, 50);
  setTimeout(resetPermissionCheckboxes, 150);

  // Role change logic
  $j('#role').on('change', function () {
    var role = $j(this).val();
    
    // Reset all sections first
    $j('#company_row').hide();
    $j('#authority_row').hide();
    $j('#type_row').hide();
    $j('#user_permissions_row').hide();
    $j('#delete_permission_col').show();
    
    // Clear selections
    $j('input[name="company[]"]').prop('checked', false);
    $j('#authority_container').html('<div class="col-12 text-muted"><i class="fa fa-info-circle"></i> Please select at least one company first.</div>');
    $j('#doc_heads_container').html('<div class="col-12 text-muted"><i class="fa fa-info-circle"></i> Please select at least one authority first.</div>');
    
    // ALWAYS reset permission checkboxes when role changes
    $j('#can_add_edit').prop('checked', false);
    $j('#can_delete').prop('checked', false);
    
    if (role === '1') {
      // Super Admin - no restrictions needed
    } 
    else if (role === '2') {
      // Admin - show company and permissions
      $j('#company_row').show('blind');
      $j('#user_permissions_row').show('blind');
    } 
    else if (role === '3') {
      // User - show company, then authority (loaded via AJAX), then doc heads (loaded via AJAX)
      $j('#company_row').show('blind');
      $j('#authority_row').show('blind');
      $j('#type_row').show('blind');
      $j('#user_permissions_row').show('blind');
      $j('#delete_permission_col').hide(); // Users cannot delete
    }
  });

  // Company checkbox change - load authorities for User role
  $j(document).on('change', 'input[name="company[]"]', function () {
    var role = $j('#role').val();
    var selectedCompanies = [];
    $j('input[name="company[]"]:checked').each(function() {
      selectedCompanies.push($j(this).val());
    });
    
    if (role === '2') {
      // Admin role - just show/hide permissions
      if (selectedCompanies.length > 0) {
        $j('#user_permissions_row').show('blind');
      } else {
        $j('#user_permissions_row').hide('blind');
      }
    }
    else if (role === '3') {
      // User role - load authorities for selected companies
      if (selectedCompanies.length === 0) {
        $j('#authority_container').html('<div class="col-12 text-muted"><i class="fa fa-info-circle"></i> Please select at least one company first.</div>');
        $j('#doc_heads_container').html('<div class="col-12 text-muted"><i class="fa fa-info-circle"></i> Please select at least one authority first.</div>');
        return;
      }
      
      // Show loading
      $j('#authority_container').html('<div class="col-12"><i class="fa fa-spinner fa-spin"></i> Loading authorities...</div>');
      
      // Fetch authorities for selected companies
      $j.ajax({
        url: '<?= base_url("user/getAuthoritiesByCompanies") ?>',
        method: 'POST',
        data: { company_ids: selectedCompanies },
        dataType: 'json',
        success: function(response) {
          if (response.success && response.authorities.length > 0) {
            var html = '';
            response.authorities.forEach(function(auth, index) {
              html += '<div class="col-md-4 mb-2">' +
                '<div class="form-check">' +
                '<input type="checkbox" name="authority[]" value="' + auth.id + '" class="form-check-input authority-checkbox" id="authority_' + index + '">' +
                '<label class="form-check-label" for="authority_' + index + '">' + auth.authority_name + '</label>' +
                '</div></div>';
            });
            $j('#authority_container').html(html);
          } else {
            $j('#authority_container').html('<div class="col-12 text-warning"><i class="fa fa-exclamation-triangle"></i> No enabled authorities found for selected companies.</div>');
          }
          // Clear doc heads when companies change
          $j('#doc_heads_container').html('<div class="col-12 text-muted"><i class="fa fa-info-circle"></i> Please select at least one authority first.</div>');
        },
        error: function() {
          $j('#authority_container').html('<div class="col-12 text-danger"><i class="fa fa-times"></i> Error loading authorities.</div>');
        }
      });
    }
  });

  // Authority checkbox change - load document heads for User role
  $j(document).on('change', '.authority-checkbox', function () {
    var role = $j('#role').val();
    
    if (role !== '3') return; // Only for User role
    
    var selectedAuthorities = [];
    $j('.authority-checkbox:checked').each(function() {
      selectedAuthorities.push($j(this).val());
    });
    
    var selectedCompanies = [];
    $j('input[name="company[]"]:checked').each(function() {
      selectedCompanies.push($j(this).val());
    });
    
    if (selectedAuthorities.length === 0) {
      $j('#doc_heads_container').html('<div class="col-12 text-muted"><i class="fa fa-info-circle"></i> Please select at least one authority first.</div>');
      return;
    }
    
    // Show loading
    $j('#doc_heads_container').html('<div class="col-12"><i class="fa fa-spinner fa-spin"></i> Loading document heads...</div>');
    
    // Fetch document heads for selected authorities
    $j.ajax({
      url: '<?= base_url("user/getDocHeadsByAuthorities") ?>',
      method: 'POST',
      data: { 
        authority_ids: selectedAuthorities,
        company_ids: selectedCompanies
      },
      dataType: 'json',
      success: function(response) {
        if (response.success && response.doc_heads.length > 0) {
          var html = '';
          response.doc_heads.forEach(function(dh, index) {
            html += '<div class="col-md-4 mb-2">' +
              '<div class="form-check">' +
              '<input type="checkbox" name="type_name[]" value="' + dh.id + '" class="form-check-input doc-head-checkbox" id="type_name_' + index + '" checked>' +
              '<label class="form-check-label" for="type_name_' + index + '">' + dh.type_name + 
              ' <small class="text-muted">(' + (dh.authority_name || 'N/A') + ')</small></label>' +
              '</div></div>';
          });
          $j('#doc_heads_container').html(html);
        } else {
          $j('#doc_heads_container').html('<div class="col-12 text-warning"><i class="fa fa-exclamation-triangle"></i> No enabled document heads found for selected authorities.</div>');
        }
      },
      error: function() {
        $j('#doc_heads_container').html('<div class="col-12 text-danger"><i class="fa fa-times"></i> Error loading document heads.</div>');
      }
    });
  });

});
</script>
