<?php include 'header.php'; ?>

<style>
  .badge {
    display: inline-block;
    padding: 0.45em 0.65em;
    font-size: 0.75em;
    font-weight: 700;
    line-height: 1;
    text-align: center;
    white-space: nowrap;
    vertical-align: baseline;
    border-radius: 0.375rem;
    color: #fff;
  }

  .badge-success {
    background-color: #28a745;
  }

  .badge-danger {
    background-color: #dc3545;
  }
</style>

<div class="dashboard-main-body">
  <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
    <h6 class="fw-semibold mb-0">Security Alerts List</h6>
  </div>

  <div class="d-flex flex-wrap justify-content-end gap-2 mb-3">
    <a href="add_alert.php" class="tooltip-button btn bg-primary-600 text-white border border-primary-600 radius-8 px-12 py-11 d-flex align-items-center" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-html="true" data-bs-custom-class="tooltip-primary" title="Add">
      <iconify-icon icon="ic:baseline-plus" class="icon text-xl line-height-1"></iconify-icon>
    </a>

    <a type="button" id="openFilter" class="tooltip-button btn bg-primary-600 text-white border border-primary-600 radius-8 px-12 py-11 d-flex align-items-center" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-html="true" data-bs-custom-class="tooltip-primary" title="Filter">
      <iconify-icon icon="mdi:filter-variant" class="icon text-xl line-height-1"></iconify-icon>
    </a>
  </div>

  <div class="card">
    <div class="card-header d-flex flex-wrap align-items-center justify-content-between gap-3">
      <div class="d-flex flex-wrap align-items-center gap-3">
        <form method="get" id="paginationForm" class="row g-2 align-items-center w-100">
          <!-- Show label -->
          <div class="col-12 col-sm-auto">
            <span class="fw-semibold">Show</span>
          </div>

          <!-- Per page select -->
          <div class="col-12 col-sm-auto">
            <select class="form-select form-select-sm" name="per_page" onchange="this.form.submit();">
              <option value="10">10</option>
              <option value="15">15</option>
              <option value="20">20</option>
            </select>
          </div>

          <!-- Search input -->
        <div class="col-12 col-sm-5">
            <input type="text" name="search" id="searchBox"
                   class="form-control form-control-sm"
                   placeholder="Search Here...." />
        </div>
        
        <div class="col-auto" id="bulkDeleteWrapper" style="display:none;">
            <button type="button" id="bulkDeleteBtn"
                class="btn btn-danger btn-sm d-flex align-items-center gap-1">
                <iconify-icon icon="mingcute:delete-2-line"></iconify-icon>
                Delete Selected (<span id="selectedCount">0</span>)
            </button>
        </div>
        </form>
      </div>
    </div>

    <div class="card-body">
      <div class="table-responsive">
        <table class="table modern-table mb-0" id="userTable">
          <thead>
            <tr>
              <th><input type="checkbox" id="checkAll" class="form-check-input"></th>
              <th>No</th>
              <th>Alert Type</th>
              <th>Location</th>
              <th>Incident Time</th>
              <th>Description</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>

            <tr>
              <td><input type="checkbox" class="form-check-input row-check" value="1"></td>
              <td>1</td>
              <td>Unauthorized Person</td>
              <td>Main Gate</td>
              <td>12-03-2026 10:30 AM</td>
              <td>
                  <a href="javascript:void(0)" 
                     class="view-desc text-primary"
                     data-bs-toggle="modal"
                     data-bs-target="#descriptionModal"
                     data-description="An unknown individual was seen attempting to enter the main gate without authorization.">
                     View
                  </a>
              </td>
              <!--<td>An unknown individual was seen attempting to enter the main gate without authorization.</td>-->
              <td>
                <div class="d-flex flex-wrap gap-1">

                  <a href="edit_security_alert.php" class="w-32-px h-32-px bg-success-focus text-success-main rounded-circle d-inline-flex align-items-center justify-content-center">
                    <iconify-icon icon="lucide:edit"></iconify-icon>
                  </a>

                  <a href="javascript:void(0);" class="delete-btn w-32-px h-32-px bg-danger-focus text-danger-main rounded-circle d-inline-flex align-items-center justify-content-center">
                    <iconify-icon icon="mingcute:delete-2-line"></iconify-icon>
                  </a>

                </div>
              </td>
            </tr>

            <tr>
              <td><input type="checkbox" class="form-check-input row-check" value="2"></td>
              <td>2</td>
              <td>Fire Alarm</td>
              <td>Tower B Parking</td>
              <td>11-03-2026 08:15 PM</td>
              <td>
                  <a href="javascript:void(0)" 
                     class="view-desc text-primary"
                     data-bs-toggle="modal"
                     data-bs-target="#descriptionModal"
                     data-description="An unknown individual was seen attempting to enter the main gate without authorization.">
                     View
                  </a>
              </td>
              <!--<td>Fire alarm triggered in Tower B parking area.</td>-->
              <td>
                <div class="d-flex flex-wrap gap-1">

                  <a href="edit_security_alert.php" class="w-32-px h-32-px bg-success-focus text-success-main rounded-circle d-inline-flex align-items-center justify-content-center">
                    <iconify-icon icon="lucide:edit"></iconify-icon>
                  </a>

                  <a href="javascript:void(0);" class="delete-btn w-32-px h-32-px bg-danger-focus text-danger-main rounded-circle d-inline-flex align-items-center justify-content-center">
                    <iconify-icon icon="mingcute:delete-2-line"></iconify-icon>
                  </a>

                </div>
              </td>
            </tr>

          </tbody>
        </table>
      </div>

      <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mt-24">
        <span>Showing 1 to 10 of 12 entries</span>
        <ul class="pagination d-flex flex-wrap align-items-center gap-2 justify-content-center">
          <li class="page-item">
            <a class="page-link bg-neutral-200 text-secondary-light fw-semibold radius-8 border-0 d-flex align-items-center justify-content-center h-32-px w-32-px text-md" href="javascript:void(0)">
              <iconify-icon icon="ep:d-arrow-left" class=""></iconify-icon>
            </a>
          </li>
          <li class="page-item">
            <a class="page-link text-secondary-light fw-semibold radius-8 border-0 d-flex align-items-center justify-content-center h-32-px w-32-px text-md bg-primary-600 text-white" href="javascript:void(0)">
              1
            </a>
          </li>
          <li class="page-item">
            <a class="page-link bg-neutral-200 text-secondary-light fw-semibold radius-8 border-0 d-flex align-items-center justify-content-center h-32-px w-32-px" href="javascript:void(0)">
              2
            </a>
          </li>
          <li class="page-item">
            <a class="page-link bg-neutral-200 text-secondary-light fw-semibold radius-8 border-0 d-flex align-items-center justify-content-center h-32-px w-32-px text-md" href="javascript:void(0)">
              <iconify-icon icon="ep:d-arrow-right" class=""></iconify-icon>
            </a>
          </li>
        </ul>
      </div>
    </div>
  </div>
