<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Property Search – Advanced (Gmail-style)</title>

  <!-- Bootstrap 5 -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

  <!-- DataTables + Buttons (Bootstrap 5 skin) -->
  <link href="https://cdn.datatables.net/v/bs5/dt-2.0.8/b-3.1.2/b-html5-3.1.2/b-print-3.1.2/r-3.0.2/datatables.min.css" rel="stylesheet"/>

  <!-- Bootstrap Icons -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">

  <style>
    body { background: #f5f7fb; }
    .card { border-radius: 1rem; }
    .modal-header { background: #0d6efd; color: #fff; }
    .dt-buttons .btn { margin-right: .25rem; }
    .modal-dialog { max-width: 940px; }
    .btn-icon { display: inline-flex; align-items: center; gap:.35rem; }
    .column-toggle .form-check { margin-bottom: .25rem; }
    .switch-label { font-size: .85rem; opacity: .85; }
    td.dt-actions, th.dt-actions, td.dt-select, th.dt-select { white-space: nowrap; }
  </style>
</head>
<body>

<div class="container py-4">

  <!-- Header for result page -->
  <div id="resultsHeader" class="mb-3 d-none">
    <div class="card shadow-sm">
      <div class="card-body bg-primary text-white rounded-3 d-flex align-items-center">
        <i class="bi bi-building-check fs-3 me-2"></i>
        <h4 class="mb-0">Property Search</h4>
      </div>
    </div>
  </div>

  <!-- Toolbar / Results card -->
  <div class="card shadow-sm mb-3 d-none" id="resultsCard">
    <div class="card-body">
      <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
        <div class="d-flex gap-2">
          <button id="btnOpenAdvanced" class="btn btn-outline-primary btn-icon">
            <i class="bi bi-funnel"></i><span>Advanced Search</span>
          </button>
          <div class="dropdown">
            <button class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">
              Add / Hide Columns
            </button>
            <div class="dropdown-menu p-3 column-toggle" id="columnToggleMenu" style="min-width: 260px;"></div>
          </div>
        </div>

        <!-- Results counter -->
        <div class="text-muted small">
          <span id="resultCount">Results: 0</span>
        </div>

        <div id="exportButtons" class="d-flex gap-2"></div>
      </div>
      <hr class="mt-3 mb-0">
      <div class="table-responsive pt-3">
        <table id="resultsTable" class="table table-striped table-hover w-100"></table>
      </div>
    </div>
  </div>

  <!-- Empty state -->
  <div id="emptyState" class="text-center text-muted py-5">
    <img alt="" src="https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/svg/1f50d.svg" width="48" height="48" />
    <h5 class="mt-3">Start with Advanced Search</h5>
    <p class="mb-4">Use the overlay to filter by Property ID, owner details, CofO info, and more.</p>
    <button class="btn btn-primary" id="btnEmptyOpen">Open Advanced Search</button>
  </div>
</div>

<!-- Advanced Search (Gmail-style full overlay) -->
<div class="modal fade" id="advancedSearchModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content shadow-lg">
      <!-- Header -->
      <div class="modal-header d-flex justify-content-between align-items-center">
        <!-- Left: title -->
        <div class="d-flex align-items-center gap-2">
          <i class="bi bi-funnel-fill"></i>
          <h5 class="modal-title mb-0">Advanced Property Search</h5>
        </div>

        <!-- Right: toggle + hidden field + close -->
        <div class="d-flex align-items-center gap-3">
          <span class="switch-label text-white-50">Match mode:</span>
          <div class="btn-group btn-group-sm" role="group" aria-label="Match Mode">
            <input type="radio" class="btn-check" name="matchMode" id="modeStrict" autocomplete="off">
            <label class="btn btn-outline-light" for="modeStrict" title="Strict: exact matches using =">Strict</label>

            <input type="radio" class="btn-check" name="matchMode" id="modeContains" autocomplete="off" checked>
            <label class="btn btn-light" for="modeContains" title="Contains: partial matches using LIKE %term%">Contains</label>
          </div>
          <input type="hidden" id="searchMode" name="searchMode" value="lax">
          <button type="button" class="btn-close btn-close-white ms-2" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
      </div>

      <!-- Body -->
      <form id="advancedSearchForm">
        <div class="modal-body">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label">Property Unique ID</label>
              <input type="text" class="form-control" name="propertyId" placeholder="e.g. EB-12345" />
            </div>
            <div class="col-md-6">
              <label class="form-label">Owner(s) Name</label>
              <input type="text" class="form-control" name="ownerName" placeholder="e.g. Chidi Okafor" />
            </div>
            <div class="col-md-6">
              <label class="form-label">Owner(s) Gender</label>
              <select class="form-select" name="ownerGender">
                <option value="">Any</option>
                <option>Male</option>
                <option>Female</option>
                <option>Other</option>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label">Ownership Type</label>
              <select class="form-select" name="ownershipType">
                <option value="">Any</option>
                <option>Sole Ownership</option>
                <option>Joint Ownership</option>
                <option>Corporate Ownership</option>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label">Owner Type</label>
              <select class="form-select" name="ownerType">
                <option value="">Any</option>
                <option>Individual</option>
                <option>Company</option>
                <option>Government</option>
                <option>Organization</option>
              </select>
            </div>

            <!-- New fields -->
            <div class="col-md-6">
              <label class="form-label">File Number</label>
              <input type="text" class="form-control" name="fileNumber" placeholder="e.g. FN-2025-001" />
            </div>
            <div class="col-md-6">
              <label class="form-label">Land Use</label>
              <input type="text" class="form-control" name="landUse" placeholder="e.g. Residential" />
            </div>
            <div class="col-md-6">
              <label class="form-label">Description</label>
              <input type="text" class="form-control" name="description" placeholder="Short description..." />
            </div>

            <div class="col-md-6">
              <label class="form-label">CofO Issuance Date (From)</label>
              <input type="date" class="form-control" name="issuanceFrom" />
            </div>
            <div class="col-md-6">
              <label class="form-label">CofO Issuance Date (To)</label>
              <input type="date" class="form-control" name="issuanceTo" />
            </div>
            <div class="col-md-6">
              <label class="form-label">CofO Registration Date (From)</label>
              <input type="date" class="form-control" name="registrationFrom" />
            </div>
            <div class="col-md-6">
              <label class="form-label">CofO Registration Date (To)</label>
              <input type="date" class="form-control" name="registrationTo" />
            </div>
            <div class="col-md-6">
              <label class="form-label">CofO Reference Number</label>
              <input type="text" class="form-control" name="referenceNumber" placeholder="e.g. C-2024-00988" />
            </div>
            <div class="col-md-6">
              <label class="form-label">LGA (optional)</label>
              <input type="text" class="form-control" name="lga" placeholder="e.g. Abakaliki" />
            </div>
          </div>
        </div>

        <!-- Footer -->
        <div class="modal-footer d-flex justify-content-between">
          <div class="text-white-50 small">
            Tip: Switch <strong>Strict</strong>/<strong>Contains</strong> to control match mode.
          </div>
          <div>
            <button type="reset" class="btn btn-outline-light">Clear</button>
            <button type="button" class="btn btn-outline-light" data-bs-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-warning text-dark">
              <i class="bi bi-search"></i> Search
            </button>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- jQuery, Bootstrap, DataTables -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/v/bs5/dt-2.0.8/b-3.1.2/b-html5-3.1.2/b-print-3.1.2/r-3.0.2/datatables.min.js"></script>

<!-- PDF/CSV deps -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>

<script>
(function() {
  const endpoint = 'search_properties.php'; // adjust if needed

  // Match Mode toggle -> hidden field
  function updateSearchMode() {
    const mode = document.getElementById('modeStrict').checked ? 'strict' : 'lax';
    document.getElementById('searchMode').value = mode;
    // (optional) visual state
    document.querySelector('label[for="modeStrict"]').classList.toggle('btn-light',  mode === 'strict');
    document.querySelector('label[for="modeStrict"]').classList.toggle('btn-outline-light', mode !== 'strict');
    document.querySelector('label[for="modeContains"]').classList.toggle('btn-light',  mode === 'lax');
    document.querySelector('label[for="modeContains"]').classList.toggle('btn-outline-light', mode !== 'lax');
  }
  document.getElementById('modeStrict').addEventListener('change', updateSearchMode);
  document.getElementById('modeContains').addEventListener('change', updateSearchMode);
  updateSearchMode();

  // Selection tracking (by propertyId)
  const selectedIds = new Set();
  const isChecked = id => selectedIds.has(id);
  const setChecked = (id, checked) => { if (!id) return; checked ? selectedIds.add(id) : selectedIds.delete(id); };

  // Data columns from backend
  const dataColumns = [
    { data: 'propertyId',       title: 'Property ID' },
    { data: 'ownerName',        title: 'Owner(s) Name' },
    { data: 'ownerGender',      title: 'Owner Gender' },
    { data: 'ownershipType',    title: 'Ownership Type' },
    { data: 'ownerType',        title: 'Owner Type' },
    { data: 'fileNumber',       title: 'File Number' },
    { data: 'landUse',          title: 'Land Use' },
    { data: 'description',      title: 'Description' },
    { data: 'issuanceDate',     title: 'CofO Issued' },
    { data: 'registrationDate', title: 'CofO Registered' },
    { data: 'referenceNumber',  title: 'CofO Ref' },
    { data: 'lga',              title: 'LGA' }
  ];

  // Add selection + actions columns
  const columns = [
    {
      title: `<input type="checkbox" id="selectAllRows" aria-label="Select all visible rows">`,
      data: null, className: 'dt-select no-export', orderable: false, searchable: false, width: '1%',
      render: (data, type, row) => {
        const id = row.propertyId ?? '';
        const checked = isChecked(id) ? 'checked' : '';
        return `<input type="checkbox" class="row-select" data-id="${id}" ${checked} aria-label="Select row">`;
      }
    },
    ...dataColumns,
    {
      title: 'Actions', data: null, className: 'dt-actions text-nowrap no-export', orderable: false, searchable: false,
      render: (data, type, row) => {
        const id = row.propertyId ?? '';
        return `
          <div class="btn-group">
            <button class="btn btn-sm btn-outline-primary btn-view" data-id="${id}">
              <i class="bi bi-eye"></i> View
            </button>
            <button class="btn btn-sm btn-outline-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown">
              <span class="visually-hidden">Toggle</span>
            </button>
            <ul class="dropdown-menu dropdown-menu-end">
              <li><a class="dropdown-item action-doc" data-id="${id}" href="#"><i class="bi bi-file-earmark-text me-2"></i>View Document</a></li>
              <li><a class="dropdown-item action-transactions" data-id="${id}" href="#"><i class="bi bi-arrow-left-right me-2"></i>View Transactions</a></li>
              <li><a class="dropdown-item action-payments" data-id="${id}" href="#"><i class="bi bi-cash-coin me-2"></i>View Payments</a></li>
            </ul>
          </div>`;
      }
    }
  ];

  let dt;
  const modal = new bootstrap.Modal(document.getElementById('advancedSearchModal'), { backdrop: 'static' });

  // Open overlay on first load
  window.addEventListener('load', () => modal.show());
  document.getElementById('btnEmptyOpen').addEventListener('click', () => modal.show());
  document.getElementById('btnOpenAdvanced').addEventListener('click', () => modal.show());

  // Collect current form payload
  function currentFormPayload() {
    const formEl = document.getElementById('advancedSearchForm');
    const fd = new FormData(formEl);
    fd.set('searchMode', document.getElementById('searchMode').value || 'lax');
    return fd;
  }

  // Initialize DataTable (server-side)
  function initDataTable() {
    dt = new DataTable('#resultsTable', {
      serverSide: true,
      processing: true,
      deferRender: true,
      responsive: true,
      pageLength: 50,
      lengthMenu: [10, 25, 50, 100],
      // Bottom: info | length | pager
      dom: "<'row'<'col-sm-12 text-md-end'B>>" +
           "<'row'<'col-sm-12'tr>>" +
           "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-3'l><'col-sm-12 col-md-4 text-md-end'p>>",
      buttons: [
        { extend: 'print', text: 'Print', exportOptions: { columns: ':visible:not(.no-export)' } },
        { extend: 'csvHtml5', title: 'property-search', text: 'Export CSV', exportOptions: { columns: ':visible:not(.no-export)' } },
        { extend: 'pdfHtml5', title: 'property-search', text: 'Download PDF', orientation: 'landscape', pageSize: 'A4', exportOptions: { columns: ':visible:not(.no-export)' } }
      ],
      ajax: (data, callback) => {
        const fd = currentFormPayload();
        fd.set('draw', data.draw);
        fd.set('start', data.start);
        fd.set('length', data.length);

        fetch(endpoint, { method: 'POST', body: fd })
          .then(res => {
            if (!res.ok) throw new Error('Network error');
            return res.json();
          })
          .then(json => {
            // Result counter
            document.getElementById('resultCount').textContent = `Results: ${json.recordsFiltered ?? 0}`;

            // Build column toggle menu once (skip select/actions)
            const menu = document.getElementById('columnToggleMenu');
            if (!menu.hasChildNodes()) {
              dt.columns().every(function(idx) {
                if (idx === 0 || idx === (columns.length - 1)) return;
                const col = this;
                const title = columns[idx].title || '';
                const id = 'colvis_'+idx;
                const wrapper = document.createElement('div');
                wrapper.className = 'form-check';
                wrapper.innerHTML = `
                  <input class="form-check-input" type="checkbox" id="${id}" ${col.visible() ? 'checked' : ''}>
                  <label class="form-check-label" for="${id}">${title}</label>
                `;
                wrapper.querySelector('input').addEventListener('change', function() {
                  col.visible(this.checked);
                });
                menu.appendChild(wrapper);
              });
            }

            callback({
              draw: json.draw,
              recordsTotal: json.recordsTotal,
              recordsFiltered: json.recordsFiltered,
              data: json.data || []
            });
          })
          .catch(err => {
            console.error(err);
            callback({ draw: data.draw, recordsTotal: 0, recordsFiltered: 0, data: [] });
            alert('Search failed. Please try again.');
          });
      },
      order: [[1, 'asc']], // sort by Property ID (index 1 because 0 is checkbox col)
      columns
    });

    // Put export buttons into toolbar
    dt.buttons().containers().appendTo('#exportButtons');

    // Selection: header "select all" (visible rows)
    $('#resultsTable').on('change', '#selectAllRows', function() {
      const checked = this.checked;
      $('#resultsTable tbody input.row-select').each(function() {
        const id = this.getAttribute('data-id') || '';
        this.checked = checked;
        setChecked(id, checked);
      });
    });

    // Selection: per-row checkbox
    $('#resultsTable').on('change', 'input.row-select', function() {
      const id = this.getAttribute('data-id') || '';
      setChecked(id, this.checked);

      const $all = $('#resultsTable tbody input.row-select');
      const $checked = $('#resultsTable tbody input.row-select:checked');
      const allVisibleChecked = $all.length && $checked.length === $all.length;
      const headerCb = document.getElementById('selectAllRows');
      if (headerCb) headerCb.checked = allVisibleChecked;
    });

    // Re-apply selection state after each draw
    $('#resultsTable').on('draw.dt', function() {
      // Restore row checkbox states
      $('#resultsTable tbody input.row-select').each(function() {
        const id = this.getAttribute('data-id') || '';
        this.checked = isChecked(id);
      });
      // Update header checkbox for visible rows
      const $all = $('#resultsTable tbody input.row-select');
      const $checked = $('#resultsTable tbody input.row-select:checked');
      const headerCb = document.getElementById('selectAllRows');
      if (headerCb) headerCb.checked = ($all.length && $checked.length === $all.length);
    });

    // Action redirects
    $('#resultsTable').on('click', '.btn-view', function(e) {
      e.preventDefault();
      const id = this.dataset.id;
      if (id) window.location.href = 'view.php?propertyId=' + encodeURIComponent(id);
    });
    $('#resultsTable').on('click', '.action-doc', function(e) {
      e.preventDefault();
      const id = this.dataset.id;
      if (id) window.location.href = 'view_document.php?propertyId=' + encodeURIComponent(id);
    });
    $('#resultsTable').on('click', '.action-transactions', function(e) {
      e.preventDefault();
      const id = this.dataset.id;
      if (id) window.location.href = 'view_transactions.php?propertyId=' + encodeURIComponent(id);
    });
    $('#resultsTable').on('click', '.action-payments', function(e) {
      e.preventDefault();
      const id = this.dataset.id;
      if (id) window.location.href = 'view_payment.php?propertyId=' + encodeURIComponent(id);
    });
  }

  // Submit: init or reload table
  document.getElementById('advancedSearchForm').addEventListener('submit', function (e) {
    e.preventDefault();

    if (!dt) {
      initDataTable();
    } else {
      // Clear selection on new search
      selectedIds.clear();
      const headerCb = document.getElementById('selectAllRows');
      if (headerCb) headerCb.checked = false;
      dt.ajax.reload(null, true); // reset to page 1
    }

    // Show results, hide empty state, close modal
    document.getElementById('emptyState').classList.add('d-none');
    document.getElementById('resultsHeader').classList.remove('d-none');
    document.getElementById('resultsCard').classList.remove('d-none');
    modal.hide();
  });
})();
</script>
</body>
</html>
