<?php

function get_field_name($type) {
	switch ($type) {
		case 'dir':
			return 'dir';
		case 'image':
			return 'image';
		default:
			throw new Exception('Invalid $type');
	}
}

function get_comments($id, $type) {
	global $pdo;

	$sql = 'SELECT * FROM comments WHERE ' . get_field_name($type) . ' = :id';
	$values = array(
		':id' => $id,
	);
	try {
		$res = $pdo->prepare($sql);
		$res->execute($values);
	} catch (PDOException $e) {
		echo 'Query error: ' . $e->getMessage();
		die();
	}
	$comments = [];
	while($row = $res->fetch(PDO::FETCH_ASSOC)) {
		$comments[] = $row;
	}
	return $comments;
}

function db_store_comment($nick, $email, $type, $id, $content) {
	global $pdo;

	$sql = 'INSERT INTO comments (ip, ' . get_field_name($type) . ', email, author, date, content) VALUES (:ip, :id, :email, :nick, :date, :content)';
	$values = array (
		':ip' => $_SERVER['REMOTE_ADDR'],
		':id' => $id,
		':email' => $email,
		':nick' => $nick,
		':date' => time(),
		':content' => $content,
	);
    try {
            $res = $pdo->prepare($sql);
            $res->execute($values);
    } catch (PDOException $e) {
            echo 'Query error: ' . $e->getMessage();
            die();
    }
}

function generate_comment_field($comments, $type, $id) {
	$emptytexts = array(
		'dir' => 'Brak komentarzy do tego katalogu, możesz być pierwszy!',
		'image' => 'Brak komentarzy do tego obrazka, możesz być pierwszy!',
	);

	$headertexts = array(
		'dir' => 'Komentarze do katalogu',
		'image' => 'Komentarze do obrazka',
	);

	if (count($comments) == 0) {
        $output = '<h2>' . $emptytexts[$type] . '</h2>';
	} else {
		$output = '<h2>' . $headertexts[$type] . '</h2>';
	}
	foreach ($comments as $comment) {
        	$output .= '<div class="comment-block"><div class="comment-author">Autor: ' . htmlspecialchars($comment['author']) . ', data: ' . date('j.m.Y G:i:s', $comment['date']) . '</div><div class="comment-text">' . htmlspecialchars($comment['content']) . '</div></div>';
	}

	$output .= '<h2>Dodaj nowy komentarz</h2><form id="comment-form" method="post" action="sendcomment.php"><table id="comment-form-table"><tr><td class="form-caption">Autor:</td><td><input type="text" name="comment-nick" id="comment-nick"></td></tr>';
	$output .= '<tr><td class="form-caption">E-mail (nie pokażę go nikomu):</td><td><input type="text" name="comment-email" id="comment-email"></td></tr>';
	$output .= '<tr><td colspan="2"><textarea id="comment-content" name="comment-content"></textarea></td></tr></table>';
	$output .= '<input type="submit" value="Wyślij">';
	$output .= '<input type="hidden" name="comment-type" id="comment-type" value="' . $type . '"><input type="hidden" name="comment-id" id="comment-id" value="' . $id . '"></form>';
	return $output;
}

?>