<!-- Topbar -->
<div class="topbar">
  <h3>Authority List</h3>
  <div class="user-profile">
    <span class="fw-semibold">Chetan Lathigara</span>
    <img src="https://cdn-icons-png.flaticon.com/512/847/847969.png" width="100" alt="User Avatar">
  </div>
</div>

<!-- Main Content -->
<style>
/* Column Search Styles */
.column-search-row input {
    width: 100%;
    padding: 6px 10px;
    border: 1px solid #e2e8f0;
    border-radius: 4px;
    font-size: 0.8rem;
    background: #fff;
    transition: all 0.2s;
}
.column-search-row input:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}
.column-search-row input::placeholder {
    color: #94a3b8;
}
.column-search-row th {
    background: #f8fafc !important;
    padding: 8px 10px !important;
}
</style>

<div class="content">
  <div class="card">
    <div class="card position-relative shadow-sm rounded-4">
    <!-- Action buttons fixed inside card -->
      <div class="fab-top-group" style="display: flex; gap: 8px; position: absolute; top: 15px; right: 15px; z-index: 10;">
        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="resetSearch()" title="Reset Search" style="border-radius: 50%; width: 36px; height: 36px; padding: 0;">
          <i class="fa fa-undo"></i>
        </button>
        <a href="<?= base_url('authority/create') ?>" class="btn btn-primary btn-sm" style="border-radius: 50%; width: 36px; height: 36px; padding: 0; display: flex; align-items: center; justify-content: center;">
          <i class="fa-solid fa-plus"></i>
        </a>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table align-middle text-center mb-0" id="authority-table">
              <thead>
                  <tr>
                      <th style="width: 60px;">Sr.No</th>
                      <th style="text-align:left;">Authority Name</th>
                      <th style="text-align:left;">Alias</th>
                      <th>Created On</th>
                      <th style="width: 140px;">Action</th>
                  </tr>
                  <tr class="column-search-row">
                      <th></th>
                      <th><input type="text" class="column-search" data-column="1" placeholder="Search Authority..."></th>
                      <th><input type="text" class="column-search" data-column="2" placeholder="Search Alias..."></th>
                      <th><input type="text" class="column-search" data-column="3" placeholder="Search Date..."></th>
                      <th></th>
                  </tr>
              </thead>
            <tbody>
              <?php if(empty($authorities)): ?>
              <tr>
                  <td colspan="5" class="text-center">No authority types found</td>
              </tr>
              <?php else: ?>
                  <?php $i = 1; foreach($authorities as $row): ?>
                  <tr>
                      <td><?= $i++ ?></td>
                      <td style="text-align:left;"><?= $row['authority_name'] ?></td>
                      <td style="text-align:left;"><?= $row['alias'] ?></td>
                      <td><?= date("d-M-Y", strtotime($row['creation_date'])); ?></td>
                      <td>
                          <a href="<?= base_url('authority/edit/'.$row['id']) ?>" class="btn btn-warning btn-icon"><i class="fas fa-edit"></i></a>
                          <a href="<?= base_url('authority/delete/'.$row['id']) ?>" class="btn btn-danger btn-icon" onclick="return confirm('Are you sure to Delete?')"><i class="fas fa-trash-alt"></i></a>
                          <?php if ($row['status'] == '1'): ?>
                                  <button type="button" 
                                  class="btn btn-success btn-icon rounded-circle" 
                                  onclick="handleDeactivation(<?= $row['id'] ?>, '<?= htmlspecialchars($row['authority_name'], ENT_QUOTES) ?>')" 
                                  title="Active - Click to Deactivate">
                                      <i class="fas fa-check"></i>
                                  </button>
                          <?php else: ?>
                                  <a href="<?= site_url('authority/toggle_status/'.$row['id']); ?>" 
                                  class="btn btn-secondary btn-icon rounded-circle"
                                  onclick="return confirm('Are you sure to activate?');" title="Inactive - Click to Activate">
                                      <i class="fas fa-times"></i>
                                  </a>
                          <?php endif; ?>
                      </td>
                  </tr>
                  <?php endforeach; ?>
              <?php endif; ?>
              </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Scripts -->
