<?php
require('protect.php');
require_once('db_connect.php');

$error = array();

$id = isset($_POST['id']) ? trim($_POST['id']) : '';
$ajax = isset($_GET['ajax']) ? trim($_GET['ajax']) : '';
$kic = isset($_POST['kic']) ? trim($_POST['kic']) : '';
if (empty($kic) || !ctype_digit($kic)) $error[] = 'Invalid KIC number.';
$instrument = isset($_POST['instrument']) ? trim($_POST['instrument']) : '';
if (empty($instrument)) $error[] = 'No instrument was selected.';
$nobs = isset($_POST['nobs']) ? trim($_POST['nobs']) : '';
if (empty($nobs) || !ctype_digit($nobs)) $error[] = 'Invalid Number of Observations.';
$contact = isset($_POST['contact']) ? trim($_POST['contact']) : '';
if (empty($contact) || !ctype_digit($contact)) $error[] = 'No contact person was selected.';

// Workgroups:
$workgroup = isset($_POST['workgroup']) ? $_POST['workgroup'] : array();
if (count($workgroup)==0) {
	$error[] = 'No working group(s) selected.';
} else {
	foreach ($workgroup as $key => $wg) {
		if (!ctype_digit(trim($wg))) {
			unset($workgroup[$key]);
		} else {
			$workgroup[$key] = trim($wg);
		}
	}
	$workgroup = array_values($workgroup);
	if (count($workgroup)==0) $error[] = 'No working group(s) selected.';

	if ($workgroup == 0 || in_array(0, $workgroup)) {
		$str_workgroup = null;
	} elseif (is_array($workgroup)) {
		$str_workgroup = implode(',', $workgroup);
	} else {
		$str_workgroup = $workgroup;
	}
}

// Parse observer:
$observer_service = trim($_POST['observer_service']);
$observer_select = $_POST['observer_select'];
if ($observer_service == 'on') {
	$observer = null;
} else {
	if (empty($observer_select)) {
		$error[] = 'No observer(s) was selected.';

	} elseif (is_array($observer_select)) {
		foreach ($observer_select as $key => $value) {
			$observer_select[$key] = trim($value);
		}
		$observer = implode(',', array_values($observer_select));

	} elseif (strpos($observer_select, ',') !== false) {
		$observer_select = explode(',', $observer_select);
		foreach ($observer_select as $key => $value) {
			$observer_select[$key] = trim($value);
		}
		$observer = implode(',', array_values($observer_select));

	} elseif (ctype_digit(trim($observer_select))) {
		$observer = trim($observer_select);

	} else {
		$error[] = 'Invalid observer.';
	}
}

// Parse obtained:
$date_pattern = '/^(\d{2})-(\d{2})-(\d{4})$/i';
$obtained_from = isset($_POST['obtained_from']) ? trim($_POST['obtained_from']) : '';
$obtained_to = isset($_POST['obtained_to']) ? trim($_POST['obtained_to']) : '';
if (empty($obtained_from)) {
	$error[] = 'No obtained (from) date selected.';
} elseif (!preg_match($date_pattern, $obtained_from, $matches) || !checkdate($matches[2], $matches[1], $matches[3])) {
	$error[] = 'Invalid date provided in obtained (from). The correct format is DD-MM-YYYY.';
}
if (!empty($obtained_to) && (!preg_match($date_pattern, $obtained_to, $matches) || !checkdate($matches[2], $matches[1], $matches[3]))) {
	$error[] = 'Invalid date provided in obtained (to). The correct format is DD-MM-YYYY.';
}
// Must be a date format the database knows:
$obtained_from = date('Y-m-d', strtotime($obtained_from));
if (!empty($obtained_to)) {
	if (strtotime($obtained_from) > strtotime($obtained_to)) {
		$error[] = 'Invalid obtained date range.';
	} else {
		$obtained_to = date('Y-m-d', strtotime($obtained_to));
	}
} else {
	$obtained_to = null;
}

