<?php
// patient_appointment.php
// Search-only patient selector for booking appointments
// - No patients are shown until user explicitly searches
// - Secure server-side search using prepared statements
// - Returns JSON for AJAX and renders results client side

// Adjust include path to your DB include
require_once __DIR__ . '/../../dripend/includes/db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'search') {
    // Server-side search endpoint: returns JSON
    header('Content-Type: application/json; charset=utf-8');

    // read and sanitize inputs
    $patient_no = trim($_POST['hospital_id'] ?? '');
    $name = trim($_POST['patient_name'] ?? '');
    $gender = trim($_POST['gender'] ?? '');
    $age = trim($_POST['age'] ?? '');

    // build base query with joins for display-friendly values
    $sql = "SELECT 
                p.patient_no,
                COALESCE(pr.prefix_name, '') AS prefix,
                p.first_name,
                p.middle_name,
                p.last_name,
                COALESCE(g.gender_name, '') AS gender,
                p.age,
                p.mobile,
                p.nhis_no,
                p.other_insurance_no
            FROM patient p
            LEFT JOIN prefix pr ON pr.id = p.prefix
            LEFT JOIN gender g ON g.id = p.gender_id
            WHERE 1=1";

    $types = '';
    $params = [];

    // patient number
    if ($patient_no !== '') {
        $sql .= " AND p.patient_no LIKE ?";
        $types .= 's';
        $params[] = '%' . $patient_no . '%';
    }

    // name (search across first, middle, last using concat)
    if ($name !== '') {
        $sql .= " AND CONCAT_WS(' ', p.first_name, p.middle_name, p.last_name) LIKE ?";
        $types .= 's';
        $params[] = '%' . $name . '%';
    }

    // gender (search by gender name)
    if ($gender !== '') {
        $sql .= " AND COALESCE(g.gender_name, '') LIKE ?";
        $types .= 's';
        $params[] = '%' . $gender . '%';
    }

    // age (if numeric, exact match)
    if ($age !== '' && is_numeric($age)) {
        $sql .= " AND p.age = ?";
        $types .= 'i';
        $params[] = intval($age);
    }

    $sql .= " ORDER BY p.created_at DESC LIMIT 200"; // limit to reasonable number

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['status' => 'error', 'message' => 'Prepare failed: ' . $conn->error]);
        exit;
    }

    // bind params dynamically
    if (!empty($params)) {
        $bind_names[] = $types;
        for ($i=0; $i<count($params); $i++) {
            $bind_name = 'bind' . $i;
            $$bind_name = $params[$i];
            $bind_names[] = &$$bind_name;
        }
        call_user_func_array([$stmt, 'bind_param'], $bind_names);
    }

    if (!$stmt->execute()) {
        echo json_encode(['status' => 'error', 'message' => 'Execute failed: ' . $stmt->error]);
        exit;
    }

    $res = $stmt->get_result();
    $rows = [];
    while ($r = $res->fetch_assoc()) {
        // build display name
        $fullName = trim($r['prefix'] . ' ' . $r['first_name'] . ' ' . ($r['middle_name'] ?: '') . ' ' . $r['last_name']);
        $rows[] = [
            'patient_no' => $r['patient_no'],
            'name' => $fullName,
            'gender' => $r['gender'],
            'age' => $r['age'],
            'insurance' => $r['other_insurance_no'] ?: $r['nhis_no'],
            'mobile' => $r['mobile']
        ];
    }

    echo json_encode(['status' => 'ok', 'count' => count($rows), 'data' => $rows]);
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Search Patient | Hospital System</title>

