<?php

// Database functions for YATWiki

namespace DB {

	$db = new \PDO('sqlite:'.DB_PATH);
	ValidateSchema();

	function ValidateSchema() {
		global $db;
		$db->query('
			CREATE TABLE articles (
				id       INTEGER PRIMARY KEY,
				modified INTEGER,
				title    TEXT,
				body     TEXT
			);		
		');
	}

	function GetArticle($title) {
		global $db;
		$stmt = $db->prepare('SELECT * FROM articles WHERE title = ? LIMIT 1');
		$stmt->execute(array(strtolower(trim($title))));
		$results = $stmt->fetchAll();
		return (count($results)) ? $results[0] : BlankArticle($title);
	}
	
	function GetRandomArticle() {
		global $db;
		$stmt = $db->query('SELECT * FROM articles ORDER BY RANDOM() LIMIT 1');
		$results = $stmt->fetchAll();
		return (count($results)) ? $results[0] : BlankArticle();
	}

	function GetRecentArticles($count) {
		global $db;
		$stmt = $db->prepare('SELECT * FROM articles ORDER BY modified DESC LIMIT ?');
		$stmt->execute(array($count));
		$results = $stmt->fetchAll();
		if (count($results)) return $results;
		return array();
	}
	
	function CountArticles() {
		global $db;
		$stmt = $db->query('SELECT COUNT(id) row_count FROM articles');
		$results = $stmt->fetchAll();
		return $results[0]['row_count'];
	}

	function BlankArticle($title = '') {
		return array(
			'id'=>0,
			'modified'=>time(),
			'title'=>strtolower(trim($title)),
			'body'=>''
		);
	}
	
	function SaveArticle($title, $body) {
		global $db;
		$title_san = strtolower(trim($title));
		$article = GetArticle($title_san);	
		if (intval($article['id']) > 0) {
			$stmt = $db->prepare('UPDATE articles SET modified=?, body=? WHERE id=?');
			$stmt->execute(array(time(), $body, $article['id']));
		} else {
			$stmt = $db->prepare('INSERT INTO articles (title, modified, body) VALUES (?, ?, ?)');
			$stmt->execute(array($title_san, time(), $body));
		}
	}

}