#if defined(ENABLE_WWW)

#include <string.h>
#include <sqlite3.h>
#include <time.h>
#include <stdlib.h>
#include <sys/utsname.h>
#include "bbs.h"

extern struct bbs_config conf;

int www_email_delete(struct user_record *user, int id) {
	char buffer[PATH_MAX];
	sqlite3 *db;
	sqlite3_stmt *res;
	int rc;
	char *csql = "CREATE TABLE IF NOT EXISTS email ("
	             "id INTEGER PRIMARY KEY,"
	             "sender TEXT COLLATE NOCASE,"
	             "recipient TEXT COLLATE NOCASE,"
	             "subject TEXT,"
	             "body TEXT,"
	             "date INTEGER,"
	             "seen INTEGER);";
	char *dsql = "DELETE FROM email WHERE id=? AND recipient LIKE ?";
	char *err_msg = 0;

	snprintf(buffer, sizeof buffer, "%s/email.sq3", conf.bbs_path);

	rc = sqlite3_open(buffer, &db);
	if (rc != SQLITE_OK) {
		sqlite3_close(db);

		return 0;
	}
	sqlite3_busy_timeout(db, 5000);
	rc = sqlite3_exec(db, csql, 0, 0, &err_msg);
	if (rc != SQLITE_OK) {
		sqlite3_free(err_msg);
		sqlite3_close(db);

		return 0;
	}

	rc = sqlite3_prepare_v2(db, dsql, -1, &res, 0);

	if (rc == SQLITE_OK) {
		sqlite3_bind_int(res, 1, id);
		sqlite3_bind_text(res, 2, user->loginname, -1, 0);
	} else {
		sqlite3_finalize(res);
		sqlite3_close(db);
		return 0;
	}
	sqlite3_step(res);

	sqlite3_finalize(res);
	sqlite3_close(db);
	return 1;
}

int www_send_email(struct user_record *user, char *recipient, char *subject, char *ibody) {
	char pathbuf[PATH_MAX];
	sqlite3 *db;
	sqlite3_stmt *res;
	int rc;
	char *csql = "CREATE TABLE IF NOT EXISTS email ("
	             "id INTEGER PRIMARY KEY,"
	             "sender TEXT COLLATE NOCASE,"
	             "recipient TEXT COLLATE NOCASE,"
	             "subject TEXT,"
	             "body TEXT,"
	             "date INTEGER,"
	             "seen INTEGER);";
	char *isql = "INSERT INTO email (sender, recipient, subject, body, date, seen) VALUES(?, ?, ?, ?, ?, 0)";
	char *err_msg = 0;
	stralloc sa = EMPTY_STRALLOC;
	char *body = NULL;
	struct utsname name;

	if (recipient == NULL || subject == NULL || ibody == NULL) {
		return 0;
	}

	if (check_user(recipient)) {
		return 0;
	}

	uname(&name);

	for (char *p = ibody; *p != '\0'; ++p)
		if (*p != '\n')
			stralloc_append1(&sa, *p);

	stralloc_cats(&sa, "\r--- MagickaBBS v");
	stralloc_cat_long(&sa, VERSION_MAJOR);
	stralloc_append1(&sa, '.');
	stralloc_cat_long(&sa, VERSION_MINOR);
	stralloc_cats(&sa, VERSION_STR);
	stralloc_cats(&sa, " (");
	stralloc_cats(&sa, name.sysname);
	stralloc_append1(&sa, '/');
	stralloc_cats(&sa, name.machine);
	stralloc_cats(&sa, ")\r");
	stralloc_cats(&sa, " * Origin: ");
	stralloc_cats(&sa, conf.default_tagline);
	stralloc_cats(&sa, " \r");
	stralloc_0(&sa);
	body = sa.s;

	snprintf(pathbuf, sizeof pathbuf, "%s/email.sq3", conf.bbs_path);
	rc = sqlite3_open(pathbuf, &db);
	if (rc != SQLITE_OK) {
		sqlite3_close(db);
		free(body);
		return 0;
	}

	sqlite3_busy_timeout(db, 5000);
	rc = sqlite3_exec(db, csql, 0, 0, &err_msg);
	if (rc != SQLITE_OK) {
		sqlite3_free(err_msg);
		sqlite3_close(db);
		free(body);
		return 0;
	}

	rc = sqlite3_prepare_v2(db, isql, -1, &res, 0);
	if (rc != SQLITE_OK) {
		sqlite3_finalize(res);
		sqlite3_close(db);
		free(body);
		return 0;
	}
	sqlite3_bind_text(res, 1, user->loginname, -1, 0);
	sqlite3_bind_text(res, 2, recipient, -1, 0);
	sqlite3_bind_text(res, 3, subject, -1, 0);
	sqlite3_bind_text(res, 4, body, -1, 0);
	sqlite3_bind_int(res, 5, time(NULL));
	sqlite3_step(res);

	sqlite3_finalize(res);
	sqlite3_close(db);
	free(body);

	return 1;
}

