<?php
// patient_medical_records.php
require_once __DIR__ . '/../../dripend/includes/db.php';

// Fetch lookup tables
$genders = [];
$res = $conn->query("SELECT id, gender_name FROM gender");
while ($r = $res->fetch_assoc()) $genders[$r['id']] = $r['gender_name'];

$insurances = [];
$res = $conn->query("SELECT id, insurance_name FROM insurance_type");
while ($r = $res->fetch_assoc()) $insurances[$r['id']] = $r['insurance_name'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search Patient | Hospital System</title>

<!-- DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.5/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.dataTables.min.css">

<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; background: #f9fafb; margin: 0; padding: 0; }
.container { max-width: 950px; 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; word-wrap: break-word; }
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; }
.dataTables_wrapper .dt-buttons button { background:#006400; color:#fff; border:none; border-radius:4px; margin-right:5px; padding:5px 10px; }
.dataTables_wrapper .dt-buttons button:hover { background:#004d00; }
</style>
</head>
<body>

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

  <div class="search-section">
    <input type="text" id="hospital_id" placeholder="Hospital ID">
    <input type="text" id="patient_name" placeholder="Patient Name">
    <input type="text" id="gender" placeholder="Gender">
    <input type="text" id="age" placeholder="Age">
    <input type="date" id="startDate" placeholder="Start Date">
    <input type="date" id="endDate" placeholder="End Date">
    <button onclick="filterTable()">Search / Filter</button>
  </div>

  <div class="table-container">
    <table id="patientTable" class="display nowrap">
      <thead>
        <tr>
          <th>Hospital ID</th>
          <th>Patient Name</th>
          <th>Gender</th>
          <th>Age</th>
          <th>Insurance</th>
          <th>Contact</th>
          <th>Registered At</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <?php
        $sql = "SELECT * FROM patient ORDER BY created_at DESC";
        $result = $conn->query($sql);
        if($result && $result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                $gender = $genders[$row['gender_id']] ?? '';
                $insurance = $insurances[$row['other_insurance_id']] ?? '';
                $full_name = trim($row['first_name'].' '.$row['middle_name'].' '.$row['last_name']);
                echo "<tr>
                        <td>{$row['patient_no']}</td>
                        <td>{$full_name}</td>
                        <td>{$gender}</td>
                        <td>{$row['age']}</td>
                        <td>{$insurance}</td>
                        <td>{$row['mobile']}</td>
                        <td>{$row['created_at']}</td>
                        <td><button class='btn-green' onclick=\"selectPatient('{$row['patient_no']}')\">Select</button></td>
                    </tr>";
            }
        } else {
            echo "<tr><td colspan='8' style='text-align:center;color:#888;'>No patient registrations found</td></tr>";
        }
        ?>
      </tbody>
    </table>
  </div>

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

<!-- jQuery and DataTables -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<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>
let table = $('#patientTable').DataTable({
    dom: 'Bfrtip',
    buttons: ['copy','excel','csv','pdf'],
    "paging": true,
    "pageLength": 10,
    "lengthMenu": [5,10,25,50,100],
    "ordering": true,
    "order": [[0,'desc']],
    "autoWidth": false
});

// Function to filter table dynamically
function filterTable(){
    const id = $('#hospital_id').val().toLowerCase();
    const name = $('#patient_name').val().toLowerCase();
    const gender = $('#gender').val().toLowerCase();
    const age = $('#age').val();
    const start = $('#startDate').val();
    const end = $('#endDate').val();

    $.fn.dataTable.ext.search = [];
    $.fn.dataTable.ext.search.push(
        function(settings, data, dataIndex){
            const hospitalId = data[0].toLowerCase();
            const fullName = data[1].toLowerCase();
            const genderVal = data[2].toLowerCase();
            const ageVal = data[3];
            const regDate = data[6];

            if(id && !hospitalId.includes(id)) return false;
            if(name && !fullName.includes(name)) return false;
            if(gender && !genderVal.includes(gender)) return false;
            if(age && ageVal != age) return false;

            if(start && regDate < start) return false;
            if(end && regDate > end) return false;

            return true;
        }
    );
    table.draw();
}
function selectPatient(patientId){
    window.location.href = `medical_record_profile.php?patient_id=${patientId}`;
}
</script>

</body>
</html>
