<?php
function getUserEmail($pdo,$empId){
    $stmt1 = $pdo->prepare("SELECT email from tbluser where empId=?");
    $stmt1->execute([$empId]);
    $empDetails = $stmt1->fetchColumn();
    //return getInitials();
    return $empDetails;   
}
function getPatientEmail($pdo, $recipients) {
    // Prepare a query to fetch emails for the provided recipient IDs
  
  
    $sql = "SELECT email FROM tblpatient WHERE id =?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$recipients]);
    
    // Fetch all the emails as an array
    return $stmt->fetchColumn();
}

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 getMonthName($id){
    $employeeNames = [
        1 => "January",
        2 => "February",
        3 => "March",
        4 => "April",
        5 => "May",
        6 => "June",
        7 => "July",
        8 => "August",
        9 => "September",
        10 => "October",
        11 => "November",
        12 => "December"
    ];

    // Check if the ID exists in the array and return the corresponding name
    if (array_key_exists($id, $employeeNames)) {
        return $employeeNames[$id];
    } else {
        return ""; // Default value if ID is not found
    }
}
function getUserInititals($pdo,$empId){
  $stmt1 = $pdo->prepare("SELECT userName from tbluser where empId=?");
  $stmt1->execute([$empId]);
  $patientDetails = $stmt1->fetch();
  //return getInitials();
  return implode('', array_map(function($part) { return strtoupper(substr($part, 0, 1)); }, explode(' ',$patientDetails['userName']))); 
  // Echo the JSON response
}
function getPatientSubStatus($pdo,$patientSubStatus){
  $stmt1 = $pdo->prepare("SELECT SubstatusName from tblpatientsubstatus where SubstatusID=?");
  $stmt1->execute([$patientSubStatus]);
  $patientDetails = $stmt1->fetchColumn();
  return $patientDetails; 
}
function getProvince($pdo,$column,$key,$value){
  $stmt1 = $pdo->prepare("SELECT $column from tblprovince where $key=?");
  $stmt1->execute([$value]);
  $province = $stmt1->fetchColumn();
 
  //return getInitials();
  return $province; 
  // Echo the JSON response
}
function getuserName($pdo,$empId){
  $stmt1 = $pdo->prepare("SELECT userName from tbluser where empId=?");
  $stmt1->execute([$empId]);
  $empDetails = $stmt1->fetchColumn();
  //return getInitials();
  return $empDetails; 
  // Echo the JSON response
}
function getpatientName($pdo,$pId){
  $stmt1 = $pdo->prepare("SELECT patientName from tblpatient where id=?");
  $stmt1->execute([$pId]);
  $empDetails = $stmt1->fetchColumn();
  //return getInitials();
  return $empDetails; 
  // Echo the JSON response
}

function getEmpType($department){
  $result='';
  if($department=='S'){
      $result='Super Admin';
  }
  if($department=='E'){
      $result='Employee';
  }
  if($department=='A'){
      $result='Admin';
  }
  return $result;
  //return getInitials();
  //return implode('', array_map(function($part) { return strtoupper(substr($part, 0, 1)); }, explode(' ',$patientDetails['userName']))); 
  // Echo the JSON response
}

