<?php
// Enable output buffering for faster page rendering
ob_start();

include('head.php');
include('header.php'); 
include('sidebar.php'); 
// error_reporting(E_ALL);ini_set('display_errors', 'On');

// OPTIMIZED: Join all tables in one query to avoid N+1 problem
// Only select columns we actually use to reduce memory
$query="SELECT 
    tblpatient.id,
    tblpatient.createdDate,
    tblpatientdetails.pId,
    tblpatientdetails.fileId,
    tblpatient.krollId,
    tblpatientdetails.patientId,
    tblpatient.firstName,
    tblpatient.lastName,
    tblpatient.dob,
    tblpatientdetails.isTransferOut,
    tblwcpart5.patientDrugName,
    tblwcpart5.prescriberName,
    tblwcpart5.staff,
    tblpatientstatus.StatusName,
    tblprovince.provinceName
FROM tblpatient 
INNER JOIN tblpatientdetails ON tblpatient.id = tblpatientdetails.pId 
LEFT JOIN tblreimbursement ON tblreimbursement.pId=tblpatient.id 
    AND tblpatientdetails.pId=tblreimbursement.pId 
    AND tblpatientdetails.fileId=tblreimbursement.fileId 
LEFT JOIN tblwcpart5 ON tblwcpart5.pId=tblpatientdetails.pId 
    AND tblwcpart5.fileId=tblpatientdetails.fileId
LEFT JOIN tblpatientstatus ON tblpatientstatus.StatusID=tblreimbursement.patientStatus
LEFT JOIN tblprovince ON tblprovince.provinceCode=tblpatient.province
WHERE tblpatient.isDeleted='N' AND tblpatientdetails.isDeleted='N'";

// Check if the user type is 'E' and add the necessary condition
if (isset($_SESSION['empType']) && $_SESSION['empType'] == 'E') {
    $sessionProvince = $_SESSION['province']; // Comma-separated string
    $provinceArray = explode(',', $sessionProvince); // Convert to array
    // Escape and quote each province for SQL
    $quotedProvinces = array_map(function($province) use ($pdo) {
        return $pdo->quote(trim($province)); // Use PDO's quote for safety
    }, $provinceArray);
    $query .= " AND tblpatient.province IN (" . implode(',', $quotedProvinces) . ")";
}

// PSP filter
$PSPID = $_GET["pspId"] ?? "";
$PSPID = $pspId ?? $PSPID;
if($PSPID!='' && $PSPID!='all'){
    $query .= " AND ".$PSPID." = tblpatientdetails.pspId";
}

// Add the ordering clause
$query .= " ORDER BY tblpatient.id DESC";

//Prepare the statement
$stmt = $pdo->prepare($query);

// Bind parameters if needed
if (isset($sessionProvince)) {
    $stmt->bindParam(':province', $sessionProvince, PDO::PARAM_STR);
}

// Execute the statement
$stmt->execute();

// Fetch all results - use PDO::FETCH_ASSOC for less memory
$patients = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Pre-process drug names to avoid doing it in the loop
foreach($patients as &$patient) {
    if (!empty($patient['patientDrugName'])) {
        $patient['drugShortName'] = trim(explode(' -', $patient['patientDrugName'])[0]);
    } else {
        $patient['drugShortName'] = '';
    }
    // Pre-format date
    if (!empty($patient['createdDate'])) {
        $patient['formattedDate'] = date('Y-m-d', strtotime($patient['createdDate']));
    } else {
        $patient['formattedDate'] = '';
    }
}
unset($patient); // Break reference
?>
<style>
.card-header.mgtop.inlineflex {
    padding: 20px;
}
a.white{
    color:white;
}
.mgtop{
    margin-top:20px;
    margin-bottom:30px;
}
#example_wrapper select:not([size]) {
    width: 10%;
    margin: 10px;
}
.rxtitle{
    font-size:24px;
    font-weight:600;
}
table a.btn {
    /* background: none; */
    height: max-content;
    width: max-content;
    display: inline-flex;
}
.dt-length,.dt-search {
    display: flex;
    vertical-align: middle;
    align-items: center;
}
.mg5{margin:0 5px;}
.customdewidth{
    margin-left: 15%;
    margin-top: 80px;
    width: 85%;
    background-color: whitesmoke;
}
aside{
   width:15%; 
}
.deindexpage .dt-search {
    float: right;
}
</style>

