<?php


function createNotification($userId = null, $pId = null, $fileId = null, $sendPush = true, $notificationType = null) {
    global $pdo;
    error_log('notificationInitiated on function line 730');
    // createdBy from session if available
    $createdBy = $_SESSION['empId'] ?? null;

    if (empty($notificationType)) {
        return ['success' => false, 'error' => 'notificationType is required'];
    }

    try {
        // fetch notification template
        $stmt1 = $pdo->prepare("SELECT title, message, receivers, `type` AS notif_type FROM tblnotificationtypes WHERE isDeleted = 'N' AND notificationType = ?");
        $stmt1->execute([$notificationType]);
        $result = $stmt1->fetch(PDO::FETCH_ASSOC);

        if (!$result) {
            error_log('notification Initiated Notification type not found');

            return ['success' => false, 'error' => 'Notification type not found'];
        }

        $title = $result['title'] ?? '';
        $message = $result['message'] ?? '';
        // prefer explicit type column, else fallback to the notificationType string
        $type = $result['notif_type'] ?? $notificationType;
        $receivers = $result['receivers'] ?? '';

        // Build recipient list
        $recipientIds = [];

        // If caller supplied a specific user, respect that first
        if (!empty($userId)) {
            $recipientIds[] = (int)$userId;
        } else {
            // Handle known receivers. Expand these cases as needed.
            if (strtolower($receivers) === 'pharmacist') {
                // Assumes tbluser has empId, userRole (comma-separated) and department fields.
                // Adjust condition to match your schema/business rules for identifying pharmacists.
                $stmt = $pdo->prepare("SELECT empId FROM tbluser WHERE isDeleted = 'N' AND FIND_IN_SET('P', userRole) AND department = 'P'");
                $stmt->execute();
                $rows = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
                if ($rows) $recipientIds = array_map('intval', $rows);
            } elseif (strtolower($receivers) === 'allemployees') {
                $stmt = $pdo->prepare("SELECT empId FROM tbluser WHERE isDeleted = 'N'");
                $stmt->execute();
                $rows = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
                if ($rows) $recipientIds = array_map('intval', $rows);
            } elseif (strtolower($receivers) === 'patient') {
                // If notifications for the patient, map patient id to user id if you maintain a mapping.
                // // Example: assume tblpatient has a user_id column — adjust to your schema.
                // if ($pId) {
                //     $stmt = $pdo->prepare("SELECT user_id FROM tblpatient WHERE id = ? AND isDeleted = 'N'");
                //     $stmt->execute([$pId]);
                //     $uid = $stmt->fetchColumn();
                //     if ($uid) $recipientIds[] = (int)$uid;
                // }
            } elseif (strtolower($receivers) === 'ae_creator') {
                $recipientIds[] = (int)$userId;
            } elseif (strtolower($receivers) === 'admin') {
                // Get all admin users (empType = 'A' or 'S')
                $stmt = $pdo->prepare("SELECT empId FROM tbluser WHERE isDeleted = 'N' AND (empType = 'A')");
                $stmt = $pdo->prepare("SELECT empId FROM tbluser WHERE isDeleted = 'N' AND empId='172'");
                $stmt->execute();
                $rows = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
                if ($rows) $recipientIds = array_map('intval', $rows);
            } elseif (strtolower($receivers) === 'pv_team') {
                // Get PV team members - users with 'PV' in their userRole
                // userRole is comma-separated, so we use FIND_IN_SET
                $stmt = $pdo->prepare("SELECT empId FROM tbluser WHERE isDeleted = 'N' AND FIND_IN_SET('PV', userRole)");
                $stmt = $pdo->prepare("SELECT empId FROM tbluser WHERE isDeleted = 'N' AND empId='172'");

                $stmt->execute();
                $rows = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
                if ($rows) $recipientIds = array_map('intval', $rows);
            } else {
                // Generic: no special receivers found — you can extend for other receiver values.
            }
        }

        if (empty($recipientIds)) {
            return ['success' => false, 'error' => 'No recipients found for this notification'];
        }

        // Insert notifications in a transaction
        $pdo->beginTransaction();

        $insertStmt = $pdo->prepare("INSERT INTO tblnotifications (user_id, title, message, type, pId, fileId, is_read, created_at, createdBy, isDeleted) VALUES (?, ?, ?, ?, ?, ?, 0, NOW(), ?, 'N')");

        $insertedIds = [];
        
        foreach ($recipientIds as $rid) {
            $insertStmt->execute([$rid,$title,$message,$type,$pId,$fileId,$createdBy]);
            $insertedIds[] = $pdo->lastInsertId();
        }

        $pdo->commit();

        // Try sending push notifications (don't roll back the DB insert if push fails)
        if ($sendPush) {
            error_log('send push initiated');

            foreach ($recipientIds as $rid) {
                try {
                    // sendPushNotification should accept (userId, title, message, type, pId, fileId)
                    // Ensure that function exists and handles errors internally.
                    sendPushNotification($rid, $title, $message, $type, $pId, $fileId);
                } catch (Exception $e) {
                    error_log("Push notification failed for user {$rid}: " . $e->getMessage());
                    // continue sending to others
                }
            }
        }

        return [
            'success' => true,
            'notification_ids' => $insertedIds,
            'message' => 'Notification(s) created successfully'
        ];
    } catch (PDOException $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        error_log('Error creating notification: ' . $e->getMessage());
        return [
            'success' => false,
            'error' => 'Failed to create notification'
        ];
    }
}