function getDepartment($department){
  $result='';
  if($department=='N'){
      $result='Nursing';
  }
  if($department=='A'){
      $result='Admin';
  }
  if($department=='B'){
      $result='Billing';
  }
  if($department=='P'){
      $result='Pharmacy';
  }
  if($department=='R'){
      $result='Reimbursement';
  }
  if($department=='I'){
      $result='Information Technology';
  }
  return $result;
  //return getInitials();
  //return implode('', array_map(function($part) { return strtoupper(substr($part, 0, 1)); }, explode(' ',$patientDetails['userName']))); 
  // Echo the JSON response
}
function getWelcomeCallStatus($id){
  $options = [
      "1" => "New - Patient Not Yet Contacted",
      "2" => "Pending - 1st Patient Contact Attempted",
      "3" => "Pending - 2nd Patient Contact Attempted",
      "4" => "Pending - 3rd Patient Contact Attempted",
      "5" => "Complete - Contact Complete",
      "6" => "Incomplete - Enrollment Discontinued - Patient Cannot be reached",
      "7" => "Clarification: Waiting for information from prescriber",
      "8" => "PPN: No welcome call required",
      "9" => "Other pharmacy: No welcome call required",
      "10" => "Patient not getting medication - closed",
      "11" => "Entered in error - disregard",
      "12" => "Pending patient update - patient contacted waiting for info"
  ];
  // Check if the id exists in the options array and return the corresponding text
  if (isset($options[$id])) {
      return $options[$id];
  }
  // Return a default message if the id is not found
  return "Pending";
}
function getReimbursementStatus($id) {
  $options = [
      "1" => "Pending - SA Submitted by RX Connect",
      "2" => "Pending - SA Submitted by PSP",
      "3" => "Pending - EAP Submitted",
      "4" => "Pending - Limited Use Code",
      "8" => "Pending - Appeal Submission",
      "11" => "Pending - patient to be enrolled into PSP",
      "12" => "Pending - PSP to initiate SA process",
      "13" => "Pending - patient to provide PSP with more information",
      "14" => "Pending - Patient to provide Rx Connect with more information",
      "15" => "Pending - Patient Signature",
      "16" => "Pending - Physician Signature",
      "17" => "Pending- Insurance decision",
      "10" => "Complete - Free of Charge",
      "6" => "Complete - Coverage Established",
      "24" => "Complete - Coverage Established- PPN",
      "25" => "Complete - Coverage Established - Not using Rx Pharmacy",
      "26" => "Complete- Coverage Established - Not using Rx Connect",
      "27" => "Complete- Compassionate",
      "30" => "Patient prefers local pharmacy - No reimb",
      "7" => "Reimbursement Not Required",
      "18" => "PSP to start EAP process",
      "19" => "Rx Connect to start EAP Process",
      "20" => "Rx Connect to start SA process",
      "21" => "Pending EAP decision",
      "22" => "Patient transferred out",
      "23" => "Pending Medical clearance from MD",
      "37" => "Pending - Screening Test/Immunization"
  ];

  // Check if the id exists in the options array and return the corresponding text
  if (isset($options[$id])) {
      return $options[$id];
  }

  // Return a default message if the id is not found
  return "Pending";
}
function getPatientType($id) {
  $options = [
      "1" => "Clinical Trial",
      "2" => "Commercial",
      "3" => "Commercial - Alt. Dose Free Goods",
      "4" => "Compassionate",
      "5" => "Fast Start - Bridge",
      "6" => "Fast Start - Retro",
      "7" => "Fast Start Criteria Not Met",
      "8" => "Free Goods - Dose Opt",
      "9" => "Lifetime Plan Max",
      "10" => "LOC",
      "11" => "Long Term Bridging - Denial",
      "12" => "Long Term Bridging - No Payer Access",
      "13" => "Low Annual Max",
      "14" => "SA Lapse",
      "15" => "SA Lapse - Retro",
      "16" => "Short Term Bridging/ Limited Timeframe",
      "17" => "Undefined / Missing Information"
  ];
  // Check if the id exists in the options array and return the corresponding text
  if (isset($options[$id])) {
      return $options[$id];
  }

  // Return a default message if the id is not found
  return "";
}
function getTaskStatus($id) {
  $options = [
      "1" => "New",
      "2" => "In Progress",
      "3" => "Completed",
      "4" => "Cancelled"
  ];
  // Check if the id exists in the options array and return the corresponding text
  if (isset($options[$id])) {
      return $options[$id];
  }
  // Return a default message if the id is not found
  return "";
}
function getTaskPriority($id) {
  $options = [
      "1" => "Low",
      "2" => "Medium",
      "3" => "High",
      "4" => "Critical"
  ];
  // Check if the id exists in the options array and return the corresponding text
  if (isset($options[$id])) {
      return $options[$id];
  }
  // Return a default message if the id is not found
  return "";
}
function getTaskSubject($id) {
  $options = [
      "1" => "SA Renewal",
      "2" => "Welcome Call"
  ];
  // Check if the id exists in the options array and return the corresponding text
  if (isset($options[$id])) {
      return $options[$id];
  }
  // Return a default message if the id is not found
  return "";
}
function asDollars($value) {
  if ($value<0) return "-".asDollars(-$value);
  return '$' . number_format($value, 2);
}
function asDollarsx($value) {
  if ($value < 0) return "-".asDollars(-$value);
  return  number_format($value, 2);
}

