<?php

namespace App\Controllers;

class FoController extends BaseController {
	
	public function index() {
		return view('fo/dashboard');
	}
	
	public function viewAccess($accessnumber): string {

		// Mengetahui Apakah User Bali atau Surabaya
		$data['usercityid'] = session()->get('usercityid');

		$db = \Config\Database::connect();
		$sql = "SELECT sr.HOSTORDERNUMBER, tu.SAMPLETYPE, ds.SHORTTEXT, tu.TUBESTATUS, ct.COLLSTATUS, ct.TUBECOMMENT from SP_TUBES tu
			left join SP_REQUESTS sr on tu.SP_ACCESSNUMBER=sr.SP_ACCESSNUMBER
			left join DICT_SAMPLES_TYPES ds on ds.SAMPCODE= tu.SAMPLETYPE
			left join cmod.dbo.CM_TUBES ct on ct.SAMPLETYPE=tu.SAMPLETYPE and ct.ACCESSNUMBER=tu.SP_ACCESSNUMBER
			where tu.SP_ACCESSNUMBER='$accessnumber'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$visit_number = $results[0]['HOSTORDERNUMBER'];
		$data['data'] = $results;
	
		// $sql = "select hp.PATNUMBER, hp.PATNAME, ho.PAYERNAME, ho.TREATDOC
		// 	from cmod.dbo.CM_HIS_ORDERS ho
		// 	left join cmod.dbo.CM_HIS_PATIENTS hp on hp.PATID=ho.PATID
		// 	WHERE ho.VISITNUMBER='$visit_number'";
		$sql = "SELECT ctp.PATNUMBER, CONCAT(ctp.FIRSTNAME, ' ', ctp.LASTNAME) as PATNAME, ctr.AGENT as PAYERNAME, ctr.DOC as TREATDOC, ctr.VISITTYPE
			from cmod.dbo.CM_TM_REQUESTS ctr
			left join cmod.dbo.CM_TM_PATIENTS ctp on ctr.PATID = ctp.PATID
			where ctr.REFFID='$visit_number'";
		$query = $db->query($sql);
		$results = $query->getResultArray();

		if($results != null) {
			$data['patnumber'] = $results[0]['PATNUMBER'];
			$data['patient_fullname'] = $results[0]['PATNAME'];
			$data['visit_description'] = $results[0]['VISITTYPE'];
			$data['treating_doctor'] = $results[0]['TREATDOC'];
			$data['payer_name'] = $results[0]['PAYERNAME'];
		} else {
			$data['patnumber'] = "";
			$data['patient_fullname'] = "";
			$data['visit_description'] = "";
			$data['treating_doctor'] = "";
			$data['payer_name'] = "";
		}

		$data['accessnumber'] = $accessnumber;

        return view('fo/dashboard_viewAccess', $data);
    }
	
	public function changePass() {
		if ($this->request->getMethod() === 'POST') {
			$password1 = $this->request->getVar('password1');
			$password2 = $this->request->getVar('password2');
			$data['password1'] = $password1;
			$data['password2'] = $password2;
			if($password1 == $password2) {	
				$password = password_hash($password1,PASSWORD_DEFAULT);
				$db = \Config\Database::connect();
				$sql = "update cmod.dbo.CM_USERS set PASSWORD='$password' where USERID='$userid'";
				$db->query($sql);
				return redirect()->to("/");
			} else {
				return redirect()->to("/auth/setpass/$userid")->with('flash_error', 'password is not the same.');
			}
		}
		return view('changePass');
    }
}