function sendPushNotification($userId, $title, $message, $type = 'info', $pId, $fileId) {
    global $pdo;
    
    try {
        // Get user's push subscriptions
        $stmt = $pdo->prepare("
            SELECT endpoint, publicKey, authToken, contentEncoding
            FROM push_subscriptions
            WHERE user_id = ?
        ");
        $stmt->execute([$userId]);
        $subscriptions = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($subscriptions)) {
            return ['success' => false, 'message' => 'No push subscriptions found'];
        }
        
        // Load VAPID keys
        $vapidPublicKey = trim(file_get_contents(__DIR__ . '/notifications/pushnotificationv1/keys/public_key.txt'));
        $vapidPrivateKey = trim(file_get_contents(__DIR__ . '/notifications/pushnotificationv1/keys/private_key.txt'));
        
        $auth = [
            'VAPID' => [
                'subject' => 'mailto:admin@rxconnect.ca',
                'publicKey' => $vapidPublicKey,
                'privateKey' => $vapidPrivateKey,
            ],
        ];
        
        $webPush = new WebPush($auth);
        
        // Build notification URL
        $url = '/rxcrm/';
        if ($pId && $fileId) {
            $url = "/rxcrm/pharmacy/edit_patient.php?id={$pId}&fileId={$fileId}";
        } else {
            $url = "/rxcrm/";
        }
        
        // Build payload
        $payload = json_encode([
            'title' => $title,
            'message' => $message,
            'type' => $type,
            'icon' => '/rxcrm/notifications/icons/info.png',
            'badge' => '/rxcrm/notifications/icons/info.png',
            'url' => $url,
            'tag' => 'notification-' . time(),
            'timestamp' => time() * 1000,
            'requireInteraction' => $type === 'error' || $type === 'warning',
            'actions' => [
                ['action' => 'view', 'title' => 'View', 'icon' => '/rxcrm/notifications/icons/info.png'],
                ['action' => 'close', 'title' => 'Close', 'icon' => '/rxcrm/notifications/icons/delete.png'],
            ]
        ]);
        
        $sentCount = 0;
        $failedCount = 0;
        
        foreach ($subscriptions as $sub) {
            $subArray = ['endpoint' => $sub['endpoint']];
            if (!empty($sub['publicKey']) && !empty($sub['authToken'])) {
                $subArray['keys'] = [
                    'p256dh' => $sub['publicKey'],
                    'auth' => $sub['authToken']
                ];
            }
            
            try {
                $subscription = Subscription::create($subArray);
                $report = $webPush->sendOneNotification($subscription, $payload);
                
                if ($report->isSuccess()) {
                    $sentCount++;
                } else {
                    $failedCount++;
                    $reason = $report->getReason();
                    
                    // Remove expired subscriptions
                    if (is_string($reason) && (
                        stripos($reason, '410') !== false || 
                        stripos($reason, '404') !== false || 
                        stripos($reason, 'gone') !== false
                    )) {
                        $delStmt = $pdo->prepare('DELETE FROM push_subscriptions WHERE endpoint = ?');
                        $delStmt->execute([$sub['endpoint']]);
                    }
                }
            } catch (Exception $e) {
                $failedCount++;
                error_log('Push notification error: ' . $e->getMessage());
            }
        }
        
        return [
            'success' => true,
            'sent' => $sentCount,
            'failed' => $failedCount,
            'total' => count($subscriptions)
        ];
        
    } catch (Exception $e) {
        error_log('Error sending push notification: ' . $e->getMessage());
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}



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 getVersion($form_id){
    global $pdo;
  $stmt1 = $pdo->prepare("SELECT version from tblconsentversions where form_id=?");
  $stmt1->execute([$form_id]);
  $patientDetails = $stmt1->fetchColumn();
  return $patientDetails;
}
function getPatientSubStatus($pdo,$patientSubStatus){
  $stmt1 = $pdo->prepare("SELECT SubstatusName from tblpatientsubstatus where SubstatusID=?");
  $stmt1->execute([$patientSubStatus]);
  $patientDetails = $stmt1->fetchColumn();
  return $patientDetails; 
}
// function added to get name of selected reason form reimbursemnt status when form is prepopulated for FK files.
function getReimbursementReason($pdo,$patientSubStatus){
  $stmt1 = $pdo->prepare("SELECT name from tblreimbursementreason where id=?");
  $stmt1->execute([$patientSubStatus]);
  $patientDetails = $stmt1->fetchColumn();
  return $patientDetails;
}
function getPatientStatus($pdo,$id){
  $stmt1 = $pdo->prepare("SELECT StatusName from tblpatientstatus where StatusID=?");
  $stmt1->execute([$id]);
  $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 getpatientInitials($pId){
  global $pdo;
  $stmt1 = $pdo->prepare("SELECT patientName from tblpatient where id=?");
  $stmt1->execute([$pId]);
  $patientDetails = $stmt1->fetch();
  //return getInitials();
  return implode('', array_map(function($part) { return strtoupper(substr($part, 0, 1)); }, explode(' ',$patientDetails['patientName'])));
  // Echo the JSON response
}
function getpatientDob($pId){
  global $pdo;
  $stmt1 = $pdo->prepare("SELECT dob from tblpatient where id=?");
  $stmt1->execute([$pId]);
  $patientDetails = $stmt1->fetchColumn();
  //return getInitials();
  return $patientDetails;
  // Echo the JSON response
}
function getpatientDrugName($pId,$fileId){
      global $pdo;
  $stmt1 = $pdo->prepare("SELECT patientDrugName from tblwcpart5 where pId=? and fileId=?");
  $stmt1->execute([$pId,$fileId]);
  $patientDetails = $stmt1->fetchColumn();
  //return getInitials();
  return $patientDetails;
}

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", 
//       "13" => "N.A.",
//       "14" => "Transfer In – Follow Up Call",
//       "15" => "Transfer in – Call Complete",
//       "16" => "First Reattempt Contact Attempted",
//       "17" => "Second Reattempt Contact Attempted"
//   ];
//   // 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 "New - Patient Not Yet Contacted";
// }
function getWelcomeCallStatus($id){
    global $pdo;
    $data='';
    if(isset($id)){
        $stmt1 = $pdo->prepare("Select title from tblwelcomecallstatus where isDeleted='N' and id=?");
        $stmt1->execute([$id]);
        $data=$stmt1->fetchColumn();
    }
  // Check if the id exists in the options array and return the corresponding text
  if (isset($data) && $data!='') {
      return $data;
  }
  // Return a default message if the id is not found
  return "New - Patient Not Yet Contacted";
}
// 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", 
//       "13" => "N.A.",
//       "14" => "New Transfer In - Follow Up Call",
//       "15" => "Transfer in – Call Complete",
//       "16" => "First Reattempt Contact Attempted",
//       "17" => "Second Reattempt Contact Attempted"
//   ];
//   // 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 "New - Patient Not Yet Contacted";
// }
function getReimbursementStatus($id) {
    global $pdo;
    $stmt1 = $pdo->prepare("SELECT name from tblreimbursementstatus where id=?");
    $stmt1->execute([$id]);
    $patientDetails = $stmt1->fetchColumn();
    //return getInitials();
    if($patientDetails){
        return $patientDetails; 
    }
    return "";
}

function getPhysicianName($id) {
    global $pdo;
    $stmt1 = $pdo->prepare("SELECT firstName,lastName from tblphysicians where id=?");
    $stmt1->execute([$id]);
    $patientDetails = $stmt1->fetch();
    //return getInitials();
    if($patientDetails){
    return $patientDetails['firstName']." ".$patientDetails['lastName']; 
    }
    return '';
}

function getPhysicianType($id) {
    global $pdo;
    $stmt1 = $pdo->prepare("SELECT physicianType from tblphysicians where id=?");
    $stmt1->execute([$id]);
    $patientDetails = $stmt1->fetch();
    //return getInitials();
    if($patientDetails){
    return $patientDetails['physicianType']; 
    }
    return '';
}

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
 }
   if (isset($_SESSION['empType'], $_SESSION['department'])) {
        $currentUrl = $_SERVER['REQUEST_URI'];
        if ($_SESSION['empType'] == 'E' && $_SESSION['department'] != 'P' && strpos($currentUrl, '/pharmacy/') == true) {
            header("Location: ../access_denied.php"); 
        }
       
   }
// End output buffering and flush output
}
function disable_inputs() {
    // Check conditions using session variables
    if (isset($_SESSION['empType'], $_SESSION['department'])) {
        $currentUrl = $_SERVER['REQUEST_URI'];
        
        // 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'] == 'R' && 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 nullIfEmpty($val) {
    return $val === '' ? null : $val;
}
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!";
    }
}

