<?php

/***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** 
 * Module Dev Notes:
 *     This module only supports MySQL searches at the moment, but OpenEMR has a fledgeling API
 *     that may (or may not) support CNAM lookups. Possible future feature.
 *
 *
 * Version History:
 *     2013-12-27 initial commit
 *     2013-12-28 minor query edits by lgaetz
 *     2013-12-30 added checkbox to enable/disable lookups, added search priority, added sort by date desc, add number format option by lgaetz
 *     2014-09-03 Removed dependency on deprecated mysql functions
 *
 ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** *****/

class OpenEMR extends superfecta_base {

	public $description = "Searches a MySQL OpenEMR Database - see http://www.open-emr.org/";
	public $version_requirement = "2.11";
	public $source_param = array(
		'DB_Host' => array(
				'description' => 'Host address of the OpenEMR database. (localhost if the database is on the same server as FreePBX)',
				'type' => 'text',
				'default' => 'localhost',
		),
		'DB_Name' => array(
				'description' => 'MySQL Database name of the OpenEMR database',
				'type' => 'text',
				'default' => 'openemr',
		),
		'DB_User' => array(
				'description' => 'Username used to connect to the OpenEMR database',
				'type' => 'text',
				'default' => 'root',
		),
		'DB_Password' => array(
				'description' => 'Password used to connect to the OpenEMR database',
				'type' => 'password',
				'default' => 'passw0rd',
		),
		'Filter_Length' => array(
				'description' => 'The number of rightmost digits to check for a match. Enter zero to disable',
				'type' => 'number',
				'default' => 10,
		),
		'Search_Cell_Number' => array(
				'description' => '1st priority - If enabled, search patient records for cell number and return patient name on match',
				'type' => 'checkbox',
		),
		'Search_Home_Number' => array(
				'description' => '2nd Priority - If enabled and if no match is found with cell number, this option searches home number field and returns patient name on match. This may be undesirable if more than one patient have the same home number.',
				'type' => 'checkbox',
		),		
		'Search_Work_Number' => array(
				'description' => '3rd Priority - If enabled and if no match is found with patient cell or home phone, this option searches the work number field and returns the patient name on match. This may be undesirable if more than one patient have the same employer number.',
				'type' => 'checkbox',
				
		),
		'Result_Format' => array(
				'description' => 'Choose how you want the patient name displayed on the endpoint.',
				'type' => 'select',
				'option' => array(
					1 => 'Last-name, First-name',
					2 => 'First-name Last-name',
				),
		),
		
	);

	function get_caller_id($thenumber, $run_param=array()) {
		$caller_id = null;
		$value = null;
		$sql_params = array();

		//  Connect to database
		if(class_exists('PDO')) {
			$this->DebugPrint("Searching OpenEMR MySQL Database ... ");
			try {
				$dbh = new PDO('mysql:dbname='.$run_param['DB_Name'].';host='.$run_param['DB_Host'], $run_param['DB_User'], $run_param['DB_Password']);
			} catch (PDOException $e) {
				$this->DebugPrint('Connection failed: ' . $e->getMessage());
				return null;
			}
		} else {
			$this->DebugPrint("PDO not present on system...Skipping");
			return null;
		}
		$sth = $dbh->prepare("SET NAMES 'utf8'");
		$sth->execute();

		// trim number to filter length
		if ($run_param['Filter_Length'] != 0) {
			if (strlen($thenumber) > $run_param['Filter_Length']) $thenumber = substr($thenumber, -$run_param['Filter_Length']);
		}

		//  Build regular expression from the number to avoid non-digit characters stored in database
		//  PDO params can't have quote delimiters
		$regex = "[^0-9]*";
		for( $x=0; $x < ((strlen($thenumber))-1); $x++ ) {
			$regex .=  substr($thenumber,$x,1)."[^0-9]*" ;
		}
		$regex = $regex.(substr($thenumber,-1))."([^0-9]+|$)";
		$sql_params[':regex'] = $regex;

		// query database first for cell number
		if ($run_param['Search_Cell_Number']) {
			$query = "SELECT * FROM `patient_data` where `phone_cell` REGEXP :regex ORDER BY `date` DESC LIMIT 1";
			try {
				$sth = $dbh->prepare($query,array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
				$sth->execute($sql_params);
				$wquery_row = $sth->fetch(PDO::FETCH_BOTH);
				
			} catch (PDOException $e) {
				$this->DebugPrint('Connection failed: ' . $e->getMessage());
				return null;
			}
		}

		// search home number if enabled and if no hit on cell
		if ($run_param['Search_Home_Number'] && !$wquery_row) {
			$query = "SELECT * FROM `patient_data` where `phone_home` REGEXP :regex ORDER BY `date` DESC LIMIT 1";
			try {
				$sth = $dbh->prepare($query);
				$sth->execute($sql_params);
				$wquery_row = $sth->fetch(PDO::FETCH_ASSOC);
				
			} catch (PDOException $e) {
				$this->DebugPrint('Connection failed: ' . $e->getMessage());
				return null;
			}
		}

		// search work number if enabled and if no hit on cell or home
		if ($run_param['Search_Work_Number'] && !$wquery_row) {
			$query = "SELECT * FROM `patient_data` where `phone_biz` REGEXP :regex ORDER BY `date` DESC LIMIT 1";
			try {
				$sth = $dbh->prepare($query);
				$sth->execute($sql_params);
				$wquery_row = $sth->fetch(PDO::FETCH_ASSOC);
				
			} catch (PDOException $e) {
				$this->DebugPrint('Connection failed: ' . $e->getMessage());
				return null;
			}
		}


		// Get last & first name if any results are returned from query
		if ($wquery_row && is_array($wquery_row)) {
			if ($run_param['Result_Format'] == '1') {
				$value = trim($wquery_row["lname"].", ".$wquery_row["fname"]);
			}
			elseif ($run_param['Result_Format'] == '2') {
				$value = trim($wquery_row["fname"]." ".$wquery_row["lname"]);
			}
		}

		if(strlen($value) > 0) {
			$caller_id = trim($value);
			return $caller_id;
		}
		else if($debug) {
			$this->DebugPrint("not found");
		}
	}
}
