<?php
	/***********************************************************************************
	*   Filename    : editcompany.php
	*   Description : Form to edit company data
	*
	*   Date        Modification By      Description
	*   20/10/2008  Shane Schokman       Initial Creation
	*   23/01/2009  Kenneth Ho           Adaptation to Digivet-Petsafe
	* 	23/08/2022  John Muffett         Reworked for Data API
    *
	*   Copyright Keysoft Pty Ltd 2022
	***********************************************************************************/

	/******************** Global Settings ********************/
	require_once '../phpobjects/common/global.php';

	/********************* Page Settings *********************/
	$gaPage['title'] = 'Petsafe.com.au';
	$gaPage['root_directory'] = '..';
	$gaPage['colour'] = 'orange';

    /************ Only allow logged in vets to this area ************/

	if ($_SESSION['LoggedIn'] == 0 or $_SESSION['VetID'] == ''){
		// Redirect
		fRedirect('logout.php');
		fCleanup();
	}
	
	/********************* Page Defaults *********************/
	fDefaultParameter('err_code', $_GET, '');
	fDefaultParameter('companyid', $_GET, '');
	fDefaultParameter('owner_state', $_GET, '');
	fDefaultParameter('owner_suburb', $_GET, '');
	fDefaultParameter('mail_state', $_GET, '');
	fDefaultParameter('mail_suburb', $_GET, '');

	$companyid = $_GET['companyid'];

	//get vet record
	$fm = \Keysoft\FileMaker\Client::getInstance();

	$filters = [						// isnt used at all in the code?
		"_sk_vet_id eq '{$_SESSION['VetID']}'",
		"_sk_company_id eq '{$companyid}'"
	];

	$odataQuery = $fm->buildODataQuery([
		'filter' => implode(' and ', $filters),
		'count'  => true
	]);

	$fmrVet = $fm->get('Company_Vet_Relation', $odataQuery, true);
	if (!$fmrVet['success'] || $fmrVet['data']['count'] == 0) {
		fRedirect('myaccount.php'); 
		fCleanup();
	}

	$fmcVet = $fmrVet['data']['value'][0];


	// get company details					// ! Check if failing
	$odataQuery = $fm->buildODataQuery([
		'filter' => "_pk_company_id eq {$companyid}",
		'count'  => true
	]);
	$fmrCompany = $fm->get('Companies', $odataQuery, $allPages = true);

	$records = $fmrCompany['data']['value'] ?? [];
	if (empty($records)) {
		var_dump($fmrCompany);
		die("No company found for ID {$companyid} amount {$fmrCompany['data']['count']}");
	}

	$fmcCompany = $records[0]; // first record
	$recordid = $fmcCompany['recordId'] ?? null;

	$fields = $fmcCompany ?? [];

	$companyName       = $fields['Company Name'] ?? '';
	$companyPhone      = $fields['Phone'] ?? '';
	$companyFax        = $fields['Fax'] ?? '';
	$companyWeekdays   = $fields['Weekdays'] ?? '';
	$companySat        = $fields['Saturday'] ?? '';
	$companySun        = $fields['Sunday'] ?? '';
	$companyHouseCalls = $fields['House Calls'] ?? '';
	$companyEmergency  = $fields['Emergency Service'] ?? '';
	$companySpecial    = $fields['Specialities'] ?? '';
	$companyOther      = $fields['Other Info'] ?? '';
	$companyEmail      = $fields['Email'] ?? '';
	$companyWebsite    = $fields['Web Site'] ?? '';
	$street            = $fields['Street'] ?? '';
	$suburb            = $fields['Suburb'] ?? '';
	$state             = $fields['State'] ?? '';
	$postcode          = $fields['Postcode'] ?? '';
	$mailstreet        = $fields['Mailing Street'] ?? '';
	$mailsuburb        = $fields['Mailing Suburb'] ?? '';
	$mailstate         = $fields['Mailing State'] ?? '';
	$mailpostcode      = $fields['Mailing Postcode'] ?? '';
	$accountnumber     = $fields['myob_account_no'] ?? '';

	// check if there is state
	// if yes, then prefill state
	// if no, get out
	// check if there is suburb
	// if yes, then prefill/select suburb
	// if no, get out
	// initialise the popups, so they can be echoed further down
		$states = ["ACT","NSW","NT","QLD","SA","TAS","WA","VIC"];
		$state_popup = popup($states, 'owner_state', $state,'onchange="setSuburbValueList()"');
		$mailstate_popup = popup($states, 'mail_state', $mailstate,'onchange="setSuburbValueListMail()"');
		
	if (trim($state) != ""){
		if (trim($suburb) != ""){
			// preselect suburb
			$suburbs = getSuburbs($state);
			$suburb_popup = popup($suburbs, 'owner_suburb', $suburb,'onchange="setPostcodeValueList()"');

			if (trim($postcode) != ""){
				// preselect postcode
                $postcodes = getPostCodes($state, $suburb);
				$postcode_popup = popup($postcodes, 'owner_postcode', $postcode);
			}
		}
	}

	if (trim($mailstate) != ""){
		// retrieve states and preselect
		if (trim($mailsuburb) != ""){
			$suburbs = getSuburbs($state);
			$mailsuburb_popup = popup($suburbs, 'mail_suburb', $mailsuburb,'onchange="setPostcodeValueListMail()"');
			if (trim($mailpostcode) != ""){
				$postcodes = getPostCodes($state, $suburb);
				$mailpostcode_popup = popup($postcodes, 'mail_postcode', $mailpostcode);
			}
		}
	}

	// fill suburbs
	if (isset($_GET['hello_from_ajax1'])) {
		if ( empty($_GET['owner_state']) ) {
			$suburb_popup = '<select name="owner_suburb" disabled="disabled"></select>';
		} else {
			$suburbs = getSuburbs($_GET['owner_state']);
			$suburb_popup = popup($suburbs, 'owner_suburb', $selected_suburb,'onchange="setPostcodeValueList()"');
		}
		echo $suburb_popup;
		die;
	}

	// fill postcodes
	if (isset($_GET['hello_from_ajax2'])) {
		if ( empty($_GET['owner_suburb']) ) {
			$postcode_popup = '<select name="owner_postcode" disabled="disabled"></select>';
		} else {
			$postcodes = getPostCodes($_GET['owner_state'], $_GET['owner_suburb']);
			if (count($postcodes) == 1){
				$selected_postcode = $postcodes[0];
			}
			$postcode_popup = popup($postcodes, 'owner_postcode', $selected_postcode);
		}
		echo $postcode_popup;
		die;
	}

	// fill suburbs - mailing
	if (isset($_GET['hello_from_ajax1m'])) {
		if ( empty($_GET['mail_state']) ) {
			$mailsuburb_popup = '<select name="mail_suburb" disabled="disabled"></select>';
		} else {
			$suburbs = getSuburbs($_GET['mail_state']);
			$mailsuburb_popup = popup($suburbs, 'mail_suburb', $selected_mailsuburb,'onchange="setPostcodeValueListMail()"');
		}
		echo $mailsuburb_popup;
		die;
	}

	// fill postcodes - mailing
	if (isset($_GET['hello_from_ajax2m'])) {
		if ( empty($_GET['mail_suburb']) ) {
			$mailpostcode_popup = '<select name="mail_postcode" disabled="disabled"></select>';
		} else {
            $postcodes = getPostCodes($_GET['mail_state'], $_GET['mail_suburb']);
            if (count($postcodes) == 1){
				$selected_mailpostcode = $postcodes[0];
			}
			$mailpostcode_popup = popup($postcodes, 'mail_postcode', $selected_mailpostcode);
		}
		echo $mailpostcode_popup;
		die;
	}

	// default values
	if (empty($_POST['owner_state'])) {
		$selected_state = '';
	} else {
		$selected_state = $_POST['owner_state'];
	}
	if (empty($_POST['owner_suburb'])) {
		$selected_suburb = '';
	} else {
		$selected_suburb = $_POST['owner_suburb'];
	}
	if (empty($_POST['owner_postcode'])) {
		$selected_postcode = '';
	} else {
		$selected_postcode = $_POST['owner_postcode'];
	}
	if (empty($_POST['mail_state'])) {
		$selected_mailstate = '';
	} else {
		$selected_mailstate = $_POST['mail_state'];
	}
	if (empty($_POST['mail_suburb'])) {
		$selected_mailsuburb = '';
	} else {
		$selected_mailsuburb = $_POST['mail_suburb'];
	}
	if (empty($_POST['mail_postcode'])) {
		$selected_mailpostcode = '';
	} else {
		$selected_mailpostcode = $_POST['mail_postcode'];
	}


	// initialise lists on first load - if empty
	if (trim($state) == ''){
		$state_popup = popup($states, 'owner_state', $selected_state,'onchange="setSuburbValueList()"');
	}
	if (trim($suburb) == ''){
		$suburb_popup = '<select name="owner_suburb" disabled="disabled"></select>';
	}
	if (trim($postcode) == ''){
		$postcode_popup = '<select name="owner_postcode" disabled="disabled"></select>';
	}
	if (trim($mailstate) == ''){
		$mailstate_popup = popup($states, 'mail_state', $selected_mailstate,'onchange="setSuburbValueListMail()"');
	}
	if (trim($mailsuburb) == ''){
		$mailsuburb_popup = '<select name="mail_suburb" disabled="disabled"></select>';
	}
	if (trim($mailpostcode) == ''){
		$mailpostcode_popup = '<select name="mail_postcode" disabled="disabled"></select>';
	}

	// function to create select list dynamically
	// function popup($values, $name, $selected_value = '', $extras = '') {
	// 	$popup = '<select name="' . $name . '" ' . $extras . '>';
	// 	$popup.= '<option value="">- Please select -</option>';
	// 	foreach($values as $value) {
	// 		if (strtoupper($value) == strtoupper($selected_value)) {
	// 			$selected = 'selected="selected"';
	// 		} else {
	// 			$selected = '';
	// 		}
	// 		$popup.= '<option value="' . $value . '" ' . $selected . '>' . $value . '</option>';
	// 	}
	// 	$popup.= '</select>';
	// 	return $popup;
	// }

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
<?php require '../phpobjects/templates/common/page_head.php'; ?>