function checkAccessAndRedirect($url) {
  // Start output buffering
 $hasAccess = true; // User has access by default
 if (isset($_SESSION['empType']) && $_SESSION['empType'] == 'E') {
     // Parse the URL to get its components
     $urlComponents = parse_url($url);
     
     // Handle cases where there might be a query string
     if (!isset($urlComponents['path'])) {
         return; // No path means no access restriction
     }
     $path = $urlComponents['path'];
     
     // Split the path into tokens
     $tokens = explode('/', trim($path, '/'));
     
     // Reconstruct the page URL safely
     if (count($tokens) >= 2) {
         $pageUrl = $tokens[count($tokens) - 2] . "/" . end($tokens);
     } else {
         // If only one token (root directory case)
         $pageUrl = end($tokens);
     }
     
     // Convert everything to lowercase to avoid case mismatch
     $pageUrl = strtolower($pageUrl);
     $restrictedPages = array_map('strtolower', [
         "billing/index.php", "billing/psps.php", "billing/add_psp.php", 
         "billing/drugs.php", "billing/add_drug.php", "billing/edit_drug.php",
         "billing/service_pricing.php", "billing/services.php", "billing/add_service.php",
         "billing/edit_service.php", "billing/generalreports.php", "billing/servicereports.php",
         "billing/drugreports.php", "billing/reports.php", "employees.php"
     ]);
     
     // Check if the constructed URL or filename is restricted
     if (in_array($pageUrl, $restrictedPages) || in_array(end($tokens), $restrictedPages)) {
         $hasAccess = false;
     }
 }
 
 // If user does not have access, redirect to the access denied page
 if (!$hasAccess) {
      if (count($tokens) >= 1) {

          header("Location:../access_denied.php");
     } else {
         // If only one token (root directory case)
         header("Location: access_denied.php");
     }
     
     exit(); // Stop further execution
 }
// End output buffering and flush output
}
function disable_inputs() {
    // Check conditions using session variables
    if (isset($_SESSION['empType'], $_SESSION['department'])) {
        $currentUrl = $_SERVER['REQUEST_URI'];
        
        // Redirect if empType is 'E' and page is /de/edit_patient.php
        if ($_SESSION['empType'] == 'E' && strpos($currentUrl, '/de/edit_patient.php') !== false) {
            header("Location: access_denied.php");
            exit;
        }
        
        // If empType is E and department is P, disable inputs for URLs containing '/reimbursement/'
        if ($_SESSION['empType'] == 'E' && $_SESSION['department'] == 'P' && strpos($currentUrl, '/reimbursement/') !== false) {
            echo "<script>
                window.onload = function() {
                    var inputs = document.querySelectorAll('input[type=\"text\"], input[type=\"radio\"], input[type=\"checkbox\"], input[type=\"date\"], textarea, select');
                    inputs.forEach(function(input) {
                        input.disabled = true;
                    });
                };
            </script>";
        }
        
        // If empType is E and department is N, disable inputs for URLs containing '/pharmacy/'
        if ($_SESSION['empType'] == 'E' && $_SESSION['department'] == 'N' && strpos($currentUrl, '/pharmacy/') !== false) {
            echo "<script>
                window.onload = function() {
                    var inputs = document.querySelectorAll('input[type=\"text\"], input[type=\"radio\"], input[type=\"checkbox\"], input[type=\"date\"], textarea, select');
                    inputs.forEach(function(input) {
                        input.disabled = true;
                    });
                };
            </script>";
        }
    }
}

function logOperation($pdo, $empId, $operationType, $tableName, $recordId = null, $fileId = null, $details = '') {
  $stmt = $pdo->prepare('INSERT INTO tblactivitylogs (empId, operation_type, table_name, record_id, fileId, details) VALUES (?, ?, ?, ?, ?, ?)');
  $result = $stmt->execute([$empId, $operationType, $tableName, $recordId, $fileId, $details]);
  if (!$result) {
      echo 'Error logging operation: ' . $stmt->errorInfo()[2];
  }
  $stmt->closeCursor();
}
function updateActivity($operationName,$empId,$pId,$fileId,$patientType,$pdo){
    if(!empty($patientType)){
  $stmt = $pdo->prepare('INSERT INTO tblstatuslogs (operationName, empId, pId, fileId, statusValue) VALUES (?, ?, ?, ?, ?)');
  $result = $stmt->execute([$operationName, $empId, $pId, $fileId, $patientType]);
  if (!$result) {
      echo 'Error logging operation: ' . $stmt->errorInfo()[2];
  }
  $stmt->closeCursor();
}
}

// Usage example:
$url = $_SERVER['REQUEST_URI']; // Get the current URL
checkAccessAndRedirect($url);
disable_inputs();



function generateNumericOTP($n)
{
  
  // Taking a generator string that consists of 
  // all the numeric digits 
  $generator = "135792468";
  
  // Iterating for n-times and pick a single character 
  // from generator and append it to $result 
  
  // Login for generating a random character from generator 
  //     ---generate a random number 
  //     ---take modulus of same with length of generator (say i) 
  //     ---append the character at place (i) from generator to result 
  
  $result = "";
  
  for ($i = 1; $i <= $n; $i++) {
    $result .= substr($generator, (rand() % 4), 1);
  }
  
  // Returning the result 
  return $result;
}

function GenerateRandomColor()
{
    $color = '#';
    $colorHexLighter = array("9","A","B","C","D","E","F" );
    for($x=0; $x < 6; $x++):
        $color .= $colorHexLighter[array_rand($colorHexLighter, 1)]  ;
    endfor;
    return substr($color, 0, 7);
}

function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
    $file = $path.$filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";
    $header .= "--".$uid."--";
    if (mail($mailto, $subject, "", $header)) {
    echo "mail send ... OK"; // or use booleans here
    } else {
    echo "mail send ... ERROR!";
    }
}

?>