</div>

<div class="chatbox1" id="filterBox" style="display: none">
  <div class="chatbox-close1" id="closeFilter"></div>
  <div style="display:flex; flex-direction:column; height:100%; overflow:hidden;">
    <div style="display: flex; justify-content: space-between; flex-shrink:0;">
      <h5 style="margin: 10px 0px 0px 17px">Filter</h5>
      <button class="chatbox-close1" style="font-size: 35px; margin-right: 15px">&times;</button>
    </div>
    <hr style="flex-shrink:0;" />
    <div style="margin: 0px 17px 0px 17px; flex:1;">
      <form class="form row g-3" action="" method="get" id="filterForm" style="margin-top: 5px; height:100%; display:flex; flex-direction:column;">
        <div style="flex:1;">
          <div class="col-lg-12 mb-3">
            <label class="form-label">Date</label>
            <input type="text" id="rangeInput" class="form-control" placeholder="dd-mm-yyyy to dd-mm-yyyy" readonly>
          </div>
          <div class="col-lg-12 mb-3">
            <label class="form-label">Name</label>
            <input type="text" name="name" class="form-control" placeholder="Enter Name" value="">
          </div>
          <div class="col-lg-12 mb-3">
            <label class="form-label">Mobile Number</label>
            <input type="tel" name="mobile" class="form-control" placeholder="Enter Mobile Number" value="" minlength="10" maxlength="10" pattern="\d{10}" inputmode="numeric" oninput="this.value = this.value.replace(/[^0-9]/g, '')" required />
          </div>

          <div class="col-lg-12 mb-3">
            <label class="form-label">Create On</label>
            <input type="text" id="singleDate" class="form-control" placeholder="dd-mm-yyyy" readonly>
          </div>
        </div>

        <!-- Fixed bottom buttons -->
        <div style="background:white; padding:10px; border-top:1px solid #ddd; display:flex; flex-shrink:0;">
          <div class="col-lg-6 p-2">
            <button type="submit" style="width:100%" class="btn btn-primary">Submit</button>
          </div>
          <div class="col-lg-6 p-2">
            <button type="button" id="resetButton" style="width:100%" class="btn btn-primary">Reset</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>
