<?php

/**
 * Database functions
 * 
 * @category    Database
 * @package     ATProcessor
 * @author      Sam Meredith <sam@aandtinstruments.com>
 * @version     0.1
 */

/**
 * Database and table names
 */
define("DB_NAME", $_SERVER['DOCUMENT_ROOT']."/configDB.db");
define("TABLE_NAME", "tblConfig");

/**
 * Attempt to read the database
 */
function databaseIsReadable()
{
    try
    {
        $DBH = new PDO("sqlite:" . DB_NAME);
        $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $STH = $DBH->prepare("SELECT * FROM '" . TABLE_NAME . "';");
        $STH->execute();
        return 1;
    } 
    catch (PDOException $e)
    {
        file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
        return 0;
    }
}

/** 
 * Read a value from the database
 * @param string $section The section to read
 * @param string $key The key to read
 * @return string The value found in the database
 */
function readDB($section, $key) {

    try {
        $DBH = new PDO("sqlite:" . DB_NAME);
        $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
        return "Unable to connect to database.";
    }
    
    try {
        $STH = $DBH->prepare("SELECT value FROM " . TABLE_NAME . "
                                WHERE (section LIKE :section AND key LIKE :key)");
        $STH->setFetchMode(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
        return "Error in prepared statement.";
    }
    
    try {
        $STH->bindParam(':section', $section);
        $STH->bindParam(':key', $key);
        $STH->execute();
        $row = $STH->fetch();
        $value = $row['value'];
    } catch (PDOException $e) {
        file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
        return "Error writing to database.";
    }
    
    $DBH = null;
    return $value;
}

/**
 * Read all key value pairs for a given section
 * @param string $section The section from which to read
 */
function readSection($section, $toLower) {
    
    try {
        $DBH = new PDO("sqlite:" . DB_NAME);
        $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
        return "Unable to connect to database.";
    }
    
    try {
        $STH = $DBH->prepare("SELECT key, value FROM " . TABLE_NAME . "
                                WHERE (section LIKE :section)
                                AND (key IS NOT NULL)");
        $STH->setFetchMode(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
        return "Error in prepared statement.";
    }
    
    try {
        $STH->bindParam(':section', $section);
        $STH->execute();
        $value = array();
        while ($row = $STH->fetch()) {
            if ($toLower) {
                $key = strtolower($row['key']);
            } else {
                $key = ($row['key']);
            }
            //Empty unit serial numbers can write 0xFF into the database, which causes json_encode to fail
            //This filters them out
            if (strpos($key, chr(255)) === false) {
                $value[$key] = $row['value'];
            }
        }
    } catch (PDOException $e) {
        file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
        return "Error reading from database.";
    }
    
    $DBH = null;
    return $value;
}

?>