<section class="bgcolordefault deindexpage">
<div class="container-fluid customdewidth">
    <div class="row">
        <div class="col-md-12">
      
       
        <div class = "page-header mgtop">
            <h1 class="rxtitle text-black">
            Patient List
                <a href="add_patient.php" class="btn float-right btn-primary">Add New Patient</a>
                <a href="add_existing_patient.php" class="btn float-right btn-primary mg5">Add Existing Patient</a>
            </h1>
        </div>
        <div class="card">
                  
                        <!-- /.card-header -->
                        <div class="card-body">

                                    <table id="example" class="table table-striped table-bordered" style="width:100%;">
                                    <thead>
                                        <tr>
                                            <th class="text-center">Entry Date</th>
                                            <th class="text-center">Kroll ID</th>
                                             <th class="text-center">Patient ID</th>
                                            <th>First Name</th>
                                            <th>Last Name</th>
                                            <th class="text-center">DOB</th>
                                            <th>Province</th>
                                            <th>Drug</th>
                                           <th>Prescriber</th>
                                            <!--<th>Specialty</th>-->
                                            <th>Status</th>
                                            <th>Staff</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        // Build all rows at once for better performance
                                        foreach($patients as $pd){ 
                                            echo '<tr>',
                                                '<td class="text-center">', $pd['formattedDate'], '</td>',
                                                '<td class="text-center">', htmlspecialchars($pd['krollId'] ?? ''), '</td>',
                                                '<td class="text-center">', htmlspecialchars($pd['patientId'] ?? ''), '</td>',
                                                '<td>', htmlspecialchars($pd['firstName'] ?? ''), '</td>',
                                                '<td>', htmlspecialchars($pd['lastName'] ?? ''), '</td>',
                                                '<td class="text-center">', htmlspecialchars($pd['dob'] ?? ''), '</td>',
                                                '<td class="text-center">', htmlspecialchars($pd['provinceName'] ?? ''), '</td>',
                                                '<td>', htmlspecialchars($pd['drugShortName']), '</td>',
                                                '<td>', htmlspecialchars($pd['prescriberName'] ?? ''), '</td>',
                                                '<td>', htmlspecialchars($pd['StatusName'] ?? ''), '</td>',
                                                '<td class="text-center">', htmlspecialchars($pd['staff'] ?? ''), '</td>',
                                                '<td class="text-center">',
                                                    '<a href="edit_de_patient.php?id=', urlencode($pd['pId']), 
                                                    '&fileId=', urlencode($pd['fileId']), 
                                                    '&isTransferOut=', urlencode($pd['isTransferOut'] ?? ''), 
                                                    '" class="blue" title="View Profile"><i class="fa fa-edit"></i></a>',
                                                '</td>',
                                            '</tr>';
                                        }
                                        ?>
                                        
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                        <th class="text-center">Entry Date</th>
                                            <th class="text-center">Kroll ID</th>
                                              <th class="text-center">Patient ID</th>
                                            <th>First Name</th>
                                            <th>Last Name</th>
                                            <th class="text-center">DOB</th>
                                            <th>Province</th>
                                            <th>Drug</th>
                                           <th>Prescriber</th>
                                            <!--<th>Specialty</th>-->
                                            <th>Status</th>
                                            <th>Staff</th>
                                            <th>Action</th>
                                        </tr>
                                    </tfoot>
                                </table>
                        </div>
                        <!-- /.card-body -->
                    </div>

    </div>
    </div>
</div>
 </section>
<script>
    // Optimize DataTables initialization
    $('#example').dataTable({
        "order": [],
        "pageLength": 100,
        "deferRender": true,  // Only render visible rows
        "processing": false,   // Disable processing indicator for speed
        "stateSave": true,     // Save user's sorting/filtering preferences
        "stateDuration": 3600  // Cache state for 1 hour
    });
</script>
<?php 
include('../psp-sidebar.php');
include('footer.php'); 
// Flush output buffer
ob_end_flush();
?>