<?

/*
 * This file is part of the 'Science Fair In A Box' project
 * SFIAB Website: http://www.sfiab.ca
 *
 * Copyright (C) 2005 Sci-Tech Ontario Inc <info@scitechontario.org>
 * Copyright (C) 2005 James Grant <james@lightbox.org>
 *
 * 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, version 2.
 *
 * 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; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
?>
<?
require ('../common.inc.php');
require_once ('../user.inc.php');
require_once ('../helper.inc.php');
user_auth_required('committee', 'config');

$divisionr = null;

if (get_value_from_array($_GET, 'action') == 'edit' || get_value_from_array($_GET, 'action') == 'new') {
	send_header(get_value_from_array($_GET, 'action') == 'edit' ? 'Edit Division' : 'New Division',
		array('Committee Main' => 'committee_main.php',
			'Science-ation Configuration' => 'config/index.php',
			'Project Divisions' => 'config/divisions.php'),
		'project_divisions');
} else {
	send_header('Project Divisions',
		array('Committee Main' => 'committee_main.php',
			'Science-ation Configuration' => 'config/index.php'),
		'project_divisions');
}

if (get_value_from_array($_POST, 'action') == 'edit') {
	if (get_value_from_array($_POST, 'id') && get_value_from_array($_POST, 'division')) {
		$q = $pdo->prepare("SELECT id FROM projectdivisions WHERE id=? AND year=?");
		$q->execute([$_POST['id'],$config['FAIRYEAR']]);
		if ($q->rowCount() && $_POST['saveid'] != $_POST['id']) {
			echo error(i18n('Division ID %1 already exists', array($_POST['id']), array('division ID')));
		} else {
			$stmt = $pdo->prepare('UPDATE projectdivisions SET '
				. "id=?, "
				. "division=?, "
				. "division_shortform=?"
				. "WHERE id=? AND year=?");
			$stmt->execute([$_POST['id'],stripslashes($_POST['division']),stripslashes($_POST['division_shortform']),$_POST['saveid'],$config['FAIRYEAR']]);

			// ###### Feature Specific - filtering divisions by category
			if ($config['filterdivisionbycategory'] == 'yes') {
				$stmt = $pdo->prepare("DELETE FROM projectcategoriesdivisions_link WHERE projectdivisions_id=? AND year=?");
				$stmt->execute([ $_POST['saveid'],$config['FAIRYEAR']]);
				if (is_array($_POST['divcat'])) {
					foreach ($_POST['divcat'] as $tempcat) {
						$stmt = $pdo->prepare('INSERT INTO projectcategoriesdivisions_link (projectdivisions_id,projectcategories_id,year) VALUES (?,?,?)');
						$stmt->execute([$_POST['id'],$tempcat,$config['FAIRYEAR']]);
					}
				}
			}
			// ###########

			echo happy(i18n('Division successfully saved'));
		}
	} else {
		echo error(i18n('All fields are required'));
	}
}

if (get_value_from_array($_POST, 'action') == 'new') {
	if (get_value_from_array($_POST, 'id') && get_value_from_array($_POST, 'division')) {
		$q = $pdo->prepare("SELECT id FROM projectdivisions WHERE id=? AND year=?");
		$q->execute([$_POST['id'],$config['FAIRYEAR']]);
		if ($q->rowCount()) {
			echo error(i18n('Division ID %1 already exists', array($_POST['id']), array('division ID')));
		} else {
			$stmt = $pdo->prepare('INSERT INTO projectdivisions (id,division,division_shortform,year) VALUES (?,?,?,?)');
			$stmt->execute([$_POST['id'],stripslashes($_POST['division']),stripslashes($_POST['division_shortform']),$config['FAIRYEAR']]);

			// ###### Feature Specific - filtering divisions by category
			if ($config['filterdivisionbycategory'] == 'yes') {
				foreach ($_POST['divcat'] as $tempcat) {
					$stmt = $pdo->prepare('INSERT INTO projectcategoriesdivisions_link (projectdivisions_id,projectcategories_id,year) VALUES (?,?)');
					$stmt->execute([$tempcat,$conference['id']]);
				}
			}
			// #######
			echo happy(i18n('Division successfully added'));
		}
	} else {
		echo error(i18n('All fields are required'));
	}
}

if (get_value_from_array($_GET, 'action') == 'remove' && get_value_from_array($_GET, 'remove')) {
	// ###### Feature Specific - filtering divisions by category - not conditional, cause even if they have the filtering turned off..if any links
	// for this division exist they should be deleted
	$stmt = $pdo->prepare("DELETE FROM projectcategoriesdivisions_link where projectdivisions_id=? AND year=?");
	$stmt->execute([$_GET['remove'], $config['FAIRYEAR']]);
	$stmt = $pdo->prepare("DELETE FROM projectdivisions WHERE id=? AND year=?");
	$stmt->execute([$_GET['remove'],$config['FAIRYEAR']]);
	echo happy(i18n('Division successfully removed'));
}

echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';

if (!get_value_from_array($_GET, 'action') == 'edit' || get_value_from_array($_GET, 'action') == 'new')
	echo '<a href="' . $_SERVER['PHP_SELF'] . '?action=new">' . i18n('Add new division') . "</a>\n";

echo '<table class="summarytable">';
echo '<tr>';
echo '<th>' . i18n('Division ID') . "</th>\n";
echo '<th>' . i18n('Division Name') . "</th>\n";
echo '<th>' . i18n('Short Form') . "</th>\n";
// ###### Feature Specific - filtering divisions by category
if ($config['filterdivisionbycategory'] == 'yes')
	echo '<th>' . i18n('Categories') . "</th>\n";
// #####
echo '<th>' . i18n('Actions') . "</th>\n";
echo '</tr>';

if (get_value_from_array($_GET, 'action') == 'edit' || get_value_from_array($_GET, 'action') == 'new') {
	echo '<input type="hidden" name="action" value="' . get_value_from_array($_GET, 'action') . "\">\n";
	if (get_value_from_array($_GET, 'action') == 'edit') {
		echo '<input type="hidden" name="saveid" value="' . get_value_from_array($_GET, 'edit') . "\">\n";
		$q = $pdo->prepare("SELECT * FROM projectdivisions WHERE id=? AND year=?");
		$q->execute([get_value_from_array($_GET, 'edit'),$config['FAIRYEAR']]);
		$divisionr = $q->fetch(PDO::FETCH_OBJ);

		$buttontext = 'Save';
	} else if (get_value_from_array($_GET, 'action') == 'new') {
		$buttontext = 'Add';
	}
	echo '<tr>';
	echo ' <td><input type="text" size="3" name="id" value="' . get_value_property_or_default($divisionr, 'id') . '" /></td>';
	echo ' <td><input type="text" size="40" name="division" value="' . get_value_property_or_default($divisionr, 'division') . '" /></td>';
	echo ' <td align="center"><input type="text" size="5" name="division_shortform" value="' . get_value_property_or_default($divisionr, 'division_shortform') . '" /></td>';

	// ###### Feature Specific - filtering divisions by category
	if ($config['filterdivisionbycategory'] == 'yes') {
		echo ' <td>';
		$q = $pdo->prepare("SELECT * FROM projectcategories WHERE year=? ORDER BY mingrade");
		$q->execute([$config['FAIRYEAR']]);
		while ($categoryr = $q->fetch(PDO::FETCH_OBJ)) {
			$query = 'SELECT * FROM projectcategoriesdivisions_link WHERE projectdivisions_id=? AND projectcategories_id=? AND year=?';
			$t = $pdo->prepare($query);
			$t->execute([$divisionr->id,$categoryr->id,$config['FAIRYEAR']]);
			if ($t && $t->rowCount() > 0)
				echo "<nobr><input type=\"checkbox\" name=\"divcat[]\" value=\"$categoryr->id\" checked=\"checked\" /> $categoryr->category</nobr><br/>";
			else
				echo "<nobr><input type=\"checkbox\" name=\"divcat[]\" value=\"$categoryr->id\" /> $categoryr->category</nobr><br/>";
		}
		echo '</td>';
	}

	echo ' <td><input type="submit" value="' . i18n($buttontext) . '" /></td>';
	echo '</tr>';
} else {
	$q = $pdo->prepare("SELECT * FROM projectdivisions WHERE year=? ORDER BY id");
	$q->execute([$config['FAIRYEAR']]);
	while ($r = $q->fetch(PDO::FETCH_OBJ)) {
		echo '<tr>';
		echo " <td>$r->id</td>";
		echo ' <td>' . i18n($r->division) . '</td>';
		echo " <td align=\"center\">$r->division_shortform</td>";
		// ###### Feature Specific - filtering divisions by category
		if ($config['filterdivisionbycategory'] == 'yes') {
			$c = $pdo->prepare("SELECT category FROM projectcategoriesdivisions_link, projectcategories 
					WHERE projectcategoriesdivisions_link.projectcategories_id = projectcategories.id
				AND projectdivisions_id=?
				AND projectcategoriesdivisions_link.year=?
				AND projectcategories.year=?
				ORDER BY projectcategories.mingrade");
			$c->execute([$r->id,$config['FAIRYEAR'],$config['FAIRYEAR']]);
			show_pdo_errors_if_any($pdo);
			if (!$c) {
				$tempcat = '&nbsp;';
			} else {
				$tempcat = '';
				while ($categoryr = $c->fetch(PDO::FETCH_OBJ)) {
					$tempcat .= ',' . $categoryr->category;
				}
				$tempcat = substr($tempcat, 1);
			}
			echo "<td> {$tempcat} </td>";
		}
		// ############
		echo ' <td>';
		echo '<a title="Edit" href="' . $_SERVER['PHP_SELF'] . "?action=edit&amp;edit=$r->id\"><img src=\"" . $config['SFIABDIRECTORY'] . '/images/16/edit.' . $config['icon_extension'] . '" border=0></a>';
		echo '&nbsp; &nbsp;';
		echo '<a title="Remove" onClick="return confirmClick(\'Are you sure you want to remove this division?\');" href="' . $_SERVER['PHP_SELF'] . "?action=remove&amp;remove=$r->id\"><img src=\"" . $config['SFIABDIRECTORY'] . '/images/16/button_cancel.' . $config['icon_extension'] . '" border=0></a>';
		echo ' </td>';
		echo '</tr>';
	}
}
echo '</table>';
echo '</form>';
echo i18n("You should assign the 'Division ID's in numerical order, starting with 1.  This Division ID is used to generate the project number");

send_footer();
?>