<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;
}
.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;
}
/* Company Access Card Styles */
.company-access-card {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 1px solid #dee2e6;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  position: relative;
}
.company-access-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #dee2e6;
}
.company-access-card .card-header h6 {
  margin: 0;
  color: #2c3e50;
  font-weight: 600;
}
.company-access-card .remove-card-btn {
  color: #dc3545;
  cursor: pointer;
  font-size: 1.2rem;
}
.company-access-card .remove-card-btn:hover {
  color: #a71d2a;
}
.authority-section, .dochead-section {
  background: white;
  border-radius: 8px;
  padding: 12px;
  margin-top: 12px;
  border: 1px solid #e0e0e0;
}
.authority-section h6, .dochead-section h6 {
  color: #6c757d;
  font-size: 0.85rem;
  margin-bottom: 10px;
  font-weight: 600;
}
.add-company-btn {
  border: 2px dashed #6c757d;
  background: transparent;
  color: #6c757d;
  padding: 15px;
  border-radius: 12px;
  width: 100%;
  transition: all 0.3s ease;
}
.add-company-btn:hover {
  border-color: #0d6efd;
  color: #0d6efd;
  background: rgba(13, 110, 253, 0.05);
}
.checkbox-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 8px;
}
.checkbox-item {
  background: #f8f9fa;
  padding: 6px 10px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  display: flex;
  align-items: center;
}
.checkbox-item:hover {
  background: #e9ecef;
}
.checkbox-item label {
  cursor: pointer;
  font-size: 0.85rem;
  margin-bottom: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
/* Fix sidebar clickability */
.main-sidebar {
  z-index: 1050 !important;
}
</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">
                  <!-- Basic User Info -->
                  <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="text" 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 Access Section (for Admin and User roles) -->
                  <div class="col-md-12" id="company_access_section" style="display:none">
                    <hr class="my-4">
                    <h5 class="mb-3"><i class="fa fa-building"></i> Company Access Configuration</h5>
                    <p class="text-muted mb-3">Configure company-specific access for this user. Select a company, then choose authorities and document heads.</p>
                    
                    <!-- Company Access Cards Container -->
                    <div id="company_access_cards">
                      <!-- Cards will be added here dynamically -->
                    </div>
                    
                    <!-- Add Company Button -->
                    <button type="button" class="add-company-btn" id="add_company_btn">
                      <i class="fa fa-plus-circle"></i> Add Company Access
                    </button>
                  </div>

                  <!-- User Permissions Section (for Super Admin only) -->
                  <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 type="submit" class="btn btn-primary">Create User</button>
                    <a class="btn btn-danger" href="<?php echo site_url();?>user">Cancel</a>
                  </div>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </section>
</div>

<!-- Company Access Card Template -->
<template id="company_card_template">
  <div class="company-access-card" data-card-index="INDEX">
    <div class="card-header">
      <h6><i class="fa fa-building"></i> Company Access #<span class="card-number">INDEX</span></h6>
      <span class="remove-card-btn" title="Remove this company access"><i class="fa fa-times-circle"></i></span>
    </div>
    
    <!-- Company Selection -->
    <div class="form-group">
      <label class="form-label"><i class="fa fa-building"></i> Select Company <span class="text-danger">*</span></label>
      <select class="form-control company-select" name="company_access[INDEX][company_id]" required>
        <option value="">-- Select Company --</option>
        <?php foreach ($company_list as $company): ?>
          <option value="<?= $company['id']; ?>"><?= $company['company_name']; ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    
    <!-- Authority Section (loaded via AJAX) -->
    <div class="authority-section">
      <h6><i class="fa fa-university"></i> Select Authorities</h6>
      <div class="authority-container">
        <div class="text-muted"><i class="fa fa-info-circle"></i> Select a company first</div>
      </div>
    </div>
    
    <!-- Document Heads Section (loaded via AJAX, visible for both Admin and User roles) -->
    <div class="dochead-section">
      <h6><i class="fa fa-file-alt"></i> Select Document Heads</h6>
      <div class="dochead-container checkbox-grid">
        <div class="text-muted"><i class="fa fa-info-circle"></i> Select authorities first</div>
      </div>
    </div>
    
    <!-- Company-Specific Permissions Section -->
    <div class="permissions-section user-role-only" style="display:none; margin-top: 15px;">
      <h6><i class="fa fa-shield-alt"></i> Permissions for this Company</h6>
      <div class="row">
        <div class="col-md-4 mb-2">
          <div class="form-check">
            <input type="checkbox" name="company_access[INDEX][can_view]" value="1" class="form-check-input" id="can_view_INDEX" checked disabled>
            <label class="form-check-label" for="can_view_INDEX">
              <i class="fa fa-eye"></i> View
            </label>
          </div>
        </div>
        <div class="col-md-4 mb-2">
          <div class="form-check">
            <input type="checkbox" name="company_access[INDEX][can_add_edit]" value="1" class="form-check-input" id="can_add_edit_INDEX">
            <label class="form-check-label" for="can_add_edit_INDEX">
              <i class="fa fa-edit"></i> Add / Edit
            </label>
          </div>
        </div>
        <div class="col-md-4 mb-2 delete-permission-item">
          <div class="form-check">
            <input type="checkbox" name="company_access[INDEX][can_delete]" value="1" class="form-check-input" id="can_delete_INDEX">
            <label class="form-check-label" for="can_delete_INDEX">
              <i class="fa fa-trash"></i> Delete
            </label>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script src="<?php echo base_url();?>public/assets/js/jquery.validate.min.js"></script>
<script>
$(document).ready(function () {
  var cardIndex = 0;
  var currentRole = '';
  
  // Form Validation
  $('#user_form').validate({
    errorClass: 'is-invalid',
    validClass: 'is-valid',
    errorElement: 'div',
    errorPlacement: function(error, element) {
      error.addClass('invalid-feedback');
      error.insertAfter(element);
    },
    highlight: function(element) {
      $(element).addClass('is-invalid').removeClass('is-valid');
    },
    unhighlight: function(element) {
      $(element).removeClass('is-invalid').addClass('is-valid');
    },
    rules: {
      first_name: { required: true, normalizer: function (value) { return $.trim(value); } },
      last_name: { required: true, normalizer: function (value) { return $.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(); }
  });

  // Reset permissions on page load
  function resetPermissionCheckboxes() {
    $('#can_add_edit').prop('checked', false);
    $('#can_delete').prop('checked', false);
  }
  resetPermissionCheckboxes();
  setTimeout(resetPermissionCheckboxes, 50);

  // Role change logic
  $('#role').on('change', function () {
    var role = $(this).val();
    currentRole = role;
    
    // Reset sections
    $('#company_access_section').hide();
    $('#user_permissions_row').hide();
    $('#delete_permission_col').show();
    $('#company_access_cards').empty();
    cardIndex = 0;
    
    // Reset permission checkboxes
    resetPermissionCheckboxes();
    
    if (role === '1') {
      // Super Admin - no restrictions needed
    } 
    else if (role === '2' || role === '3') {
      // Admin or User - show company access section (permissions are now per-company)
      $('#company_access_section').show();
      $('#user_permissions_row').hide(); // Hidden - using company-specific permissions instead
      
      // Add first company access card
      addCompanyCard();
    }
  });

  // Add Company Button
  $('#add_company_btn').on('click', function() {
    addCompanyCard();
  });

  // Function to add a new company access card
  function addCompanyCard() {
    cardIndex++;
    var template = $('#company_card_template').html();
    template = template.replace(/INDEX/g, cardIndex);
    $('#company_access_cards').append(template);
    
    // Show dochead and permissions sections for both Admin and User roles
    var card = $('#company_access_cards .company-access-card').last();
    if (currentRole === '2' || currentRole === '3') {
      card.find('.user-role-only').show();
      
      // Hide delete permission for User role
      if (currentRole === '3') {
        card.find('.delete-permission-item').hide();
      }
    }
    
    // Hide already selected companies from the dropdown
    filterAvailableCompanies(card);
    
    updateCardNumbers();
  }
  
  // Function to filter out already selected companies
  function filterAvailableCompanies($card) {
    // Get all currently selected company IDs (excluding this card)
    var selectedCompanyIds = [];
    $('.company-select').not($card.find('.company-select')).each(function() {
      var val = $(this).val();
      if (val) {
        selectedCompanyIds.push(val);
      }
    });
    
    // Hide options that are already selected in other cards
    $card.find('.company-select option').each(function() {
      var optionValue = $(this).val();
      if (optionValue && selectedCompanyIds.includes(optionValue)) {
        $(this).hide();
      } else {
        $(this).show();
      }
    });
  }

  // Remove company card
  $(document).on('click', '.remove-card-btn', function() {
    var cardsCount = $('.company-access-card').length;
    if (cardsCount > 1) {
      $(this).closest('.company-access-card').remove();
      updateCardNumbers();
      
      // Refresh available companies in all remaining cards
      $('.company-access-card').each(function() {
        filterAvailableCompanies($(this));
      });
    } else {
      alert('At least one company access is required.');
    }
  });

  // Update card numbers after add/remove
  function updateCardNumbers() {
    $('.company-access-card').each(function(index) {
      $(this).find('.card-number').text(index + 1);
    });
  }

  // Company selection change - load authorities ONLY (not document heads)
  $(document).on('change', '.company-select', function() {
    var $card = $(this).closest('.company-access-card');
    var companyId = $(this).val();
    var $authorityContainer = $card.find('.authority-container');
    var $docheadContainer = $card.find('.dochead-container');
    var cardIdx = $card.data('card-index');
    
    // Update available companies in all other cards
    $('.company-access-card').each(function() {
      if (!$(this).is($card)) {
        filterAvailableCompanies($(this));
      }
    });
    
    // Clear doc heads and show message to select authorities first
    $docheadContainer.html('<div class="text-muted"><i class="fa fa-info-circle"></i> Select authorities first</div>');
    
    if (!companyId) {
      $authorityContainer.html('<div class="text-muted"><i class="fa fa-info-circle"></i> Select a company first</div>');
      $docheadContainer.html('<div class="text-muted"><i class="fa fa-info-circle"></i> Select a company first</div>');
      return;
    }
    
    // Show loading
    $authorityContainer.html('<div><i class="fa fa-spinner fa-spin"></i> Loading authorities...</div>');
    
    // Fetch authorities for selected company
    $.ajax({
      url: '<?= base_url("user/getAuthoritiesByCompany") ?>',
      method: 'POST',
      data: { company_id: companyId },
      dataType: 'json',
      success: function(response) {
        if (response.success && response.authorities.length > 0) {
          var html = '<div class="row">';
          response.authorities.forEach(function(auth, index) {
            html += '<div class="col-md-4 mb-2">' +
              '<div class="form-check">' +
              '<input type="checkbox" class="form-check-input authority-checkbox" ' +
              'name="company_access[' + cardIdx + '][authorities][]" value="' + auth.id + '" ' +
              'id="auth_' + cardIdx + '_' + auth.id + '">' +
              '<label class="form-check-label" for="auth_' + cardIdx + '_' + auth.id + '">' + 
              auth.authority_name + '</label>' +
              '</div></div>';
          });
          html += '</div>';
          $authorityContainer.html(html);
          
          // DO NOT auto-load document heads - wait for authority selection
          $docheadContainer.html('<div class="text-muted"><i class="fa fa-info-circle"></i> Select authorities to load document heads</div>');
        } else {
          $authorityContainer.html('<div class="text-warning"><i class="fa fa-exclamation-triangle"></i> No authorities found for this company.</div>');
          $docheadContainer.html('<div class="text-muted"><i class="fa fa-info-circle"></i> No authorities available</div>');
        }
      },
      error: function() {
        $authorityContainer.html('<div class="text-danger"><i class="fa fa-times"></i> Error loading authorities.</div>');
        $docheadContainer.html('<div class="text-muted"><i class="fa fa-info-circle"></i> Select authorities first</div>');
      }
    });
  });

  // Function to load document heads based on selected authorities
  function loadDocumentHeadsByAuthorities($card, companyId, authorityIds, cardIdx) {
    var $docheadContainer = $card.find('.dochead-container');
    
    if (!authorityIds || authorityIds.length === 0) {
      $docheadContainer.html('<div class="text-muted"><i class="fa fa-info-circle"></i> Select at least one authority to load document heads</div>');
      return;
    }
    
    // Fetch document heads for selected authorities
    $.ajax({
      url: '<?= base_url("user/getDocHeadsByAuthorities") ?>',
      method: 'POST',
      data: { 
        company_id: companyId,
        authority_ids: authorityIds 
      },
      dataType: 'json',
      success: function(response) {
        if (response.success && response.doc_heads && response.doc_heads.length > 0) {
          // Group document heads by authority
          var groupedDocHeads = {};
          response.doc_heads.forEach(function(dh) {
            var authName = dh.authority_name || 'Uncategorized';
            if (!groupedDocHeads[authName]) {
              groupedDocHeads[authName] = [];
            }
            groupedDocHeads[authName].push(dh);
          });
          
          // Build HTML with authority groups - document heads flow horizontally
          var html = '';
          
          Object.keys(groupedDocHeads).sort().forEach(function(authName) {
            html += '<div class="authority-group" style="margin-bottom: 15px;">';
            html += '<div class="authority-group-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 8px 12px; border-radius: 6px; margin-bottom: 8px; font-weight: 600; font-size: 0.85rem;">';
            html += '<i class="fa fa-university"></i> ' + authName;
            html += '</div>';
            html += '<div class="dochead-grid-container" style="display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px;">';
            
            groupedDocHeads[authName].forEach(function(dh) {
              html += '<div class="dochead-checkbox-wrapper" style="background: #f8f9fa; padding: 6px 10px; border-radius: 4px; border: 1px solid #e9ecef; min-width: 140px;">' +
                '<div class="form-check" style="margin: 0;">' +
                '<input type="checkbox" class="form-check-input dochead-checkbox" ' +
                'name="company_access[' + cardIdx + '][doc_heads][]" value="' + dh.id + '" ' +
                'id="dh_' + cardIdx + '_' + dh.id + '" checked style="margin-top: 0.15rem;">' +
                '<label class="form-check-label" for="dh_' + cardIdx + '_' + dh.id + '" style="font-size: 0.8rem; margin-left: 5px; cursor: pointer;">' + 
                dh.type_name + '</label>' +
                '</div></div>';
            });
            
            html += '</div></div>';
          });
          
          $docheadContainer.html(html);
        } else {
          $docheadContainer.html('<div class="text-warning"><i class="fa fa-exclamation-triangle"></i> No document heads found for selected authorities.</div>');
        }
      },
      error: function() {
        $docheadContainer.html('<div class="text-danger"><i class="fa fa-times"></i> Error loading document heads.</div>');
      }
    });
  }
  
  // Authority checkbox change - load document heads for selected authorities
  $(document).on('change', '.authority-checkbox', function() {
    var $card = $(this).closest('.company-access-card');
    var companyId = $card.find('.company-select').val();
    var cardIdx = $card.data('card-index');
    
    // Get all checked authority IDs in this card
    var authorityIds = [];
    $card.find('.authority-checkbox:checked').each(function() {
      authorityIds.push($(this).val());
    });
    
    // Load document heads for selected authorities
    if (companyId) {
      loadDocumentHeadsByAuthorities($card, companyId, authorityIds, cardIdx);
    }
  });

});
</script>