char *www_new_email() {
	stralloc page = EMPTY_STRALLOC;

	stralloc_copys(&page, "<div class=\"content-header\"><h2>New Email</h2></div>\n");
	stralloc_cats(&page, "<form action=\"");
	stralloc_cats(&page, conf.www_url);
	stralloc_cats(&page, "email/\" method=\"POST\" onsubmit=\"return validate()\" enctype=\"application/x-www-form-urlencoded\">\n");
	stralloc_cats(&page, "To : <input type=\"text\" name=\"recipient\" id=\"recipient\" /><br />\n");
	stralloc_cats(&page, "Subject : <input type=\"text\" name=\"subject\" id=\"subject\" /><br />\n");
	stralloc_cats(&page, "<textarea name=\"body\" wrap=\"hard\" rows=\"25\" cols=\"79\" id=\"body\"></textarea>\n<br />");
	stralloc_cats(&page, "<input type=\"submit\" name=\"submit\" value=\"Send\" />\n<br />");
	stralloc_cats(&page, "</form>\n");
	stralloc_0(&page);

	return page.s;
}

char *www_email_display(struct user_record *user, int email) {
	stralloc page = EMPTY_STRALLOC;
	char pathbuf[PATH_MAX];
	char datebuf[32];
	sqlite3 *db;
	sqlite3_stmt *res;
	int rc;
	struct tm msg_date;
	time_t date;
	char *from;
	char *subject;
	char *body;
	int id;
	int i;
	int chars;
	char *err_msg = 0;
	char *email_create_sql = "CREATE TABLE IF NOT EXISTS email ("
	                         "id INTEGER PRIMARY KEY,"
	                         "sender TEXT COLLATE NOCASE,"
	                         "recipient TEXT COLLATE NOCASE,"
	                         "subject TEXT,"
	                         "body TEXT,"
	                         "date INTEGER,"
	                         "seen INTEGER);";
	char *email_show_sql = "SELECT id,sender,subject,body,date FROM email WHERE recipient LIKE ? LIMIT ?, 1";

	char *update_seen_sql = "UPDATE email SET seen=1 WHERE id=?";

	snprintf(pathbuf, sizeof pathbuf, "%s/email.sq3", conf.bbs_path);
	rc = sqlite3_open(pathbuf, &db);
	if (rc != SQLITE_OK) {
		sqlite3_close(db);
		return NULL;
	}
	sqlite3_busy_timeout(db, 5000);
	rc = sqlite3_exec(db, email_create_sql, 0, 0, &err_msg);
	if (rc != SQLITE_OK) {
		sqlite3_free(err_msg);
		sqlite3_close(db);
		return NULL;
	}

	rc = sqlite3_prepare_v2(db, email_show_sql, -1, &res, 0);

	if (rc != SQLITE_OK) {
		sqlite3_finalize(res);
		sqlite3_close(db);
		return NULL;
	}
	sqlite3_bind_text(res, 1, user->loginname, -1, 0);
	sqlite3_bind_int(res, 2, email - 1);

	if (sqlite3_step(res) != SQLITE_ROW) {
		return strdup("<div class=\"content-header\"><h2>No Such Email</h2></div>\n");
	}
	id = sqlite3_column_int(res, 0);
	from = (char *)sqlite3_column_text(res, 1);
	subject = (char *)sqlite3_column_text(res, 2);
	body = (char *)sqlite3_column_text(res, 3);
	date = (time_t)sqlite3_column_int(res, 4);
	localtime_r(&date, &msg_date);

	stralloc_copys(&page, "<div class=\"content-header\"><h2>Your Email</h2></div>\n");
	stralloc_cats(&page, "<div class=\"email-view-header\">\n");
	stralloc_cats(&page, "<div class=\"email-view-subject\">");
	stralloc_cats(&page, subject);
	stralloc_cats(&page, "</div>\n");
	stralloc_cats(&page, "<div class=\"email-view-from\">From: ");
	stralloc_cats(&page, from);
	stralloc_cats(&page, "</div>\n");
	stralloc_cats(&page, "<div class=\"email-view-date\">Date: ");
	if (conf.date_style == 1)
		strftime(datebuf, sizeof datebuf, "%H:%M %m-%d-%y", &msg_date);
	else
		strftime(datebuf, sizeof datebuf, "%H:%M %d-%m-%y", &msg_date);
	stralloc_cats(&page, datebuf);
	stralloc_cats(&page, "</div>\n");
	stralloc_cats(&page, "</div>\n");
	stralloc_cats(&page, "<div id=\"msgbody\">\n");
	for (char *p = body; *p != '\0'; ++p) {
		switch (*p) {
			case '\r': stralloc_cats(&page, "<br />"); break;
			case '<': stralloc_cats(&page, "&lt;"); break;
			case '>': stralloc_cats(&page, "&gt;"); break;
			default: stralloc_append1(&page, *p); break;
		}
	}
	stralloc_cats(&page, "</div>\n");
	stralloc_cats(&page, "<div class=\"email-reply-form\">\n");
	stralloc_cats(&page, "<h3>Reply</h3>\n");
	stralloc_cats(&page, "<form action=\"");
	stralloc_cats(&page, conf.www_url);
	stralloc_cats(&page, "email/\" method=\"POST\" enctype=\"application/x-www-form-urlencoded\">\n");
	stralloc_cats(&page, "<input type=\"hidden\" name=\"recipient\" value=\"");
	stralloc_cats(&page, from);
	stralloc_cats(&page, "\" />\n");
	stralloc_cats(&page, "Subject : <input type=\"text\" name=\"subject\" value=\"");
	if (strncasecmp(subject, "re:", 3) != 0)
		stralloc_cats(&page, "RE: ");
	stralloc_cats(&page, subject);
	stralloc_cats(&page, "\" /><br />\n");
	stralloc_cats(&page, "<textarea name=\"body\" wrap=\"hard\" rows=\"25\" cols=\"79\" id=\"replybody\">");
	stralloc_cats(&page, from);
	stralloc_cats(&page, " said....\n\n");
	stralloc_cats(&page, "> ");
	size_t column = 0;
	for (char *p = body; *p != '\0'; ++p) {
		if (*p == '\r') {
			stralloc_cats(&page, "\n> ");
			column = 0;
			continue;
		} else if (column >= 78) {
			stralloc_cats(&page, "\n> ");
			column = 0;
		}
		stralloc_append1(&page, *p);
		++column;
	}
	stralloc_cats(&page, "</textarea>\n<br />");
	stralloc_cats(&page, "<input type=\"submit\" name=\"submit\" value=\"Reply\" />\n<br />");
	stralloc_cats(&page, "</form>\n");
	stralloc_cats(&page, "</div>\n");
	stralloc_0(&page);

	sqlite3_finalize(res);
	rc = sqlite3_prepare_v2(db, update_seen_sql, -1, &res, 0);
	if (rc != SQLITE_OK) {
		sqlite3_finalize(res);
		sqlite3_close(db);
		free(page.s);
		return NULL;
	}
	sqlite3_bind_int(res, 1, id);
	sqlite3_step(res);
	sqlite3_finalize(res);
	sqlite3_close(db);

	return page.s;
}