<script type="text/javascript" src="../javascripts/prototype.js"></script>
<script type="text/javascript" src="../javascripts/common.js"></script>

<script language="javascript">
	// handler to fill suburbs
	function setSuburbValueList(){

		var state_popup = document.forms[0].elements['owner_state'];
		var selected_state = state_popup.value;
		var suburb_popup = document.forms[0].elements['owner_suburb'];
		var postcode_popup = document.forms[0].elements['owner_postcode'];
		suburb_popup.disabled = false;
		postcode_popup.options.length = 0;
		postcode_popup.disabled = true;
		suburb_popup.options[suburb_popup.length] = new Option('loading...','');
		suburb_popup.selectedIndex = suburb_popup.length-1;

		var url = 'editcompany.php?companyid='+ '<?php echo $companyid; ?>' + '&hello_from_ajax1=true&owner_state='+selected_state;
		var target = 'suburb_container';
		var result = new Ajax.Updater(target, url,{method: 'get'});
		suburb_popup.focus();
	}

	// handler to fill postcodes
	function setPostcodeValueList(){
		var state_popup = document.forms[0].elements['owner_state'];
		var selected_state = state_popup.value;
		var suburb_popup = document.forms[0].elements['owner_suburb'];
		var selected_suburb = suburb_popup.value;
		var postcode_popup = document.forms[0].elements['owner_postcode'];
		postcode_popup.disabled = false;
		postcode_popup.options[postcode_popup.length] = new Option('loading...','');
		postcode_popup.selectedIndex = postcode_popup.length-1;
		var url = 'editcompany.php?companyid='+ '<?php echo $companyid; ?>' + '&hello_from_ajax2=true&owner_suburb='+selected_suburb+'&owner_state='+selected_state;
		var target = 'postcode_container';
		var result = new Ajax.Updater(target, url,{method: 'get'});
		postcode_popup.focus();
	}

	// handler to fill suburbs - mailing
	function setSuburbValueListMail(){
		var state_popup = document.forms[0].elements['mail_state'];
		var selected_state = state_popup.value;
		var suburb_popup = document.forms[0].elements['mail_suburb'];
		var postcode_popup = document.forms[0].elements['mail_postcode'];
		suburb_popup.disabled = false;
		postcode_popup.options.length = 0;
		postcode_popup.disabled = true;
		suburb_popup.options[suburb_popup.length] = new Option('loading...','');
		suburb_popup.selectedIndex = suburb_popup.length-1;
		var url = 'editcompany.php?companyid='+ '<?php echo $companyid; ?>' + '&hello_from_ajax1m=true&mail_state='+selected_state;
		var target = 'mailsuburb_container';
		var result = new Ajax.Updater(target, url,{method: 'get'});
		suburb_popup.focus();
	}

	// handler to fill postcodes - mailing
	function setPostcodeValueListMail(){
		var state_popup = document.forms[0].elements['mail_state'];
		var selected_state = state_popup.value;
		var suburb_popup = document.forms[0].elements['mail_suburb'];
		var selected_suburb = suburb_popup.value;
		var postcode_popup = document.forms[0].elements['mail_postcode'];
		postcode_popup.disabled = false;
		postcode_popup.options[postcode_popup.length] = new Option('loading...','');
		postcode_popup.selectedIndex = postcode_popup.length-1;
		var url = 'editcompany.php?companyid='+ '<?php echo $companyid; ?>' + '&hello_from_ajax2m=true&mail_suburb='+selected_suburb+'&mail_state='+selected_state;
		var target = 'mailpostcode_container';
		var result = new Ajax.Updater(target, url,{method: 'get'});
		postcode_popup.focus();
	}

	function trim(mystring){
		return mystring.replace(/^\s+|\s+$/g, '') ;
	}

	function validateForm(myform) {
		var error1 = 'Please complete the following mandatory field(s):\n';
		var error2 = 'Company phone number must be 10 digits long.';
		var error3 = 'Company fax number must be 10 digits long.';
		var mandatory_err = 0;

		// check mandatory fields
		// company_name,  company_phone, 
		// company_street, company_suburb, company_state, company_postcode,
		// mailing_street, mailing_suburb, mailing_state, mailing_postcode
		if (trim(myform.company_name.value) == ''){
			myform.company_firstname.value = '';
			error1 = error1 + '\n- Company Name';
			mandatory_err = 1;
		}
		if (trim(myform.company_phone.value) == ''){
			myform.company_phone.value = '';
			error1 = error1 + '\n- Phone';
			mandatory_err = 1;
		}
		if (trim(myform.company_fax.value) == ''){
			myform.company_fax.value = '';
			error1 = error1 + '\n- Fax';
			mandatory_err = 1;
		}

		if (trim(myform.owner_address.value) == ''){
			myform.owner_address.value = '';
			error1 = error1 + '\n- Company Street Address';
			mandatory_err = 1;
		}
		if (trim(myform.owner_suburb.value) == ''){
			myform.owner_suburb.value = '';
			error1 = error1 + '\n- Company Suburb';
			mandatory_err = 1;
		}
		if (myform.owner_state.selectedIndex == 0){
			error1 = error1 + '\n- Company State';
			mandatory_err = 1;
		}
		if (trim(myform.owner_postcode.value) == ''){
			myform.owner_postcode.value = '';
			error1 = error1 + '\n- Company Postcode';
			mandatory_err = 1;
		}

		if (!(myform.match_mailaddr.checked)){
			if (trim(myform.mail_address.value) == ''){
				myform.mail_address.value = '';
				error1 = error1 + '\n- Mailing Address';
				mandatory_err = 1;
			}
			if (trim(myform.mail_suburb.value) == ''){
				myform.mail_suburb.value = '';
				error1 = error1 + '\n- Mailing Suburb';
				mandatory_err = 1;
			}
			if (myform.mail_state.selectedIndex == 0){
				error1 = error1 + '\n- Mailing State';
				mandatory_err = 1;
			}
			if (trim(myform.mail_postcode.value) == ''){
				myform.mail_postcode.value = '';
				error1 = error1 + '\n- Mailing Postcode';
				mandatory_err = 1;
			}
		}
		
		if (mandatory_err != 0){
			alert(error1);
			return false;
		}

		// check if phone numbers, if defined, are 10 digits
		if (myform.company_phone.value.replace(/\D/g,'').length != 10){
			alert(error2);
			myform.company_phone.focus();
			return false;
		}
		if (myform.company_fax.value.replace(/\D/g,'').length != 10){
			alert(error3);
			myform.company_fax.focus();
			return false;
		}

		return true;
	}
