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

if (!isset($conn) || !$conn) {
    echo "<p style='color:red;'>Error: Database connection failed.</p>";
    exit;
}

// Lookup tables
$prefixes = []; 
$genders = []; 
$insurances = [];

$res = $conn->query("SELECT id, prefix_name FROM prefix");
while ($r = $res->fetch_assoc()) $prefixes[$r['id']] = $r['prefix_name'];

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

$res = $conn->query("SELECT id, insurance_name FROM insurance_type");
while ($r = $res->fetch_assoc()) $insurances[$r['id']] = $r['insurance_name'];

// Page title
echo '<h1 style="text-align:center;color:#fff;background-color:#006400;padding:12px;border-radius:8px;margin-bottom:20px;font-family:Segoe UI, Arial, sans-serif;">
        Total Patient Report
      </h1>';

// Filters row
echo '
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;color:#000;">

    <div>
        <label>Start Date:</label>
        <input type="date" id="startDate" style="margin-right:10px;padding:5px;">
        <label>End Date:</label>
        <input type="date" id="endDate" style="margin-right:10px;padding:5px;">
        <button id="filterDate" style="padding:5px 10px;background:#006400;color:#fff;border:none;border-radius:4px;cursor:pointer;">
            Filter
        </button>
    </div>

    <div>
        <input type="text" id="globalSearch" placeholder="Search Patient..." style="padding:5px;width:300px;">
    </div>

</div>
';

// Fetch patients
$sql = "SELECT * FROM patient ORDER BY created_at DESC";
$result = $conn->query($sql);

// Table container with scroll
echo '<div style="overflow-x:auto; max-height:600px; overflow-y:scroll;">';

echo '
<table id="patientTable" class="display nowrap" style="width:100%;border-radius:8px;">
<thead>
<tr>
    <th>Sn</th>
    <th>Patient No</th>
    <th>Prefix</th>
    <th>First Name</th>
    <th>Middle Name</th>
    <th>Last Name</th>
    <th>Gender</th>
    <th>Mobile</th>
    <th>DOB</th>
    <th>Age</th>
    <th>NHIS No</th>
    <th>Other Insurance</th>
    <th>Insurance No</th>
    <th>Registered At</th>
    <th>Actions</th>
</tr>
</thead>
<tbody>
';

$colors = ['#e6f2e6','#d9f0d9','#cce9cc','#bff2bf','#b3f7b3'];
$sn = 1;

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {

        $prefix = $prefixes[$row['prefix']] ?? '';
        $gender = $genders[$row['gender_id']] ?? '';
        $insurance = $insurances[$row['other_insurance_id']] ?? '';
        $bgColor = $colors[$sn % count($colors)];
        $patientId = $row['id'];

        echo '<tr style="background-color:'.$bgColor.';">';
        echo '<td>'. $sn++ .'</td>';
        echo '<td>'. htmlspecialchars($row['patient_no']) .'</td>';
        echo '<td>'. htmlspecialchars($prefix) .'</td>';
        echo '<td>'. htmlspecialchars($row['first_name']) .'</td>';
        echo '<td>'. htmlspecialchars($row['middle_name']) .'</td>';
        echo '<td>'. htmlspecialchars($row['last_name']) .'</td>';
        echo '<td>'. htmlspecialchars($gender) .'</td>';
        echo '<td>'. htmlspecialchars($row['mobile']) .'</td>';
        echo '<td>'. htmlspecialchars($row['dob']) .'</td>';
        echo '<td>'. htmlspecialchars($row['age']) .'</td>';
        echo '<td>'. htmlspecialchars($row['nhis_no']) .'</td>';
        echo '<td>'. htmlspecialchars($insurance) .'</td>';
        echo '<td>'. htmlspecialchars($row['other_insurance_no']) .'</td>';
        echo '<td>'. htmlspecialchars($row['created_at']) .'</td>';

        // Actions column
        echo '<td style="text-align:center;">
                <a href="viewPatient.php?id='.$patientId.'" title="View" class="action-icon view">
                    👁️
                </a>
                <a href="editPatient.php?id='.$patientId.'" title="Edit" class="action-icon edit">
                    ✏️
                </a>
                <a href="deletePatient.php?id='.$patientId.'" title="Delete" class="action-icon delete" onclick="return confirm(\'Are you sure you want to delete this patient?\');">
                    🗑️
                </a>
              </td>';

        echo '</tr>';
    }
}
else {
    echo '<tr><td colspan="15" style="text-align:center;">No patient registrations found.</td></tr>';
}

echo '</tbody></table></div>';
?>

<!-- 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">
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.dataTables.min.css">

<!-- DataTables Scripts -->
<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://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.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>
$(document).ready(function() {

    var table = $('#patientTable').DataTable({
        dom: 'Bfrtip',
        buttons: ['copy', 'excel', 'csv', 'pdf'],
        paging: true,
        pageLength: 10,
        responsive: true,
        ordering: true,
        order: [[13, 'desc']],
        scrollY: "500px",
        scrollCollapse: true,
        autoWidth: false
    });

    $('#globalSearch').keyup(function() {
        table.search($(this).val()).draw();
    });

    $('#filterDate').click(function() {
        let start = $('#startDate').val();
        let end = $('#endDate').val();

        $.fn.dataTable.ext.search.push(function(settings, data) {
            let regDate = data[13];
            if (start && regDate < start) return false;
            if (end && regDate > end) return false;
            return true;
        });

        table.draw();
        $.fn.dataTable.ext.search.pop();
    });

});
</script>

<style>
body { 
    background-color: #2a9d8f; 
    color: #fff; 
    font-family: Segoe UI, Arial, sans-serif; 
    padding: 15px; 
}
#patientTable { 
    background-color: #fff; 
    color: #000; 
    border-radius: 8px; 
}
#patientTable th { 
    background-color: #006400; 
    color: #fff; 
}
#patientTable td { 
    padding: 8px; 
}
#patientTable tbody tr:hover { 
    background-color: #c0e6c0; 
    cursor: pointer; 
}
.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; 
}

/* Action Icons Styling */
.action-icon {
    text-decoration: none;
    font-size: 16px;
    margin: 0 5px;
}
.action-icon.view { color: #007bff; }
.action-icon.edit { color: #ffc107; }
.action-icon.delete { color: #dc3545; }
.action-icon:hover { opacity: 0.7; }
</style>