<div class="modal fade" id="descriptionModal" tabindex="-1">
  <div class="modal-dialog modal-md modal-dialog-centered">
    <div class="modal-content">

      <div class="modal-header">
        <h5 class="modal-title">Alert Description</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">
        <p id="modalDescription"></p>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button>
      </div>

    </div>
  </div>
</div>
<!--date picker-->
<script src="https://cdn.jsdelivr.net/npm/litepicker/dist/bundle.js"></script>

<!--filter script-->
<script>
  // Open filter on button click
  document
    .getElementById("openFilter")
    .addEventListener("click", function() {
      document.getElementById("filterBox").style.display = "block";
    });

  // Close filter on close button click
  document
    .getElementById("closeFilter")
    .addEventListener("click", function() {
      document.getElementById("filterBox").style.display = "none";
    });

  // Optional: Close on clicking second close button (inside the header)
  document.querySelectorAll(".chatbox-close1").forEach((btn) => {
    btn.addEventListener("click", function() {
      document.getElementById("filterBox").style.display = "none";
    });
  });
</script>
<script>
document.querySelectorAll(".view-desc").forEach(function(btn){

    btn.addEventListener("click", function(){

        let description = this.getAttribute("data-description");

        document.getElementById("modalDescription").innerText = description;

    });

});
</script>
<!--Date Picker -->
<script>
  new Litepicker({
    element: document.getElementById('rangeInput'),
    singleMode: false,
    format: 'DD-MM-YYYY',
    delimiter: ' to ',

    // ✅ month & year popup enabled
    dropdowns: {
      months: true,
      years: true
    }
  });
  new Litepicker({
    element: document.getElementById('singleDate'),
    singleMode: true,
    format: 'DD-MM-YYYY',

    // ✅ month & year popup enabled
    dropdowns: {
      months: true,
      years: true
    }
  });
</script>
<!--search script-->
<script>
  document.getElementById("searchBox").addEventListener("keyup", function() {

    let input = this.value.toLowerCase();
    let rows = document.querySelectorAll("#userTable tbody tr");

    rows.forEach(function(row) {

      let text = row.textContent.toLowerCase();

      if (text.indexOf(input) > -1) {
        row.style.display = "";
      } else {
        row.style.display = "none";
      }

    });

  });
</script>