<script src="<?php echo site_url(); ?>public/assets/js/jquery-1.11.1.min.js"></script>
<script src="<?php echo site_url(); ?>public/assets/js/dataTables.js"></script>
<script src="<?php echo site_url(); ?>public/assets/js/dataTables.bootstrap5.js"></script>
<script src="<?php echo site_url(); ?>public/assets/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    // DataTable with column search
    var table = new DataTable('#authority-table', {
        orderCellsTop: true,
        autoWidth: false,
        columnDefs: [
            { orderable: false, targets: [0, 4] },
            { searchable: false, targets: [0, 4] }
        ]
    });

    // Column search functionality
    $('#authority-table .column-search').on('keyup change', function() {
        var columnIdx = $(this).data('column');
        table.column(columnIdx).search(this.value).draw();
    });
    
    // Reset search function
    function resetSearch() {
        $('#authority-table .column-search').val('');
        table.columns().search('').draw();
    }
    
    // Handle Authority Deactivation with Date and Remarks
    function handleDeactivation(authorityId, authorityName) {
        Swal.fire({
            title: 'Deactivate Authority',
            html: `
                <div style="text-align: left;">
                    <p style="margin-bottom: 1rem; color: #64748b;">You are about to deactivate: <strong>${authorityName}</strong></p>
                    
                    <div style="margin-bottom: 1rem;">
                        <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #334155;">
                            Deactivation Date <span style="color: #ef4444;">*</span>
                        </label>
                        <input type="date" id="deactivation_date" class="swal2-input" 
                            style="width: 100%; padding: 0.5rem; margin: 0;" 
                            value="${new Date().toISOString().split('T')[0]}" 
                            max="${new Date().toISOString().split('T')[0]}" required>
                    </div>
                    
                    <div style="margin-bottom: 1rem;">
                        <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #334155;">
                            Reason/Remarks <span style="color: #ef4444;">*</span>
                        </label>
                        <textarea id="deactivation_remarks" class="swal2-textarea" 
                            style="width: 100%; min-height: 80px; padding: 0.5rem; margin: 0;" 
                            placeholder="Enter reason for deactivation..." required></textarea>
                    </div>
                </div>
            `,
            showCancelButton: true,
            confirmButtonText: 'Next',
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#3b82f6',
            cancelButtonColor: '#6b7280',
            preConfirm: () => {
                const date = document.getElementById('deactivation_date').value;
                const remarks = document.getElementById('deactivation_remarks').value.trim();
                
                if (!date) {
                    Swal.showValidationMessage('Please select deactivation date');
                    return false;
                }
                if (!remarks) {
                    Swal.showValidationMessage('Please enter reason/remarks');
                    return false;
                }
                
                return { date, remarks };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                // Show confirmation dialog with entered details
                Swal.fire({
                    title: 'Confirm Deactivation',
                    html: `
                        <div style="text-align: left;">
                            <p style="margin-bottom: 1rem;"><strong>Authority:</strong> ${authorityName}</p>
                            <p style="margin-bottom: 1rem;"><strong>Deactivation Date:</strong> ${new Date(result.value.date).toLocaleDateString('en-GB', {day: '2-digit', month: 'short', year: 'numeric'})}</p>
                            <p style="margin-bottom: 1rem;"><strong>Reason:</strong> ${result.value.remarks}</p>
                            <p style="color: #dc2626; margin-top: 1rem;">
                                <i class="fas fa-exclamation-triangle"></i> This will hide the authority from uploads and reports.
                            </p>
                        </div>
                    `,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Deactivate',
                    cancelButtonText: 'Cancel',
                    confirmButtonColor: '#dc2626',
                    cancelButtonColor: '#6b7280'
                }).then((confirmResult) => {
                    if (confirmResult.isConfirmed) {
                        // Proceed with deactivation
                        $.ajax({
                            url: '<?= base_url('authority/toggle_status/') ?>' + authorityId,
                            type: 'POST',
                            data: {
                                deactivation_date: result.value.date,
                                deactivation_remarks: result.value.remarks
                            },
                            success: function(response) {
                                Swal.fire({
                                    title: 'Deactivated!',
                                    text: 'Authority has been deactivated successfully.',
                                    icon: 'success',
                                    confirmButtonColor: '#10b981'
                                }).then(() => {
                                    location.reload();
                                });
                            },
                            error: function() {
                                Swal.fire({
                                    title: 'Error!',
                                    text: 'Failed to deactivate authority. Please try again.',
                                    icon: 'error',
                                    confirmButtonColor: '#dc2626'
                                });
                            }
                        });
                    }
                });
            }
        });
    }
</script>
