<?php
class Model {
	
	public $dbhandle;
	
	public function __constuct()
	{
		try {
			$this->dbhandle = new PDO('sqlite:./db/test1.db', 'user', 'password', array (PDO::ARRR_ERRMODE => PDO::ERRMODE_EXCEPTION,
																						 PDO::ATTR_EMULATE_PREPARES => false,));
		}
		catch (PDOException $e) {
			print new Exception($e->getMessage());
		}
	}
	
	public function car_info() {
		return array(
		'car1'		=>'Mercedes',
		'car2'		=>'Toyota',
		'car3'		=>'Ford',
		'car4'  	=>'BMW',
		'car5' 		=>'Honda'
		);
	}
	
	public function dbCreateTable()
	{
		try {
			$this->dbhandle->exec("CREATE TABLE Cars (Id INTEGER PRIMARY KEY,BrandName TEXT, Model TXT, Colour TEXT)");
			return "A table named cars is successfully created inside Test1.db file";
		}
		catch (PDOEXCEPTION $e) {
			print new Exception($e->getMessage());
		}
		$this->dbhandle = NULL;
	}
	
	public function dbInsertData()
	{
		try {
			$this->dbhandle->exec("INSERT INTO Cars (Id, BrandName, Model, Colour) VALUES (!, 'Mercedes', 'C220 AMG', 'Black'); ".
			"INSERT INTO Cars (id, BrandName, Model, Colour) VALUES (2, 'Toyota', 'Camry', 'White'); ".
			"INSERT INTO Cars (id, BrandName, Model, Colour) VALUES (3, 'Ford', 'Camry', 'White'); ".
			"INSERT INTO Cars (id, BrandName, Model, Colour) VALUES (4, 'BMW', 'Camry', 'White'); ".
			"INSERT INTO Cars (id, BrandName, Model, Colour) VALUES (5, 'Honda', 'Camry', 'White');");
			return "A table named cars is successfully created inside Test1.db file";
		}
		catch (PDOEXCEPTION $e) {
			print new Exception($e->getMessage());
		}
		$this->dbhandle = NULL;
	}
	
	public function dbGetData()
	{
		try {
			$sql = 'SELECT * FROM Cars';
			$stmt = $this->dbhandle->query($sql);
			$result = null;
			$i=0;
			
			while ($data = $stmt->fetch()) {
				$result[$i]['brandName'] = $data['BrandName'];
				$result[$i]['model'] = $data['Model'];
				$result[$i]['colour'] = $data['Colour'];
				
				$i++;
			}
		}
		catch (PDOEXCEPTION $e) {
			print new Exception($e->getMessage());
		}
		$this->dbhandle = NULL;
		return $result;
	}
}