<?php
include('connect.php');

session_start();
if(!isset($_SESSION['clientName'])){
    header("location: login.php");
}
$clientName = isset($_SESSION['clientName']) ? $_SESSION['clientName'] : 'Client';


function sanitizeDate($date) {
    return ($date === '0000-00-00' || empty($date)) ? '' : date('Y-m-d', strtotime($date));
}
function sanitizePercentage($input) {
    // Use regex to find a number with an optional decimal part
    if (preg_match('/\d+(\.\d+)?/', $input, $matches)) {
        $value = floatval($matches[0]);
        // Clamp the value to the 0-100 range
        if ($value < 0) {
            return 0;
        } elseif ($value > 100) {
            return 100;
        }
        return $value;
    }
    // Return 0 if no numeric value is found
    return 0;
}
function getProvinceCode($province) {
    global $pdo;
   $stmt = $pdo->prepare("SELECT provinceCode from tblprovince  WHERE provinceName=?");                             
                        $stmt->execute([$province]);
                        return $stmt->fetchColumn();
}
function checkExist($innomarPatientId) {
    global $connx;
    $stmtx = $connx->prepare("SELECT COUNT(*) FROM Patient_Detail_Report WHERE Patient_Number = ?");                    
    $stmtx->execute([$innomarPatientId]);
    $count = $stmtx->fetchColumn();

    return $count > 0 ? 'Exist' : 'Does not exist';
}