char *www_email_summary(struct user_record *user) {
	stralloc page = EMPTY_STRALLOC;
	char pathbuf[PATH_MAX];
	sqlite3 *db;
	sqlite3_stmt *res;
	int rc;
	char *email_summary_sql = "SELECT id,sender,subject,seen,date FROM email WHERE recipient LIKE ?";
	int msgid = 0;
	char *err_msg = 0;
	char *email_create_sql = "CREATE TABLE IF NOT EXISTS email ("
	                         "id INTEGER PRIMARY KEY,"
	                         "sender TEXT COLLATE NOCASE,"
	                         "recipient TEXT COLLATE NOCASE,"
	                         "subject TEXT,"
	                         "body TEXT,"
	                         "date INTEGER,"
	                         "seen INTEGER);";

	snprintf(pathbuf, sizeof pathbuf, "%s/email.sq3", conf.bbs_path);
	rc = sqlite3_open(pathbuf, &db);
	if (rc != SQLITE_OK) {
		sqlite3_close(db);
		return NULL;
	}
	sqlite3_busy_timeout(db, 5000);
	rc = sqlite3_exec(db, email_create_sql, 0, 0, &err_msg);
	if (rc != SQLITE_OK) {
		sqlite3_free(err_msg);
		sqlite3_close(db);
		return NULL;
	}

	rc = sqlite3_prepare_v2(db, email_summary_sql, -1, &res, 0);
	if (rc != SQLITE_OK) {
		sqlite3_finalize(res);
		sqlite3_close(db);
		return NULL;
	}
	sqlite3_bind_text(res, 1, user->loginname, -1, 0);

	stralloc_copys(&page, "<div class=\"content-header\"><h2>Your Email</h2></div>\n");
	stralloc_cats(&page, "<div class=\"button\"><a href=\"");
	stralloc_cats(&page, conf.www_url);
	stralloc_cats(&page, "email/new\">New Email</a></div>\n");
	stralloc_cats(&page, "<div class=\"div-table\">\n");

	while (sqlite3_step(res) == SQLITE_ROW) {
		char datebuf[32];
		++msgid;
		int id = sqlite3_column_int(res, 0);
		const char *from = (const char *)sqlite3_column_text(res, 1);
		const char *subject = (const char *)sqlite3_column_text(res, 2);
		int seen = sqlite3_column_int(res, 3);
		struct tm msg_date;

		time_t date = (time_t)sqlite3_column_int(res, 4);
		localtime_r(&date, &msg_date);
		stralloc_cats(&page, "<div class=\"email-summary");
		if (seen != 0) {
			stralloc_cats(&page, "-seen");
		}
		stralloc_cats(&page, "\"><div class=\"email-id\">");
		stralloc_cat_long(&page, msgid);
		stralloc_cats(&page, "</div><div class=\"email-subject\"><a href=\"");
		stralloc_cats(&page, conf.www_url);
		stralloc_cats(&page, "email/");
		stralloc_cat_long(&page, msgid);
		stralloc_cats(&page, "\">");
		stralloc_cats(&page, subject);
		stralloc_cats(&page, "</a></div><div class=\"email-from\">");
		stralloc_cats(&page, from);
		stralloc_cats(&page, "</div><div class=\"email-date\">");
		if (conf.date_style == 1)
			strftime(datebuf, sizeof datebuf, "%H:%M %m-%d-%y", &msg_date);
		else
			strftime(datebuf, sizeof datebuf, "%H:%M %d-%m-%y", &msg_date);
		stralloc_cats(&page, datebuf);
		stralloc_cats(&page, "</div><a href=\"");
		stralloc_cats(&page, conf.www_url);
		stralloc_cats(&page, "email/delete/");
		stralloc_cat_long(&page, id);
		stralloc_cats(&page, "\"><div class=\"email-delete\"></div></a></div>\n");
	}
	stralloc_cats(&page, "</div>\n");
	stralloc_0(&page);

	sqlite3_finalize(res);
	sqlite3_close(db);

	return page.s;
}

#endif