<!--delete btn script-->
<script>
document.addEventListener('DOMContentLoaded', function () {

    // Shared SweetAlert config
    const swalConfig = {
        width: '350px',
        customClass: {
            popup:         'swal-modern',
            title:         'swal-title',
            htmlContainer: 'swal-text',
            confirmButton: 'swal-confirm',
            cancelButton:  'swal-cancel'
        }
    };

    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', function (e) {
            e.preventDefault();
            const row       = this.closest('tr');
            const alertType = row.querySelector('td:nth-child(3)').textContent.trim();
            const location  = row.querySelector('td:nth-child(4)').textContent.trim();

            Swal.fire({
                ...swalConfig,
                title: 'Delete Security Alert?',
                html: `Are you sure you want to delete <strong>"${alertType}"</strong> alert at <strong>${location}</strong>?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#d33',
                cancelButtonColor: '#6c757d',
            }).then((result) => {
                if (result.isConfirmed) {
                    row.remove();

                    // Update serial numbers
                    const rows = document.querySelectorAll('#userTable tbody tr');
                    rows.forEach((r, i) => {
                        r.querySelector('td:nth-child(2)').textContent = i + 1;
                    });

                    // Update entries text
                    const totalRows = rows.length;
                    const info = document.querySelector('.d-flex.align-items-center.justify-content-between.flex-wrap.gap-2.mt-24 span');
                    if (info) info.textContent = `Showing 1 to ${totalRows} of ${totalRows} entries`;

                    Swal.fire({
                        ...swalConfig,
                        title: 'Deleted!',
                        html: `<strong>"${alertType}"</strong> alert at <strong>${location}</strong> has been deleted successfully.`,
                        icon: 'success',
                        confirmButtonColor: '#4a63ff',
                    });
                }
            });
        });
    });
});
</script>
<script>
const checkAll = document.getElementById('checkAll');
const bulkWrapper = document.getElementById('bulkDeleteWrapper');
const selectedCount = document.getElementById('selectedCount');

function getVisibleRowCheckboxes() {
    return Array.from(document.querySelectorAll('#userTable tbody tr'))
        .filter(row => row.style.display !== 'none')
        .map(row => row.querySelector('.row-check'))
        .filter(Boolean);
}

function getCheckedRowCheckboxes() {
    return Array.from(
        document.querySelectorAll('#userTable tbody .row-check:checked')
    );
}

function updateBulkUI() {
    const checked = getCheckedRowCheckboxes();
    const count = checked.length;

    bulkWrapper.style.display = count > 0 ? '' : 'none';
    selectedCount.textContent = count;

    const visibleBoxes = getVisibleRowCheckboxes();
    const visibleChecked = visibleBoxes.filter(cb => cb.checked).length;

    checkAll.checked =
        visibleBoxes.length > 0 &&
        visibleChecked === visibleBoxes.length;

    checkAll.indeterminate =
        visibleChecked > 0 &&
        visibleChecked < visibleBoxes.length;
}

checkAll.addEventListener('change', function () {
    getVisibleRowCheckboxes().forEach(cb => cb.checked = this.checked);
    updateBulkUI();
});

document.getElementById('userTable').addEventListener('change', function(e) {
    if (e.target.matches('.row-check')) {
        updateBulkUI();
    }
});

document.getElementById('bulkDeleteBtn').addEventListener('click', function () {

    const checked = getCheckedRowCheckboxes();
    const count = checked.length;

    Swal.fire({
        title: 'Delete ' + count + ' security alert' + (count > 1 ? 's' : '') + '?',
        text: 'This action cannot be undone!',
        icon: 'warning',
        showCancelButton: true,
        width: '350px',
        confirmButtonColor: '#d33',
        cancelButtonColor: '#6c757d',
        customClass: {
            popup: 'swal-modern',
            title: 'swal-title',
            htmlContainer: 'swal-text',
            confirmButton: 'swal-confirm',
            cancelButton: 'swal-cancel'
        }
    }).then((result) => {

        if (result.isConfirmed) {

            checked.forEach(cb => {
                cb.closest('tr').remove();
            });

            updateBulkUI();

            document.querySelectorAll('#userTable tbody tr')
                .forEach((row, index) => {
                    row.querySelector('td:nth-child(2)').textContent = index + 1;
                });

            Swal.fire({
                title: 'Deleted!',
                text: 'Selected security alerts have been deleted.',
                icon: 'success',
                width: '350px',
                confirmButtonColor: '#4a63ff',
                customClass: {
                    popup: 'swal-modern',
                    title: 'swal-title',
                    htmlContainer: 'swal-text',
                    confirmButton: 'swal-confirm'
                }
            });
        }
    });
});
</script>

<?php include 'footer.php'; ?>