function getComDate($innomarPatientId){
    global $connx;
    $stmtx = $connx->prepare("SELECT SA_Result_Date from reimbursements_sa  WHERE Patient_ID_Number__c=? and SA_Status=? and SA_Result_Date!=''  LIMIT 1");                    
    $active='Active';
    $stmtx->execute([$innomarPatientId,$active]);
    return $stmtx->fetchColumn();
}
function getPlanType($payer){
    global $connx;
    $stmtx = $connx->prepare("SELECT `Plan Type` from Reimbursement_History  WHERE `Payer Name` = ?");                    
  
    if($stmtx->execute([$payer])){
    return $stmtx->fetchColumn();
    }else{
        return '-';
    }
    
    
}
function getFSA($postalCode) {
    // Remove any spaces or special characters from the postal code
    $postalCode = strtoupper(preg_replace('/\s+/', '', $postalCode));

    // Check if the postal code is valid (Canadian postal codes are 6 characters long, e.g., A1A1A1)
    if (strlen($postalCode) >= 3) {
        // Extract the first 3 characters (FSA)
        return substr($postalCode, 0, 3);
    }

    // Return an empty string or handle invalid postal codes
    return '';
}
function getPrimaryDiagnosiss($stringofdiagnosis, $innomarPatientId) {
    global $connx;
   
    // Check if a diagnosis string was provided.
    if (trim($stringofdiagnosis) !== "") {
        
        // Split the string by commas to get the first diagnosis.
        $diagnosisArray = explode(',', $stringofdiagnosis);
        $primaryDiagnosis = trim($diagnosisArray[0]); // Get first diagnosis and trim spaces

        // Diagnosis mapping for values provided in the string.
        $diagnosisMap = [
            'AD'     => 'Atopic Dermatitis',
            'PN'     => 'Prurigo nodularis',
            'Asthma' => 'Asthma',
            'CRSwNP' => 'Chronic Rhinosinusitis with Nasal Polyposis',
            'EOE'    => 'Eosinophilic esophagitis'
        ];
        
        // Return mapped diagnosis or 'Unknown' if not found.
        return $diagnosisMap[$primaryDiagnosis] ?? 'Unknown';
    } else {
         
        // If the diagnosis string is empty, fetch it from the Patient_Detail_Report table.
        $stmt = $connx->prepare("
            SELECT `Primary Diagnosis` 
            FROM Patient_Detail_Report
            WHERE Patient_Number = ?
            LIMIT 1
        ");
        $stmt->execute([$innomarPatientId]);
        $primaryDiagnosisFromDB = $stmt->fetchColumn();
        // Return the diagnosis fetched from the DB (assumed to be already mapped).
        return $primaryDiagnosisFromDB;
    }
}

function getDosage($innomarPatientId){
    global $connx;
    
    // Prepare and execute the query
    $stmtx = $connx->prepare("SELECT Prescribed_Dosage FROM patient_dosage WHERE Patient_ID_Number__c=? ORDER BY Created_Date DESC LIMIT 1");                  
    $stmtx->execute([$innomarPatientId]);
    
    // Fetch the dosage
    $dosage = $stmtx->fetchColumn();
    
    // Check if the dosage is 600 and return 300 instead
    if ($dosage == 600) {
        return 300;
    }
    
    // Otherwise, return the fetched dosage
    return $dosage;
}
function getFrequency($innomarPatientId){
     global $connx;
    
    // Prepare and execute the query
    $stmtx = $connx->prepare("SELECT Frequency_Type,Frequency_UOM FROM patient_dosage WHERE Patient_ID_Number__c=? ORDER BY Created_Date DESC LIMIT 1");                  
    $stmtx->execute([$innomarPatientId]);
    
    // Fetch the dosage
    $fre = $stmtx->fetch();
    $frequencyType=$fre['Frequency_Type'];
    $Frequency_UOM=$fre['Frequency_UOM'];
    $frequency=$frequencyType.' '.$Frequency_UOM;
    // Check if the dosage is 600 and return 300 instead
  
    
    // Otherwise, return the fetched dosage
    return $frequency;
}
function getPatientTypeNew($innomarPatientId){
         global $connx;
    
    // Prepare and execute the query
    $stmtx = $connx->prepare("SELECT Patient_Type FROM patient_therapy WHERE Patient_ID_Number__c=? ORDER BY Created_Date DESC LIMIT 1");                  
    $stmtx->execute([$innomarPatientId]);
    
    // Fetch the dosage
    $fre = $stmtx->fetchColumn();
  
    // Check if the dosage is 600 and return 300 instead
  
    
    // Otherwise, return the fetched dosage
    return $fre;
}
function getChangeReason($innomarPatientId){
         global $connx;
    
    // Prepare and execute the query
    $stmtx = $connx->prepare("SELECT Patient_Type_Change_Reason FROM patient_therapy WHERE Patient_ID_Number__c=? ORDER BY Created_Date DESC LIMIT 1");                  
    $stmtx->execute([$innomarPatientId]);
    
    // Fetch the dosage
    $fre = $stmtx->fetchColumn();
  
    // Check if the dosage is 600 and return 300 instead
  
    
    // Otherwise, return the fetched dosage
    return $fre;
}

function getSubstatus($innomarPatientId){
     global $connx;
    
    // Prepare and execute the query
    $stmtx = $connx->prepare("SELECT New_Sub_Status FROM patient_status WHERE Patient_ID_Number__c=? and New_Sub_Status!='' ORDER BY Created_Date DESC LIMIT 1");                  
    $stmtx->execute([$innomarPatientId]);
    
    // Fetch the dosage
    $fre = $stmtx->fetchColumn();
  
    // Check if the dosage is 600 and return 300 instead
  
    
    // Otherwise, return the fetched dosage
    return $fre;
}
function getStatus($innomarPatientId){
     global $connx;
    
    // Prepare and execute the query
    $stmtx = $connx->prepare("SELECT New_Status FROM patient_status WHERE Patient_ID_Number__c=? and New_Status!='' ORDER BY Created_Date DESC LIMIT 1");                  
    $stmtx->execute([$innomarPatientId]);
    
    // Fetch the dosage
    $fre = $stmtx->fetchColumn();
  
    // Check if the dosage is 600 and return 300 instead
  
    
    // Otherwise, return the fetched dosage
    return $fre;
}
function getDisDate($innomarPatientId){
     global $connx;
      $stmtx = $connx->prepare("SELECT Created_Date FROM patient_status WHERE Patient_ID_Number__c=? and (New_Status='Discontinued' || New_Status='Dropout') ORDER BY Created_Date DESC LIMIT 1");                  
    $stmtx->execute([$innomarPatientId]);
    
    // Fetch the dosage
    $fre = $stmtx->fetchColumn();
  
    // Check if the dosage is 600 and return 300 instead
  
    
    // Otherwise, return the fetched dosage
    return $fre;
    
}
function getDaysDifference($startDate, $endDate) {
    if (!empty($startDate) && !empty($endDate)) {
        try {
            $start = new DateTime($startDate);
            $end   = new DateTime($endDate);
            return $start->diff($end)->days;
        } catch (Exception $e) {
            // Handle any conversion errors if needed
            return '';
        }
    }
    return '';
}
function getTherapyData($innomarPatientId, $type) {
    global $connx;

    // Prepare and execute the query
    $stmtx = $connx->prepare("
        SELECT 
            DATE(Enrollment_Form_Received_Date) AS Enrollment_Form_Received_Date,
            DATE(Enrolment_Complete_Date) AS Enrolment_Complete_Date,
            DATE(On_Drug_Start_Date) AS On_Drug_Start_Date
        FROM patient_therapy 
        WHERE Patient_ID_Number__c = ? 
        LIMIT 1
    ");
    $stmtx->execute([$innomarPatientId]);

    // Fetch the result
    $result = $stmtx->fetch();
    if ($result) {
        switch ($type) {
            case 'complete':
                return $result['Enrolment_Complete_Date'];
            case 'drugStart':
                return $result['On_Drug_Start_Date'];
            default:
                return $result['Enrollment_Form_Received_Date'];
        }
    } else {
        return '';
    }
}

function getCommercializationDate($innomarPatientId) { 
    global $connx;

    // Step 1: Check Patient_Detail_Report for Commercialization Date
    $stmtCommercialization = $connx->prepare("
        SELECT `Commercialization_Date` 
        FROM Patient_Detail_Report
        WHERE Patient_Number = ?
        LIMIT 1
    ");
    $stmtCommercialization->execute([$innomarPatientId]);
    $commercializationDate = $stmtCommercialization->fetchColumn();

    // If Commercialization Date is found and not empty, return it after formatting
    if (!empty($commercializationDate)) {
        return $commercializationDate; // Convert to YYYY-MM-DD
    }else{
        return '';
    }
}
function getPlanStatusNew($innomarPatientId, $type, $priority) { 
    global $connx;
    if (!in_array($priority, ['1', '2', '3'])) {
        return null; // Invalid priority
    }
     $query = "
        SELECT 
            `Plan Type 1` AS plan1, `Payer Name 1` AS payer1, `Payer Status 1` AS status1, `Payer Decision 1` AS decision1, `Coverage % 1` AS coverage1,
            `Plan Type 2` AS plan2, `Payer Name 2` AS payer2, `Payer Status 2` AS status2, `Payer Decision 2` AS decision2, `Coverage % 2` AS coverage2,
            `Plan Type 3` AS plan3, `Payer Name 3` AS payer3, `Payer Status 3` AS status3, `Payer Decision 3` AS decision3, `Coverage % 3` AS coverage3
        FROM Patient_Detail_Report
        WHERE Patient_Number = ?
        LIMIT 1
    ";

    $planStatus = $connx->prepare($query);
    $planStatus->execute([$innomarPatientId]);
    $planStatusReturn = $planStatus->fetch();

    // Step 2: Return the requested field based on the type and priority
    if ($planStatusReturn) {
        // Dynamically construct the field name based on priority
        $fieldPrefix = [
            '1' => ['plan' => 'plan1', 'payer' => 'payer1', 'status' => 'status1', 'decision' => 'decision1', 'coverage' => 'coverage1'],
            '2' => ['plan' => 'plan2', 'payer' => 'payer2', 'status' => 'status2', 'decision' => 'decision2', 'coverage' => 'coverage2'],
            '3' => ['plan' => 'plan3', 'payer' => 'payer3', 'status' => 'status3', 'decision' => 'decision3', 'coverage' => 'coverage3'],
        ][$priority];

        switch ($type) {
            case 'Coverage_Percentage':
                return $planStatusReturn[$fieldPrefix['coverage']] ?? null;
            case 'Final_Outcome_Status':
                return $planStatusReturn[$fieldPrefix['decision']] ?? null;
            case 'Payer_Insurer_Name':
                return $planStatusReturn[$fieldPrefix['payer']] ?? null;
            case 'Plan_Status':
                return $planStatusReturn[$fieldPrefix['status']] ?? null;
            case 'Plan_Type':
                return $planStatusReturn[$fieldPrefix['plan']] ?? null;
            default:
                return null; // Invalid type
        }
    }

    // Step 3: Return null if no data is found
    return null;
    
}

function mapPayerDecision($decision) {
    // Define the mapping array
    $mapping = [
        "Approved"                                           => "Approved",
        "SA - Approved"                                      => "Approved",
        "Abandoned"                                          => "Abandoned",
        "Pending"                                            => "Pending",
        "PD- Pending additional information from patient"    => "Pending",
        "PD- Pending MD signature"                           => "Pending",
        "PD - Denied"                                        => "Denied",
        "PD - Approved"                                      => "Approved",
        "SA - Denied"                                        => "Denied",
        "SA - Pending insurance decision"                    => "Pending",
        "Approved - Plan Max"                                => "Approved - Plan Max",
        "Denied"                                             => "Denied",
        "PD- Pending Public decision"                        => "Pending",
        "PD - Pending appeal from MD"                        => "Pending",
        "PD - Denied not on formulary"                       => "Denied",
        "SA - Pending initiation"                            => "Pending",
        "Pending insurance verification"                     => "Pending",
        "PD- Pending additional information from insurance"  => "Pending",
        "PD- Pending additional information from MD"         => "Pending",
        "SA - Pending patient signature"                     => "Pending",
        "SA - Appeal required"                               => "Pending",
        "PD- Pending registration"                           => "Pending",
        "SA - Abandon (file close)"                          => "Abandoned",
        "PD- Pending initiation"                             => "Pending",
        "PD - Denied appeal required"                        => "Denied",
        "SA - Denied Din not eligible"                       => "Denied",
        "SA - Pending MD signature"                          => "Pending",
        "SA - Pending additional information from patient"   => "Pending",
        "SA - Denied patient does not meet criteria" => "Denied"

    ];

    // Return the mapped value if it exists, otherwise return the original or "Unknown"
    return isset($mapping[$decision]) ? $mapping[$decision] : $decision;
}

    
function getPlanStatus($innomarPatientId, $type, $priority) {
    global $connx;

    // Validate priority
    if (!in_array($priority, ['1', '2', '3'])) {
        return null; // Invalid priority
    }

    // Step 1: Query the database for plan status details
    $query = "
        SELECT 
            `Plan Type 1` AS plan1, `Payer Name 1` AS payer1, `Payer Status 1` AS status1, `Payer Decision 1` AS decision1, `Coverage % 1` AS coverage1,
            `Plan Type 2` AS plan2, `Payer Name 2` AS payer2, `Payer Status 2` AS status2, `Payer Decision 2` AS decision2, `Coverage % 2` AS coverage2,
            `Plan Type 3` AS plan3, `Payer Name 3` AS payer3, `Payer Status 3` AS status3, `Payer Decision 3` AS decision3, `Coverage % 3` AS coverage3
        FROM Patient_Detail_Report
        WHERE Patient_Number = ?
        LIMIT 1
    ";

    $planStatus = $connx->prepare($query);
    $planStatus->execute([$innomarPatientId]);
    $planStatusReturn = $planStatus->fetch();

    // Step 2: Return the requested field based on the type and priority
    if ($planStatusReturn) {
        // Dynamically construct the field name based on priority
        $fieldPrefix = [
            '1' => ['plan' => 'plan1', 'payer' => 'payer1', 'status' => 'status1', 'decision' => 'decision1', 'coverage' => 'coverage1'],
            '2' => ['plan' => 'plan2', 'payer' => 'payer2', 'status' => 'status2', 'decision' => 'decision2', 'coverage' => 'coverage2'],
            '3' => ['plan' => 'plan3', 'payer' => 'payer3', 'status' => 'status3', 'decision' => 'decision3', 'coverage' => 'coverage3'],
        ][$priority];

        switch ($type) {
            case 'Coverage_Percentage':
                return $planStatusReturn[$fieldPrefix['coverage']] ?? null;
            case 'Final_Outcome_Status':
                return $planStatusReturn[$fieldPrefix['decision']] ?? null;
            case 'Payer_Insurer_Name':
                return $planStatusReturn[$fieldPrefix['payer']] ?? null;
            case 'Plan_Status':
                return $planStatusReturn[$fieldPrefix['status']] ?? null;
            case 'Plan_Type':
                return $planStatusReturn[$fieldPrefix['plan']] ?? null;
            default:
                return null; // Invalid type
        }
    }

    // Step 3: Return null if no data is found
    return null;
}
function getdrugName($pdo,$empId){
  $stmt1 = $pdo->prepare("SELECT drugName from tbldrugs where id=?");
  $stmt1->execute([$empId]);
  $patientDetails = $stmt1->fetch();
  //return getInitials();
  return $patientDetails['drugName']; 
  // Echo the JSON response
}
function getDOPD($innomarPatientId) {
    global $connx; // Assuming you have a PDO connection

    $sql = "SELECT `Date Of Primary Diagnosis` 
            FROM Patient_Detail_Report 
            WHERE Patient_Number = :patientId";

    $stmt = $connx->prepare($sql);
    $stmt->bindParam(':patientId', $innomarPatientId, PDO::PARAM_STR);
    $stmt->execute();

    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    return $result['Date Of Primary Diagnosis'] ?? null;
}
function getClinicalCriteria($innomarPatientId, $columnName) {
    global $connx; // Assuming you have a PDO connection object defined globally
    
    // Validate column name to prevent SQL injection
    $sql = "SELECT `$columnName` 
            FROM `Patient_Detail_Report` 
            WHERE `Patient_Number` = :patientId";

    $stmt = $connx->prepare($sql);
    $stmt->bindParam(':patientId', $innomarPatientId, PDO::PARAM_STR);
    $stmt->execute();

    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    return $result[$columnName] ?? null;
}
function getFindr($OneKeyID){

global $connx; // Assuming you have a PDO connection object defined globally
    
    // Validate column name to prevent SQL injection
    $sql = "SELECT `IMS_ID` 
            FROM physician 
            WHERE OneKey_ID = :OneKeyID";

    $stmt = $connx->prepare($sql);
    $stmt->bindParam(':OneKeyID', $OneKeyID, PDO::PARAM_STR);
    $stmt->execute();

    $result = $stmt->fetchColumn();

    return $result ?? null;
}

function getEarliestCommercializationDate($fileId){
    global $pdo;
    $stmtx = $pdo->prepare("SELECT saEapCom FROM tblsahistory WHERE fileId=? and isDeleted='N' and saEapCom is not NULL and saEapCom != '0000-00-00' ORDER BY saEapCom LIMIT 1");                  
    $stmtx->execute([$fileId]);
    
    // Fetch the dosage
    $fre = $stmtx->fetchColumn();
  
    // Check if the dosage is 600 and return 300 instead
  
    
    // Otherwise, return the fetched dosage
    return $fre;
    
}

