<?php
require_once 'sendhttp.php';

define('OK', 'OK');
define('KO_MISSINGNUMBER', 'KO_MISSINGNUMBER');
define('KO_BADNUMBER', 'KO_BADNUMBER');
define('KO_MISSINGFILE', 'KO_MISSINGFILE');
define('KO_BADFILE', 'KO_BADFILE');
define('KO_FAXNOTSENT', 'KO_FAXNOTSENT');

$site_host=$_SERVER['SERVER_NAME'];
$path='/api/sendfax.php';
$proto='http';

$to=$files=false;
$action='init';

if (isset($_POST['fax_send'])) {
	$action='send';
}

switch($action) {
	case 'send':
		if (isset($_POST['fax_to'])) {
			preg_match_all('/([\d]+)/', $_POST['fax_to'], $r);
			$to=implode(' ', $r[0]);
		}

		if (isset($_FILES['fax_document']['tmp_name']) and $_FILES['fax_document']['tmp_name']) {
			$name=$_FILES['fax_document']['name'];
			$tmp_name=$_FILES['fax_document']['tmp_name'];
			$type=$_FILES['fax_document']['type'];
			$files=array('document' => array('name' => $name, 'type' => $type, 'tmp_name' => $tmp_name));
		}
		break;
	default:
		break;
}

$fax_sent=false;
$missing_number=false;
$bad_number=false;
$missing_file=false;
$bad_file=false;
$fax_not_sent=false;

switch($action) {
	case 'send':
		$url=$proto.'://'.$site_host.$path;

		$args = array(
			'to'		=> $to,
		);
		$response=sendpost($url, $args, $files, true);

		if (!$response or $response[0] != 200) {
			$fax_not_sent=true;
			break;
		}

		$r=$response[2];

		$codes=explode(';', $r);

		foreach ($codes as $c) {
			switch($c) {
				case OK:
					$fax_sent=true;
					break;
				case KO_MISSINGNUMBER:
					$missing_number=true;
					break;
				case KO_BADNUMBER:
					$bad_number=true;
					break;
				case KO_MISSINGFILE:
					$missing_file=true;
					break;
				case KO_BADFILE:
					$bad_file=true;
					break;
				case KO_FAXNOTSENT:
				default:
					$fax_not_sent=true;
					break;
			}
		}
		break;
	default:
		break;
}
?>
<h6 id="faxexpress">Fax express</h6>
<form enctype="multipart/form-data" method="post" action="#faxexpress">
<p>Who will be receiving the fax?</p>
<p class="<?php echo ($missing_number or $bad_number) ? 'error' : 'info' ?>">Enter a series of telephone numbers.</p>
<p><textarea name="fax_to" id="fax_to" cols="50" rows="2"><?php echo $to; ?></textarea></p>
<p>Which document do you want to fax?</p>
<p class="<?php echo ($missing_file or $bad_file) ? 'error' : 'info' ?>">Select a text file or an image.</p>
<p><input type="hidden" name="MAX_FILE_SIZE" value="200000" /><input name="fax_document" id="fax_document" type="file" size="25" /></p>
<p><input name="fax_send" id="fax_send" type="submit" value="Fax" /></p>
<?php if ($fax_not_sent): ?>
<p class="error">Sending the fax has failed.</p>
<?php elseif ($fax_sent): ?>
<p class="info">Your fax has been sent.</p>
<?php else: ?>
<p class="info">Fill in the form and press Fax.</p>
<?php endif; ?>
</form>