// get master detail functions:

// FastStartCriteria
function getFastStartCriteria($pdo,$pspid){
    $stmt1 = $pdo->prepare("Select * from tblfaststartcriteria where tblfaststartcriteria.isActive='Y' and pspId=?");
    $stmt1->execute([$pspid]);
    return $stmt1->fetchAll();
}

// patientStatusCRM
function getPatientStatusCRM($pdo){
    $stmt1 = $pdo->prepare("Select * from tblpatientstatuscrm where tblpatientstatuscrm.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// appealStatus
function getAppealStatus($pdo){
    $stmt1 = $pdo->prepare("Select * from tblappealstatus where tblappealstatus.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// planMaxPeriod
function getPlanMaxPeriod($pdo){
    $stmt1 = $pdo->prepare("Select * from tblplanmaxperiod where tblplanmaxperiod.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// saStatus
function getSaStatus($pdo){
    $stmt1 = $pdo->prepare("Select * from tblsastatus where tblsastatus.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// saResult
function getSaResult($pdo){
    $stmt1 = $pdo->prepare("Select * from tblsaresult where tblsaresult.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// saResultReasonNA
function getSaResultReasonNA($pdo){
    $stmt1 = $pdo->prepare("Select * from tblsaresultreasonna where tblsaresultreasonna.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// appealResult
function getAppealResult($pdo){
    $stmt1 = $pdo->prepare("Select * from tblappealresult where tblappealresult.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// appealResultReasonNA
function getAppealResultReasonNA($pdo){
    $stmt1 = $pdo->prepare("Select * from tblappealresultreasonna where tblappealresultreasonna.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// Method of Re-consent
function getMethodofReconsent($pdo){
    $stmt1 = $pdo->prepare("Select * from tblreconsentmethod where tblreconsentmethod.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// Task Status
function getTaskStatusPL($pdo){
    $stmt1 = $pdo->prepare("Select * from tbltaskstatus where tbltaskstatus.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// Priority
function getPriority($pdo){
    $stmt1 = $pdo->prepare("Select * from tblpriority where tblpriority.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// lastActionTaken
function getLastActionTaken($pdo){
    $stmt1 = $pdo->prepare("Select * from tbllastactiontaken where tbllastactiontaken.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// trainingsite
function getTrainingsite($pdo){
    $stmt1 = $pdo->prepare("Select * from tbltrainingsite where tbltrainingsite.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// pharmacyType
function getPharmacyType($pdo){
    $stmt1 = $pdo->prepare("Select DISTINCT(pharmacyType) as data from tblpharmacy where tblpharmacy.pharmacyType is not null and tblpharmacy.isDeleted='N'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// welcome call status
function getWelcomecallstatusPL($pdo){
    $stmt1 = $pdo->prepare("Select * from tblwelcomecallstatus where isDeleted='N'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// tbltasksubject
function getTasksubjectPL($pdo){
    $stmt1 = $pdo->prepare("Select * from tbltasksubject where tbltasksubject.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// tblgender
function getGender($pdo){
    $stmt1 = $pdo->prepare("Select * from tblgender where tblgender.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// tbllatexallergies
function getLatexallergies($pdo){
    $stmt1 = $pdo->prepare("Select * from tbllatexallergies where tbllatexallergies.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// tblrouteofadministration
function getRouteofadministration($pdo){
    $stmt1 = $pdo->prepare("Select * from tblrouteofadministration where tblrouteofadministration.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// tblindicationtype
function getIndicationtype($pdo){
    $stmt1 = $pdo->prepare("Select distinct(name) as name from tblindicationtype where tblindicationtype.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// tblindicationtype
function getIndicationtypeacctomed($pdo,$med){
    if(isset($med) && $med!=''){
        if(strpos($med, " ") !== false)
        {
            $med=explode(" ", $med)[0];
        }
    }
    $stmt1 = $pdo->prepare("Select distinct(name) as name from tblindicationtype where drug=? and tblindicationtype.isActive='Y'");
    $stmt1->execute([$med]);
    return $stmt1->fetchAll();
}

// tblsistatus
function getSIStatus($pdo){
    $stmt1 = $pdo->prepare("Select * from tblsistatus where tblsistatus.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// tblofflabeluse
function getOfflabeluse($pdo){
    $stmt1 = $pdo->prepare("Select * from tblofflabeluse where tblofflabeluse.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// tblofflabeluse
function getCounselingDeclinedReasons($pdo){
    $stmt1 = $pdo->prepare("Select * from tblcounselingdeclinedreasons where tblcounselingdeclinedreasons.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// tblClinicServices
function getClinicServices($pdo){
    $stmt1 = $pdo->prepare("Select * from tblclinicservices where tblclinicservices.isDeleted='N'");
    $stmt1->execute();
    return $stmt1->fetchAll();
    return true;
}
// tblreimbursementplanorder
function getReimbursementPlanOrder($pdo,$pId,$fileId){
    $stmt1 = $pdo->prepare("Select * from tblreimbursementplanorder where isDeleted='N' and name in (Select DISTINCT(tblsahistory.plan) from tblsahistory where tblsahistory.fileId=? and tblsahistory.pId=?)");
    $stmt1->execute([$fileId,$pId]);
    return $stmt1->fetchAll();
}

// tblpspenrollmentreason
function getPspEnrollmentReason($pdo){
    $stmt1 = $pdo->prepare("Select * from tblpspenrollmentreason where isDeleted='N'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}
function getClinicSites($pdo,$service){
    $stmt1 = $pdo->prepare("Select * from tbltrainingsite where tbltrainingsite.isActive='Y' and 'Y' = (case
                            when (?='7') then (tbltrainingsite.isvirtualinjection)
                            when (?='1') then (tbltrainingsite.isclinicinjection)
                            when (?='2') then (tbltrainingsite.isclinicinfusion)
                            end)");
    $stmt1->execute([$service,$service,$service]);
    return $stmt1->fetchAll();
}
function getPatientId($pId,$fileId){
    global $pdo;
        $stmtCheck = $pdo->prepare("SELECT CASE WHEN(tblpatientdetails.isPsp='N') THEN (tblpatientdetails.exPatientId) 
                                ELSE tblpatientdetails.patientId END AS patientId FROM tblpatientdetails WHERE pId = ? AND fileId = ? and isDeleted='N' LIMIT 1");
        $stmtCheck->execute([$pId, $fileId]);
        $check = $stmtCheck->fetchColumn();
        return $check;
}
function getPatientDetails($pdo, $pId, $column) {
    // Prepare a query to fetch emails for the provided recipient IDs
  
  
    $sql = "SELECT $column FROM tblpatient WHERE id =? and isDeleted='N'";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$pId]);
    
    // Fetch all the emails as an array
    return $stmt->fetchColumn();
}

?>