// Remarks:
$remarks = isset($_POST['remarks']) ? trim($_POST['remarks']) : '';
if (empty($remarks)) { $remarks = null; }

// Check that the KIC number exists in the database:
if (empty($error)) {
	$stmt = $db->prepare("SELECT Kepler_id FROM KIC WHERE Kepler_id=:starid;");
	$stmt->bindValue(':starid', $kic, PDO::PARAM_INT);
	$stmt->execute();
	if ($stmt->fetch() === false) {
		$error[] = 'Unknown KIC number. If you are positive that the KIC-number is correct, please contact the KASOC administrator.';
	}
	$stmt->closeCursor();
}

// Update the database:
if (empty($error)) {
	if (empty($id)) {
		$stmt = $db->prepare("INSERT INTO gb_observations (Kepler_id,instid,obtained_from,obtained_to,workgroup,nobs,observer,contact,remarks,uploader) VALUES (:starid,:instrument,:obtainedfrom,:obtainedto,:workgroup,:nobs,:observer,:contact,:remarks,:uploader);");
		$stmt->bindValue(':starid', $kic, PDO::PARAM_INT);
		$stmt->bindValue(':instrument', $instrument, PDO::PARAM_STR);
		$stmt->bindValue(':obtainedfrom', $obtained_from, PDO::PARAM_STR);
		$stmt->bindValue(':obtainedto', $obtained_to, PDO::PARAM_STR);
		$stmt->bindValue(':workgroup', $str_workgroup, PDO::PARAM_STR);
		$stmt->bindValue(':nobs', $nobs, PDO::PARAM_INT);
		$stmt->bindValue(':observer', $observer, PDO::PARAM_STR);
		$stmt->bindValue(':contact', $contact, PDO::PARAM_INT);
		$stmt->bindValue(':remarks', $remarks, PDO::PARAM_STR);
		$stmt->bindValue(':uploader', $_SESSION['userid'], PDO::PARAM_INT);
		$stmt->execute();

	// Only admins are allowed to alter observations:
	} elseif (user_is_gb_admin()) {
		$stmt = $db->prepare("UPDATE gb_observations SET Kepler_id=:starid,instid=:instrument,obtained_from=:obtainedfrom,obtained_to=:obtainedto,workgroup=:workgroup,nobs=:nobs,observer=:observer,contact=:contact,remarks=:remarks WHERE id=:id;");
		$stmt->bindValue(':starid', $kic, PDO::PARAM_INT);
		$stmt->bindValue(':instrument', $instrument, PDO::PARAM_STR);
		$stmt->bindValue(':obtainedfrom', $obtained_from, PDO::PARAM_STR);
		$stmt->bindValue(':obtainedto', $obtained_to, PDO::PARAM_STR);
		$stmt->bindValue(':workgroup', $str_workgroup, PDO::PARAM_STR);
		$stmt->bindValue(':nobs', $nobs, PDO::PARAM_INT);
		$stmt->bindValue(':observer', $observer, PDO::PARAM_STR);
		$stmt->bindValue(':contact', $contact, PDO::PARAM_INT);
		$stmt->bindValue(':remarks', $remarks, PDO::PARAM_STR);
		$stmt->bindValue(':id', $id, PDO::PARAM_INT);
		$stmt->execute();

	} else {
		$error[] = 'You are not allowed to edit observations.';
	}
}

if (!empty($error)) {
	echo "<i>The following errors were detected:</i><br />\n";
	echo "<ul style=\"padding-left:5px;margin-top:5px;\">";
	foreach ($error as $msg) {
		echo "<li>" . $msg . "</li>\n";
	}
	echo "</ul>";
}

// If the script was not called through ajax, redirect back to the form:
if ($ajax != 1) {
	require_once('redirect.php');
	redirect('./gb_edit.php', 303);
}
exit();
