<?php

require_once(realpath(dirname(__FILE__) . "/../config.php"));

function getDb() {
    global $config, $renkan_table;

    $db = new PDO(
        $config['db']['dsn'], $config['db']['user'], $config['db']['password'],
        array(PDO::ATTR_EMULATE_PREPARES => false,
              PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
    );

    $querycheck = "SELECT 1 FROM ". RENKAN_PROJECT_TABLE ." LIMIT 1;";

    $create_table = false;

    try {
        $res = $db->query($querycheck);
        if($res === false) {
            $create_table = true;
        }
    }
    catch(PDOException $e) {
        $create_table = true;
    }

    if($create_table === true) {
        $db->query("CREATE TABLE ". RENKAN_PROJECT_TABLE ." ( id CHAR(36) NOT NULL PRIMARY KEY, title VARCHAR(2048) NULL, renkan TEXT NULL);");
    }
    return $db;
}

function insertProject($renkanId, $title, $renkan) {
    $insertSql = "INSERT INTO ". RENKAN_PROJECT_TABLE ." (id, title, renkan) VALUES (:renkanId, :title, :renkan)";
    $values = ['renkanId' => $renkanId, 'title' => $title, 'renkan' => $renkan];
    return execStmt($insertSql, $values);
}

function updateProject($renkanId, $title, $renkan) {
    $updateSql = "UPDATE ". RENKAN_PROJECT_TABLE ." SET id = :renkanId, title = :title, renkan = :renkan;";
    $values = ['renkanId' => $renkanId, 'title' => $title, 'renkan' => $renkan];
    return execStmt($updateSql, $values);
}

function deleteProject($renkanId) {
    $deleteSql = "DELETE FROM ". RENKAN_PROJECT_TABLE ." WHERE id = :renkanId;";
    $values = ['renkanId' => $renkanId];
    return execStmt($deleteSql, $values);
}

function selectProject($renkanId) {
    $selectSql = "SELECT id, title, renkan FROM ". RENKAN_PROJECT_TABLE ." WHERE id = :renkanId;";
    $values = ['renkanId' => $renkanId];

    return execStmt($selectSql, $values)->fetchAll(PDO::FETCH_ASSOC);
}

function listProjects() {
    $selectSql = "SELECT id, title, renkan FROM ". RENKAN_PROJECT_TABLE .";";
    return execStmt($selectSql, array())->fetchAll(PDO::FETCH_ASSOC);
}

function execStmt($sql, $values) {
    $stmt = getDb()->prepare($sql);
    $stmt->execute($values);
    return $stmt;
}