</script>

</head>

<?php

require '../phpobjects/templates/common/page_header.php';
/*********************** Page Start **********************/
?>

<td valign="top">

<?php

	echo '<br/><h2 class="orangeheading">Edit Clinic Details</h2><br/>';

?>

<form action="editcompany_submit.php" method="post" name="frmCompany" id="frmCompany">
<table border="0" width="90%">
	<tr>
		<td>Clinic ID</td>
		<td valign="top">
			<b><?php echo $accountnumber; ?></b>
		</td>
	</tr>
	<tr>
		<td><span style="color:red"><sup>*</sup></span> Clinic Name</td>
		<td valign="top">
			<input type="text" size="30" readonly value="<?php echo $companyName; ?>" name="company_name" class="disabled" />
		</td>
	</tr>
	<tr>
		<td colspan="2">&nbsp;</td>
	</tr>
	<tr>
		<td><span style="color:red"><sup>*</sup></span> Phone</td>
		<td valign="top">
			<input type="text" size="20" value="<?php echo $companyPhone; ?>" name="company_phone" />
		</td>
	</tr>
	<tr>
		<td><span style="color:red"><sup>*</sup></span> Fax</td>
		<td valign="top">
			<input type="text" size="20" value="<?php echo $companyFax; ?>" name="company_fax" />
		</td>
	</tr>
	<tr>
		<td>Office Hours</td>
		<td valign="top">
			Weekdays: <input type="text" size="20" value="<?php echo $companyWeekdays; ?>" name="company_weekdays" />
			<br/>
			Saturday: <input type="text" size="20" value="<?php echo $companySat; ?>" name="company_sat" />
			<br/>
			Sunday: <input type="text" size="20" value="<?php echo $companySun; ?>" name="company_sun" />
		</td>
	</tr>
	<tr>
		<td>House Calls</td>
		<td valign="top">
			<input type="text" size="20" value="<?php echo $companyHouseCalls; ?>" name="company_housecalls" />
		</td>
	</tr>
	<tr>
		<td>Emergency Service</td>
		<td valign="top">
			<input type="text" size="20" value="<?php echo $companyEmergency; ?>" name="company_emergency" />
		</td>
	</tr>
	<tr>
		<td colspan="2">&nbsp;</td>
	</tr>
	<tr>
		<td>Specialties</td>
		<td valign="top">
			<input type="text" size="30" value="<?php echo $companySpecial; ?>" name="company_special" />
		</td>
	</tr>
	<tr>
		<td>Other Info</td>
		<td valign="top">
			<input type="text" size="30" value="<?php echo $companyOther; ?>" name="company_other" />
		</td>
	</tr>
	<tr>
		<td>E-mail</td>
		<td valign="top">
			<input type="text" size="30" value="<?php echo $companyEmail; ?>" name="company_email" />
		</td>
	</tr>
	<tr>
		<td>Web Site</td>
		<td valign="top">
			<input type="text" size="40" value="<?php echo $companyWebsite; ?>" name="company_website" />
		</td>
	</tr>
	<tr>
		<td colspan="2">&nbsp;</td>
	</tr>
	<tr>
		<td><span style="color:red"><sup>*</sup></span> Street Address</td>
		<td valign="top">
			Unit/Street No &nbsp;&nbsp;Street Name<br/>
			<input type="text" size="30" value="<?php echo $street; ?>" name="owner_address" />
		</td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> State</td>
		<td valign="top">
			<?php echo $state_popup ?>
		<td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> Suburb</td>
		<td valign="top">
			<div id="suburb_container"><?php echo $suburb_popup ?></div>
		<td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> Postcode</td>
		<td valign="top">
			<div id="postcode_container"><?php echo $postcode_popup ?></div>
		<td>
	</tr>
	<tr>
		<td colspan="2">&nbsp;</td>
	</tr>
	<tr>
		<td colspan="2"><input type="checkbox" name="match_mailaddr" value="1" onclick="if (this.checked){document.getElementById('mailaddr').style.display = 'none'; document.getElementById('mailaddr').style.visibility = 'hidden'; } else { document.getElementById('mailaddr').style.display = ''; document.getElementById('mailaddr').style.visibility = 'visible'; }" /> Mailing address same as above</td>
	</tr>
	<tr>
		<td colspan="2">
			<div id="mailaddr" name="mailaddr">
			<table width="100%" border="0">
			<tr>
				<td><span style="color:red"><sup>*</sup></span> Mailing Address</td>
				<td valign="top">
					<input type="text" size="30" value="<?php echo $mailstreet; ?>" name="mail_address" />
				</td>
			</tr>
			<tr>
				<td valign="top"><span style="color:red"><sup>*</sup></span> State</td>
				<td valign="top">
					<?php echo $mailstate_popup ?>
				<td>
			</tr>
			<tr>
				<td valign="top"><span style="color:red"><sup>*</sup></span> Suburb</td>
				<td valign="top">
					<div id="mailsuburb_container"><?php echo $mailsuburb_popup ?></div>
				<td>
			</tr>
			<tr>
				<td valign="top"><span style="color:red"><sup>*</sup></span> Postcode</td>
				<td valign="top">
					<div id="mailpostcode_container"><?php echo $mailpostcode_popup ?></div>
				<td>
			</tr>
			</table>
			</div>
		</td>
	</tr>
	<tr>
		<td colspan="2">&nbsp;</td>
	</tr>
	<tr>
		<td valign="top">&nbsp;</td>
		<td valign="top">
			<input type="hidden" name="companyid" value="<?php echo $companyid; ?>" />
			<input type="hidden" name="recordid" value="<?php echo $recordid; ?>" />
			<br/><input type="submit" value="Update Details" class="button" onclick="javascript: if(!validateForm(this.form)) return false;" />
			<input type="button" value="Cancel" class="button" onclick="javascript: window.location.href = 'myaccount.php';" />
		</td>
	</tr>
</table>
</form>

<br/><br/>

</td>

<?php
/************************ Page End ***********************/

require '../phpobjects/templates/common/page_footer.php';
?>

</html>
<?php fCleanup(); ?>