<?php
	
	if (!defined('BASEPATH'))
    exit('No direct script access allowed');
	
	class ClinicModel extends CI_Model {
		
		function __construct() {
			// Call the Model constructor
			parent::__construct();
			$this->load->database();
			$this->load->library('session');
			
			$this->load->library('email');
		}
		
		public function getClinics() 
		{
			if(!isset($_SESSION["login_type"]) && !isset($_SESSION["user_id"]))
			{
				echo  header('location:'.base_url().'index.php/Login/logout');	
			}
			else
			{
				$login_type = $this->session->userdata('login_type');
				if ($login_type == 'super_admin')
				{
					$session_login_id = $_SESSION['login_id'];
					$sql = 'select * from  tblClinicRegistration';
					$query = $this->db->query($sql);
					$result = $query->result();
					return $result;
				}
			}
		}
		public function getpackages() 
		{
			if(!isset($_SESSION["login_type"]) && !isset($_SESSION["user_id"]))
			{
				echo  header('location:'.base_url().'index.php/Login/logout');	
			}
			else
			{
				$login_type = $this->session->userdata('login_type');
				if ($login_type == 'super_admin')
				{
					$session_login_id = $_SESSION['login_id'];
					$sql = 'select * from  tbl_package';
					$query = $this->db->query($sql);
					$result = $query->result();
					return $result;
				}
			}
		}public function gettemplates() 
		{
			if(!isset($_SESSION["login_type"]) && !isset($_SESSION["user_id"]))
			{
				echo  header('location:'.base_url().'index.php/Login/logout');	
			}
			else
			{
				$login_type = $this->session->userdata('login_type');
				if ($login_type == 'super_admin')
				{
					$session_login_id = $_SESSION['login_id'];
					$sql = 'select * from  tblTemplateMaster where templateFlag=0';
					$query = $this->db->query($sql);
					$result = $query->result();
					return $result;
				}
			}
		}
		
			function filename_exists($rest_email,$btnval,$pageval)
			{
				if($pageval=='clinic')
				{
					if($btnval=='reg')
					{
						$this->db->select('*'); 
						$this->db->from('tblClinicRegistration');
						$this->db->where('regNo', $rest_email);
					}
					else{
						$this->db->select('*'); 
						$this->db->from('tblClinicRegistration');
						$this->db->where('clinicContact', $rest_email);
					}
				}
				$query = $this->db->get();
			$result = $query->result_array();
			return $result;
		}
		
		public function insertRegistration($reg_no,$contact_person,$contact_person_email,$contact_person_contact, $clinic_name, $clinic_website,$clinic_email, $clinic_contact, $short_desc,$package_id,$branch_name,$branch_address,$branch_email,$branch_contact,$cat_button,$clinic_reg_id,$no_of_branches,$branch_id,$branch_code,$photo_file,$clinic_proof,$sms_link,$payment_api_key,$payment_secret_key,$newpatient,$existingpatient,$bankAcc_name,$bank_name,$accno,$ifcsccode,$bankbranch,$prescTemplate)
		
		{
			
			if ($cat_button=='add_clinic_btn')
			{
			 	$created_date=date('Y-m-d'); 
				// clinicIconFile , '".$photo_file."'
				
				 $presc ="select * from  tblTemplateMaster where templateID=".$prescTemplate;
				$preqry = $this->db2->query($presc);
				$presres = $preqry->result(); 
			  	$prescTemplateurl=$presres[0]->templateurl; 
				
				
				
				
		  	    $sql ="INSERT INTO tblClinicRegistration (regNo,contactPerson, contactEmail, contactNumber, clinicName,clinicEmail,clinicContact, clinicCreateDate, clinicInfo,clinicWebsite,idProof,smsLink,payemntApiKey,paymentSecretKey,clinicIconFile,newPatientDos ,existingPatientDos ,bankAccountName,accountNo ,bankName ,IFSCCode,bankBranch,prescriptionTemplateID,prescriptionTemplateurl ) values ('".$reg_no."','".$contact_person."','".$contact_person_email."','".$contact_person_contact."','".$clinic_name."','".$clinic_email."','".$clinic_contact."', '".$created_date."',   '".$short_desc."', '".$clinic_website."', '".$clinic_proof."', '".$sms_link."', '".$payment_api_key."', '".$payment_secret_key."','".$photo_file."','".$newpatient."','".$existingpatient."','".$bankAcc_name."','".$accno."','".$bank_name."','".$ifcsccode."','".$bankbranch."','".$prescTemplate."','".$prescTemplateurl."')";
				
			  	$result = $this->db->query($sql);
			 	$clinicID=$this->db->insert_id();
				$created_date=date("Y-m-d");
				$_SESSION['success']='Clinic Registration Submitted Successfully';
				
				
				for($k=0;$k<count($branch_name);$k++)
				{
					
					
					$branchsql ="INSERT INTO 	tblBranchMaster (fkClinicID, branchName, branchAddress,branchEmail,branchContact,branchCode) values ('".$clinicID."','".$branch_name[$k]."','".$branch_address[$k]."','".$branch_email[$k]."','".$branch_contact[$k]."' ,'".$branch_code[$k]."' )";
					$this->db->query($branchsql);
				}	
				
				
				//mail detauls
				
				$data = array();
			 
				
				$reset_key= rtrim(base64_encode('rest|'.$clinicID.'|'.(time())),"==");  
		
			 	$link= base_url().'index.php/Login/reset_password_enter_password/'.$reset_key;
					$new_url = $this->get_tiny_url($link);
				$message1   =   "To Set clinic Credentials,Click the link ".$new_url; 
    
					$msg     =   str_replace(" ",'%20',$message1);
					$mob       =   "91".$contact_person_contact; 
				/* 	$url   =   "http://sms2.iissms.co.in/V2/http-api.php?apikey=eYYP9s7k6qHjRiKX&senderid=VAIDYA&number=".$mob."&message=".$msg."&format=json";	
					 */
					$sms=str_replace("#",$mob,$sms_link);
				$finallinksms=str_replace("*",$msg,$sms);
				$url   =$finallinksms;
				 	$urls       =   preg_replace("/ /", "%20", $url); 
					$p1         =   file_get_contents($urls);
				
				
					$curl = curl_init();
				curl_setopt_array($curl, array(
				CURLOPT_URL => "https://api.sendinblue.com/v3/smtp/email",		
				CURLOPT_SSL_VERIFYPEER => "C:/xampp/apache/crt/cacert.pem",
				CURLOPT_SSL_VERIFYHOST => "C:/xampp/apache/crt/cacert.pem",
				CURLOPT_VERBOSE	=> true,   
				CURLOPT_CAINFO => "C:/xampp/apache/crt/cabundle.crt",
				CURLOPT_CAPATH => "C:/xampp/apache/crt/cabundle.crt",
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_ENCODING => "",
				CURLOPT_MAXREDIRS => 10,
				CURLOPT_TIMEOUT => 30,
				CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				CURLOPT_CUSTOMREQUEST => "POST",
				CURLOPT_POSTFIELDS => "{\"sender\":{\"name\":\"E-VAIDAYAK.COM\",\"email\":\"info@e-vaidyak.com\"},\"to\":[{\"email\":\"$contact_person_email\",\"name\":\"$contact_person\"}],\"replyTo\":{\"email\":\"info@e-vaidyak.com\",\"name\":\"E-VAIDAYAK.COM\"},\"htmlContent\":\"<p>Hello, your registrtion with E-VAIDYAK.COM is successfully done, now you are just 1 step ahead for accessing the world class medical services. To set your login Credentials, please click on below link :</br><a href='".$new_url."'>Click here </a></p>\",\"subject\":\"Clinic Registered Successfully\"}",
				CURLOPT_HTTPHEADER => array(
				"accept: application/json",
				"api-key: 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",
				"content-type: application/json"
				),
				));
				$response = curl_exec($curl);
				$err = curl_error($curl);
				curl_close($curl);
									
									
				
				
				//databse				
				$dbname='db_'.$clinicID;
				$s="create database ".$dbname;
				$result = $this->db->query($s);	
				 
				 $appointmentLink='http://localhost:84/clinic_final/index.php/Welcome/appointmentLink/'.$reset_key;
				$loginsql ="update  tblClinicRegistration set  clinicDbName='".$dbname."',clinicDbCreateDate='".$created_date."',appointmentLink='".$appointmentLink."' where clinicID=".$clinicID;	
				$result = $this->db->query($loginsql); 
				
				 
				 
			/* 	 $insert_user_stored_proc = "{CALL TmpCreateTable(?)}";
                    $data = array('DbName' => $dbname);
                 $result = $this->db->query($insert_user_stored_proc, $data);
				
				 */
			 
				
				$this->db->close();					
			}
			else
			{
				
				
				$this->db->from('tblClinicRegistration');	
				$this->db->where('clinicID',$clinic_reg_id);
				$query = $this->db->get();
				$row=$query->row();
				
				
				/* $idProof=$row->idProof;
					if($address_proof_file!='')
					{
					$address_proof_data=$idProof;
					}
					else{
					$address_proof_data=$clinic_proof;
				} */
				
				
				$sql = "update tblClinicRegistration set contactPerson='".$contact_person."', contactNumber='".$contact_person_contact."', clinicName='".$clinic_name."' , clinicInfo='".$short_desc."' , clinicContact='".$clinic_contact."' , clinicEmail='".$clinic_email."', clinicWebsite='".$clinic_website."',newPatientDos='".$newpatient."',existingPatientDos= '".$existingpatient."' ,bankAccountName='".$bankAcc_name."',accountNo='".$accno."',bankName='".$bank_name."',IFSCCode='".$ifcsccode."',bankBranch='".$bankbranch."' where clinicID=".$clinic_reg_id;
				
				$result = $this->db->query($sql);
				$_SESSION['success']='Clinic Updated Successfully';
				
				
            	$branchQry=$this->db->query("select * from tblBranchMaster where fkClinicID=".$clinic_reg_id);
				
            	foreach ($branchQry->result() as $row)
            	{
            		if(in_array($row->branch_id,$branch_id))
            		{
					}
            		else
            		{
            			$q="delete from tblBranchMaster where branchID=".$row->branch_id;
						$this->db->query($q);
            			
					}
				}
				
				
				
				
				for($k=0;$k<count($branch_name);$k++)
				{
					if($branch_id[$k]=='')
					{
						
						
						$branchsql ="INSERT INTO 	tblBranchMaster (fkClinicID, branchName, branchAddress,branchEmail,branchContact,branchCode) values ('".$clinicID."','".$branch_name[$k]."','".$branch_address[$k]."','".$branch_email[$k]."','".$branch_contact[$k]."' ,'".$branch_code[$k]."' )";
						$this->db->query($branchsql);
					}	
					else
					{
						$rs="update tblBranchMaster set branchName='".$branch_name[$k]."', branchAddress='".$branch_address[$k]."',branchEmail='".$branch_email[$k]."',branchContact='".$branch_contact[$k]."',branchCode='".$branch_code[$k]."'  where   fkClinicID=".$clinic_reg_id;
						$this->db->query($rs);
					}
				}
            	
				
			} 
			
		redirect(base_url() . 'index.php/clinicDetails');
		}
		
		
		
		
		public function editClinic($id) {
			$query = $this->db->query("select * from  tblClinicRegistration reg where  reg.clinicID = $id");
			return $query->result_array();
		}
		
		public function viewClinic($id) {
			$query = $this->db->query("SELECT * FROM tblClinicRegistration vm WHERE vm.clinicID = '$id' ");
			return $query->result_array();
		} 
		
		public function getbranchages($id) {
			$query = $this->db->query("SELECT * FROM tblBranchMaster branch, tblClinicRegistration reg WHERE branch.fkClinicID = $id and reg.clinicID=branch.fkClinicID ");
			return $query->result_array();
		} 
		
		public function deleteClinic($id) {
			$query = $this->db->query("update  tblClinicRegistration  set activeFlag=2 WHERE clinicID='$id' ");
			return $query->result_array();
		}
		public function insert_newpackage($package_name, $user_limit, $per_user_cost, $package_desc,$duration, $duration_type,$cat_button,$package_id)
		{
			if ($cat_button=='add_package_btn')
			{
			 	$created_date=date('Y-m-d'); 
				$package_cost=$user_limit * $per_user_cost;
				$sql = 'INSERT INTO tbl_package (package_name, user_min_limit, per_user_cost, package_cost, package_desc, duration, duration_type) values ("'.$package_name.'","'.$user_limit.'","'.$per_user_cost.'","'.$package_cost.'","'.$package_desc.'", "'.$duration.'", "'.$duration_type.'")';
			  	$result = $this->db->query($sql);
				$clinicID=$this->db->insert_id();
				
				$_SESSION['success']='Packages  Added Successfully';
				
			}
			else
			{
				
				$package_cost=$user_limit * $per_user_cost;
				
				$sql = 'update tbl_package set package_name="'.$package_name.'", user_min_limit="'.$user_limit.'",per_user_cost="'.$per_user_cost.'", package_cost="'.$package_cost.'" , package_desc="'.$package_desc.'" , duration="'.$duration.'" , duration_type="'.$duration_type.'" where package_id='.$package_id;
				
				$result = $this->db->query($sql);
				$_SESSION['success']='Packages  Updated Successfully';
			} 
			
			redirect(base_url() . 'index.php/packageDetails');
		}
		
		public function editpackage($id) {
			$query = $this->db->query("select * from  tbl_package where  package_id = $id and package_flag=0");
			return $query->result_array();
		}
		public function deletepackage($id) {
			$query = $this->db->query("delete FROM tbl_package  WHERE package_id = '$id' ");
			
		}
		
		function get_tiny_url($url)  {
			$ch = curl_init();
			$timeout = 5;
			curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$url);
			curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
			curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
			$data = curl_exec($ch);
			curl_close($ch);
			return $data;
		}
	}
	
?>				