<style>
/* keep your UI exactly as provided with minor adaptive touches */
body {
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  background: #f9fafb;
  margin: 0;
  padding: 0;
}
.container {
  max-width: 900px;
  margin: 50px auto;
  background: #ffffff;
  border-radius: 10px;
  box-shadow: 0 3px 10px rgba(0,0,0,0.08);
  padding: 20px 30px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 2px solid #e2e8f0;
  margin-bottom: 15px;
  padding-bottom: 10px;
}
.header h2 {
  margin: 0;
  color: #006400;
  font-weight: 700;
}
.search-section {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}
.search-section input {
  flex: 1 1 200px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 6px;
  font-size: 14px;
}
.search-section button {
  padding: 10px 18px;
  background-color: #006400;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 600;
}
.search-section button:hover { background-color: #004d00; }
.table-container { width: 100%; overflow-x: auto; }
table { width: 100%; border-collapse: collapse; margin-top: 10px; }
th, td { text-align: left; padding: 10px; border-bottom: 1px solid #e2e8f0; font-size: 14px; }
th { background-color: #f1f5f9; color: #333; }
tr:hover { background-color: #f8fafc; cursor: pointer; }
.btn-green {
  padding: 8px 15px;
  background-color: #006400;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-weight: 600;
  cursor: pointer;
}
.btn-green:hover { background-color: #004d00; }
.footer { margin-top: 20px; text-align: center; }
.no-results { text-align:center; color:#888; padding:18px; }
.small { font-size:12px; color:#666; margin-top:6px; }
</style>
</head>
<body>

<div class="container">
  <div class="header">
    <h2>Search Patient Record</h2>
  </div>

  <div class="search-section" role="search" aria-label="Search patient">
    <input type="text" id="hospital_id" placeholder="Hospital ID (e.g. DDC-K2025-11-00001)">
    <input type="text" id="patient_name" placeholder="Patient Name (first, middle or last)">
    <input type="text" id="gender" placeholder="Gender">
    <input type="text" id="age" placeholder="Age">
    <button id="btnSearch">Search</button>
    <button id="btnClear" style="background:#e2e2e2;color:#333;">Clear</button>
  </div>

  <div class="table-container" aria-live="polite">
    <table id="patientTable" role="table" aria-label="Search results">
      <thead>
        <tr>
          <th>Hospital ID</th>
          <th>Patient Name</th>
          <th>Gender</th>
          <th>Age</th>
          <th>Insurance</th>
          <th>Contact</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody id="patientBody">
        <tr><td colspan="7" class="no-results">Enter search criteria then click Search. No patients are shown by default.</td></tr>
      </tbody>
    </table>
  </div>

  <div class="small">Tip: You must search before selecting a patient to book an appointment.</div>

  <div class="footer">
    <button class="btn-green" onclick="window.location.href='../../dashboard.php'">Go to Main Dashboard</button>
  </div>
</div>

<script>
// helper: build a safe fetch POST
async function doSearch(payload) {
  const form = new FormData();
  form.append('action', 'search');
  for (const k in payload) {
    form.append(k, payload[k]);
  }

  const resp = await fetch(location.href, {
    method: 'POST',
    body: form,
    credentials: 'same-origin'
  });
  return resp.json();
}

function renderNoResults(message) {
  const body = document.getElementById('patientBody');
  body.innerHTML = '<tr><td colspan="7" class="no-results">' + message + '</td></tr>';
}

// render rows into table
function renderTable(data) {
  const body = document.getElementById('patientBody');
  body.innerHTML = '';
  if (!data || data.length === 0) {
    renderNoResults('No patient found for the search criteria.');
    return;
  }

  data.forEach(p => {
    const tr = document.createElement('tr');

    // sanitize basic values for insertion
    const esc = v => v === null || v === undefined ? '' : String(v).replace(/</g,'&lt;').replace(/>/g,'&gt;');

    tr.innerHTML = `
      <td>${esc(p.patient_no)}</td>
      <td>${esc(p.name)}</td>
      <td>${esc(p.gender)}</td>
      <td>${esc(p.age)}</td>
      <td>${esc(p.insurance)}</td>
      <td>${esc(p.mobile)}</td>
      <td><button class="btn-green" data-id="${esc(p.patient_no)}">Select</button></td>
    `;

    // attach click handler for select
    tr.querySelector('button').addEventListener('click', function() {
      const patientId = this.getAttribute('data-id');
      // redirect to appointment booking - preserve your path
      window.location.href = `../appointment/add_appointment.php?patient_id=${encodeURIComponent(patientId)}`;
    });

    body.appendChild(tr);
  });
}

// wire search button
document.getElementById('btnSearch').addEventListener('click', async function() {
  const hospital_id = document.getElementById('hospital_id').value.trim();
  const patient_name = document.getElementById('patient_name').value.trim();
  const gender = document.getElementById('gender').value.trim();
  const age = document.getElementById('age').value.trim();

  // basic quick client-side check to avoid empty searches if you prefer
  if (!hospital_id && !patient_name && !gender && !age) {
    alert('Please supply at least one search field.');
    return;
  }

  // UI feedback while searching
  const body = document.getElementById('patientBody');
  body.innerHTML = '<tr><td colspan="7" class="no-results">Searching...</td></tr>';

  try {
    const res = await doSearch({ hospital_id, patient_name, gender, age });
    if (res && res.status === 'ok') {
      renderTable(res.data);
    } else {
      renderNoResults(res.message || 'No patient found.');
    }
  } catch (err) {
    console.error(err);
    renderNoResults('An error occurred while searching. Check console for details.');
  }
});

// clear inputs and reset table message
document.getElementById('btnClear').addEventListener('click', function() {
  document.getElementById('hospital_id').value = '';
  document.getElementById('patient_name').value = '';
  document.getElementById('gender').value = '';
  document.getElementById('age').value = '';
  renderNoResults('Enter search criteria then click Search. No patients are shown by default.');
});

// allow pressing Enter in any field to trigger search
document.querySelectorAll('.search-section input').forEach(inp => {
  inp.addEventListener('keydown', function(e) {
    if (e.key === 'Enter') {
      e.preventDefault();
      document.getElementById('btnSearch').click();
    }
  });
});
</script>
</body>
</html>
