<?php
/**
 * BusinessAdmin: administrative software for small companies
 * Copyright (C) 2015 Camil Staps (ViviSoft)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

require('../conf.php');

if (isset($_GET['create_tables'])) {
	try {
		$_pdo->query("CREATE TABLE IF NOT EXISTS `".Constants::db_prefix."assignment` (
				`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
				`offerId` smallint(5) unsigned NOT NULL,
				`title` tinytext NOT NULL,
				`description` text NOT NULL,
				`hours` float NOT NULL,
				`price_per_hour` float NOT NULL,
				`VAT_percentage` float NOT NULL,
				PRIMARY KEY (`id`),
				UNIQUE KEY `offerId - title` (`offerId`,`title`(255)),
				KEY `offerId` (`offerId`)
			) ENGINE=InnoDB  DEFAULT CHARSET=latin1");

		$_pdo->query("CREATE TABLE IF NOT EXISTS `".Constants::db_prefix."client` (
				`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
				`name` tinytext NOT NULL,
				PRIMARY KEY (`id`),
				UNIQUE KEY `name` (`name`(255))
			) ENGINE=InnoDB  DEFAULT CHARSET=latin1");

		$_pdo->query("CREATE TABLE IF NOT EXISTS `".Constants::db_prefix."contact` (
				`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
				`clientId` smallint(5) unsigned NOT NULL,
				`name` tinytext NOT NULL,
				`email` varchar(680) NOT NULL,
				`address` tinytext NOT NULL,
				`address_2` tinytext,
				`postal_code` varchar(7) NOT NULL,
				`city` tinytext NOT NULL,
				`country` tinytext NOT NULL,
				`language` varchar(3) NOT NULL DEFAULT 'en',
				PRIMARY KEY (`id`),
				UNIQUE KEY `clientId-name` (`clientId`,`name`(255)),
				KEY `clientId` (`clientId`)
			) ENGINE=InnoDB  DEFAULT CHARSET=latin1");

		$_pdo->query("CREATE TABLE IF NOT EXISTS `".Constants::db_prefix."discount` (
				`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
				`offerId` smallint(5) unsigned NOT NULL,
				`title` tinytext NOT NULL,
				`description` text NOT NULL,
				`value` float unsigned NOT NULL,
				`VAT_percentage` float NOT NULL,
				PRIMARY KEY (`id`)
			) ENGINE=InnoDB DEFAULT CHARSET=latin1;");

		$_pdo->query("CREATE TABLE IF NOT EXISTS `".Constants::db_prefix."file` (
				`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
				`filename` varchar(100) NOT NULL,
				`secret_key` varchar(63) DEFAULT NULL,
				PRIMARY KEY (`id`),
				UNIQUE KEY `filename` (`filename`)
			) ENGINE=InnoDB  DEFAULT CHARSET=latin1");

		$_pdo->query("CREATE TABLE IF NOT EXISTS `".Constants::db_prefix."mail` (
				`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
				`contactId` smallint(5) unsigned NOT NULL,
				`offerId` smallint(5) unsigned DEFAULT NULL,
				`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
				`subject` varchar(100) NOT NULL,
				PRIMARY KEY (`id`),
				KEY `contactId` (`contactId`),
				KEY `offerId` (`offerId`)
			) ENGINE=InnoDB DEFAULT CHARSET=latin1;");

		$_pdo->query("CREATE TABLE IF NOT EXISTS `".Constants::db_prefix."offer` (
				`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
				`contactId` smallint(5) unsigned NOT NULL,
				`start_date` date NOT NULL,
				`end_date` date NOT NULL,
				`invoice_date` date NOT NULL,
				`accepted` tinyint(1) unsigned NOT NULL DEFAULT '0',
				`invoice_fileId` smallint(5) unsigned DEFAULT NULL,
				`payment_key` varchar(63) DEFAULT NULL,
				PRIMARY KEY (`id`),
				UNIQUE KEY `invoice_fileId` (`invoice_fileId`),
				KEY `contactId` (`contactId`),
				KEY `contactId_2` (`contactId`),
				KEY `invoice_fileId_2` (`invoice_fileId`)
			) ENGINE=InnoDB  DEFAULT CHARSET=latin1");

		$_pdo->query("CREATE TABLE IF NOT EXISTS `".Constants::db_prefix."payment` (
				`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
				`offerId` smallint(5) unsigned NOT NULL,
				`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
				`braintree_id` varchar(36) DEFAULT NULL,
				`braintree_status` varchar(63) DEFAULT NULL,
				PRIMARY KEY (`id`),
				UNIQUE KEY `offerId` (`offerId`)
			) ENGINE=InnoDB DEFAULT CHARSET=latin1;");

		$_pdo->query("CREATE TABLE IF NOT EXISTS `".Constants::db_prefix."user` (
				`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
				`username` varchar(24) NOT NULL,
				`password` varchar(255) NOT NULL,
				PRIMARY KEY (`id`)
			) ENGINE=InnoDB DEFAULT CHARSET=latin1;");

		$_pdo->query("ALTER TABLE `".Constants::db_prefix."assignment`
				ADD CONSTRAINT `assignment_ibfk_1` FOREIGN KEY (`offerId`) REFERENCES `".Constants::db_prefix."offer` (`id`)");

		$_pdo->query("ALTER TABLE `".Constants::db_prefix."contact`
				ADD CONSTRAINT `contact_ibfk_1` FOREIGN KEY (`clientId`) REFERENCES `".Constants::db_prefix."client` (`id`)");

		$_pdo->query("ALTER TABLE `".Constants::db_prefix."discount`
				ADD CONSTRAINT `discount_ibfk_1` FOREIGN KEY (`offerId`) REFERENCES `".Constants::db_prefix."offer` (`id`);");

		$_pdo->query("ALTER TABLE `".Constants::db_prefix."mail`
				ADD CONSTRAINT `mail_ibfk_1` FOREIGN KEY (`contactId`) REFERENCES `".Constants::db_prefix."contact` (`id`) ON UPDATE CASCADE,
				ADD CONSTRAINT `mail_ibfk_2` FOREIGN KEY (`offerId`) REFERENCES `".Constants::db_prefix."offer` (`id`) ON UPDATE CASCADE;");

		$_pdo->query("ALTER TABLE `".Constants::db_prefix."offer`
				ADD CONSTRAINT `offer_ibfk_1` FOREIGN KEY (`invoice_fileId`) REFERENCES `".Constants::db_prefix."file` (`id`),
				ADD CONSTRAINT `offer_ibfk_2` FOREIGN KEY (`contactId`) REFERENCES `".Constants::db_prefix."contact` (`id`)");

		$_pdo->query("ALTER TABLE `".Constants::db_prefix."payment`
				ADD CONSTRAINT `payment_ibfk_1` FOREIGN KEY (`offerId`) REFERENCES `".Constants::db_prefix."offer` (`id`);");

		echo "Succeeded creating the database tables.";

	} catch (PDOException $e) {

		echo "Creating the database tables failed with a PDOException ({$e->getCode()}): {$e->getMessage()}<br/>" . $e->getTraceAsString();

	}
}

if (isset($_GET['create_folders'])) {
	if (!mkdir(Constants::files_folder)) {
		echo "Creating folder `" . Constants::files_folder . "` failed.<br/>";
	}
	if (!mkdir(Constants::files_folder . Constants::files_folder_trash)) {
		echo "Creating folder `" . Constants::files_folder_trash . "` failed.<br/>";
	}
}

if (isset($_GET['create_user'])) {
	$username = 'admin';
	try {
		$password = User::generateRandomPassword();
		$user = User::create($_pdo, [$username, $password]);
		if ($user !== false) {
			echo "Created user '$username' ({$user->id}) with password '$password'.";
		} else {
			echo "Unknown error while creating the admin user.";
		}
	} catch (PDOException $e) {
		echo "Creating an admin user failed (does one exist already?).";
	}
}

if (isset($_GET['password_cost'])) {
	$target = 1;
	$start = $end = 0;
	for ($cost = 10; $end - $start < $target; $cost++) {
		$start = microtime(true);
		User::hash('test', $cost);
		$end = microtime(true);
	}
	echo "Password cost suggestion: $cost.<br/>You can set this in classes/constants.php.";
}
?>

<hr/>

<h1>Available tools:</h1>

<ol>
	<li><a href="?create_tables">Create database tables</a></li>
	<li><a href="?create_folders">Create folders</a></li>
	<li><a href="?create_user">Create a user</a></li>
	<li><a href="?password_cost">Finding a good password cost</a></li>
</ol>

<p>When you're done, it would be the neatest to remove the /install folder (even though this whole control panel should not be accessible for the public).</p>