<?php
require_once(dirname(__FILE__).'/CsvController.php');

class RemoteQueryController
{
	/** @var  PDO */
    private $dbh;
	/** @var  PDOStatement */
    private $qh;
    
    private $exception;
    
    public function connectToDatabase($dsn)
    {
        try {
            $this->dbh = new PDO($dsn);
        } 
        catch (PDOException $e) 
        {
            $this->exception = $e;
            return false;
        }
        return true;
    }
    
    public function getLastException() 
    {
        return $this->exception;    
    }
    
    public function query($queryString) 
    {
        if (!$this->dbh) return false;
        
        try {
            $this->qh = $this->dbh->query($queryString);
        }
        catch (PDOException $e)
        {
            $this->exception = $e;
            return false;
        }
        return true;
    }
    
    public function fetchAll() 
    {
        if (!$this->qh) return array();
        return $this->qh->fetchAll(PDO::FETCH_NUM);
    }
    
    public function connectFetchAndConvertToCsv($dsn, $queryString)
    {
        $this->connectToDatabase($dsn);
        $this->query($queryString);

        $csvCtrl = new CsvController();
        return $csvCtrl->csvConvert($this->fetchAll());
    }
}