<?php

class LabTest{
	
	public function __construct() {
		require_once("class/connectdb.php");
		$db = new DbConnect;
		$this->con = $db->connect();
		
	}
	
	public function createLabTest($department, $sub_department, $sample, $test_name, $price){
		$sql = "CREATE TABLE IF NOT EXISTS labtest (
		   test_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
		   department VARCHAR(255),
		   sub_department VARCHAR(255),
		   sample VARCHAR(255),
		   test_name VARCHAR(255),
		   price DOUBLE,
		   date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
		)";
		
		if (mysqli_query($this->con, $sql)){
			$response =  "Table MyGuests created successfully";
			$query = mysqli_query($this->con, "INSERT INTO labtest (department, sub_department, sample, test_name, price) 
			           VALUES ('$department', '$sub_department', '$sample', '$test_name', '$price')");  // Insert into database
			if($query){
				$output['error'] = false;
				$output['status'] = "Test created successfully.";
			}else{
				$output['error'] = true;
				$output['status'] = "Failed to create test" . mysqli_error($this->con);
			}
		} else {
			$output['error']  = true;
			$output['status'] =  "Error creating table: " . mysqli_error($this->con);
		}
		
		return json_encode($output);
	}
	
	public function getLabTest(){
		$sql = mysqli_query($this->con, "SELECT * FROM labtest");
		$data = [];
		
		while($row = mysqli_fetch_array($sql)){
			$arr_data = array(
				'test_name'=>$row['test_name'],
				'price'=>$row['price']
			);
			array_push($data, $arr_data);
		}
		return $data; 
	}
	
	public function updateLabTest($lab_test_id, $department, $sub_department, $sample, $test_name, $price){
		$sql = mysqli_query($this->con, "UPDATE labtest SET department = '$department', sub_department = '$sub_department', sample = '$sample',
                         		test_name = '$test_name', price = '$price' WHERE test_id = $lab_test_id ");
		
		if($sql){
			$output['error']  = false;
	        $output['status'] = "Lab test successfully updated";
		}else{
			$output['error']  = true;
	        $output['status'] = "Error updating lab test" .  mysqli_error($this->con);
		}
		
		return json_encode($output);
	}
	
	public function deleteTest($lab_test_id){
		$sql = mysqli_query($this->con, "DELETE from labtest WHERE test_id = $lab_test_id ");
		if($sql){
			$output['error']  = false;
	        $output['status'] = "Lab test successfully deleted";
		}else{
			$output['error']  = true;
	        $output['status'] = "Failed to delete lab test: " . mysqli_error($this->con);
		}
		return json_encode($output);
	}
	
}


?>