<?php
include('../head.php');
include('../header.php'); 
requirePermission($pdo, $_SESSION['clientId'], 'enrollment');
// error_reporting(E_ALL);ini_set('display_errors', 'On');
// Start by defining the base query
// $query = "SELECT * FROM tblpatient INNER JOIN tblpatientdetails ON tblpatient.id = tblpatientdetails.pId";
$query="SELECT tblpatient.*,tblpatientdetails.*,tblreimbursement.patientStatus as pStatus 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 
WHERE tblpatient.isDeleted='N' and tblpatientdetails.isDeleted='N'";
// Check if the user type is 'E' and add the necessary condition
// if ($_SESSION['empType'] == 'E') {
//     $sessionProvince = $_SESSION['province'];
//     $query .= " && tblpatient.province = :province";
// }
// Check if the user type is 'E' and add the necessary condition
if (isset($_SESSION['empType'])) {
if ($_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
// $pspCondition = '';
// $PSP=$_GET["psp"] ?? "";
// if(isset($_GET["psp"]) && $_GET["psp"]!=''){
//     $query .= " AND ".$_GET["psp"]." IN (Select pspId from tblpatientdetails where tblpatientdetails.pId=tblpatient.id)";
// }
 $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
$patients = $stmt->fetchAll();
function getPatientStatusx($pdo,$id){
  $stmt1 = $pdo->prepare("SELECT StatusName from tblpatientstatus where StatusID=?");
  $stmt1->execute([$id]);
  $patientDetails = $stmt1->fetchColumn();
  return $patientDetails; 
}
?>
<style>
    .enrollment-container {
        max-width: 90%;
        margin: 0 auto;
        padding: 32px 30px;
    }
    
    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 32px;
    }
    
    .page-title {
        font-size: 28px;
        font-weight: 700;
        color: #1a202c;
        margin-bottom: 8px;
    }
    
    .page-subtitle {
        font-size: 15px;
        color: #718096;
    }
    
    .header-actions {
        display: flex;
        gap: 12px;
    }
    
    .btn-add-patient {
        background: linear-gradient(135deg, #1a70b8 0%, #60e438 100%);
        color: white;
        padding: 12px 24px;
        border-radius: 10px;
        text-decoration: none;
        font-weight: 600;
        font-size: 15px;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        transition: all 0.3s ease;
        box-shadow: 0 2px 8px rgba(26, 112, 184, 0.3);
        border: none;
    }
    
    .btn-add-patient:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(26, 112, 184, 0.4);
        color: white;
    }
    
    .patients-card {
        background: white;
        border-radius: 16px;
        padding: 28px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    }
    
    .table-responsive {
        overflow-x: auto;
    }
    
    @media (max-width: 768px) {
        .page-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 16px;
        }
        
        .header-actions {
            width: 100%;
            flex-direction: column;
        }
        
        .btn-add-patient {
            width: 100%;
            justify-content: center;
        }
    }
</style>

<div class="main-content">
    <div class="enrollment-container">
        <div class="page-header">
            <div>
                <h1 class="page-title">Patient Enrollment</h1>
                <p class="page-subtitle">Manage patient enrollments and records</p>
            </div>
            <div class="header-actions">
                <a href="add_patient.php" class="btn-add-patient">
                    <i class="fas fa-plus-circle"></i>
                    Add New Patient
                </a>
                <a href="add_existing_patient.php" class="btn-add-patient" style="background: linear-gradient(135deg, #8b5cf6 0%, #a78bfa 100%);">
                    <i class="fas fa-user-plus"></i>
                    Add Existing
                </a>
            </div>
        </div>

        <div class="patients-card">
            <div class="table-responsive">

                                    <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 foreach($patients as $pd){  

                                        $stmt = $pdo->prepare("SELECT * FROM tblwcpart5 where pId=? and fileId = ?");
                                        $stmt->execute([$pd['pId'],$pd['fileId']]);
                                        $pdi= $stmt->fetch();    //PrescriptionDrugInformation   
                                        ?> 
                                        <tr>
                                        <td class="text-center"><?= isset($pd['createdDate']) ? date('Y-m-d', strtotime($pd['createdDate'])) : ''; ?></td>
                                        <td class="text-center"><?=$pd['krollId'];?></td>
                                         <td class="text-center"><?=$pd['patientId'];?></td>
                                        <td><?=$pd['firstName'];?></td>
                                        <td><?=$pd['lastName'];?></td>
                                        <td class="text-center"><?=$pd['dob'];?></td>
                                        <td class="text-center"><?=getProvince($pdo,'provinceCode','provinceName',$pd['province']);?></td>
                                        <!-- <td><?= trim(explode('-',$pdi['patientDrugName'])[0]); ?></td> -->
                                        <!--<td><?=trim(explode('-',$pdi['patientDrugName'])[0]); ?></td>-->
                                        <td><?=trim(explode(' -',$pdi['patientDrugName'])[0]); ?></td>
                                        
                                        <td><?= isset($pdi['prescriberName']) ? $pdi['prescriberName'] : ''; ?></td>
                                        <!--<td><?= isset($pdi['prescriberSpecialty']) ? $pdi['prescriberSpecialty'] : ''; ?></td>-->
                                        <!--<td><?= isset($pdi['team']) ? $pdi['team'] : ''; ?></td>-->
                                        <td><?= isset($pd['pStatus']) ? getPatientStatusx($pdo,$pd['pStatus']) : ''; ?></td>
                                        <td class="text-center"><?= isset($pdi['staff']) ? $pdi['staff'] : ''; ?></td>
                                            <td class="text-center">
                                               <a href="edit_patient.php?id=<?=$pd['pId'];?>&fileId=<?=$pd['fileId'];?>&isTransferOut=<?=$pd['isTransferOut'];?>" class="btn btn-sm btn-info" title="Edit Patient">
                                                   <i class="fas fa-edit"></i> Edit
                                               </a>
                                            </td>
                                        </tr>
                                        <?php } ?>
                                    </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>
                    </div>
                </div>
            </div>

<script>
    $(document).ready(function() {
        $('#example').DataTable({
            "order": [],
            "pageLength": 100,
            "responsive": true,
            "autoWidth": false
        });
    });
</script>

<?php include('../footer.php'); ?>