<?PHP

require_once 'class.templatepage.php';

class ContactPage extends TemplatePage {
	public function __construct() {
		if ( @$_GET['subject'] != 'share' ) {
			$this->cache_time = 3600;
			$this->cache_qs = [ 'subject', 'user_id' ];
		}
		parent::__construct();
	}

	public function generate() {
		$this->write_menu( 'contact' );
		$subject = getString( 'subject' );
		$user_id = getInt( 'user_id' );
		$uri = getString( 'uri' );
		$uri_title = getString( 'title' );

		if ( strpos( $_SERVER['REQUEST_URI'], '/contact' ) === false ) {
			$this->redirect( "{$this->base}/contact/$subject", true );
		}

		$user_to = null;
		if ( $user_id ) {
			$user = new User( $this );
			$stmt = $user->get( [ 'user_id' => $user_id, 'receive_email' => 1 ] );
			if ( $row = $stmt->fetch_assoc() ) {
				$user_to = new User( $this, $row );
			} else {
				$this->redirect( "{$this->base}/musicians" );
			}
		}

		if ( $user_to && !$user_to->get_data( 'public' ) && !$this->session->user ) {
			$this->write_lang_title( 'title-private-profile' );
			$this->output( '<h1>' . $this->language( 'title-private-profile' ) . '</h1>' );
			$this->output( '<p>' . $this->language( 'help-private-profile', [ 'login-link-start' => '<a href="login/?r=' . $this->escape_text( urlencode( $user->get_link() ) ) . '">', 'login-link-end' => '</a>' ] ) . '</p>' );
			return;
		}

		$result = '';

		$form = new Form( $this );
		$form->add_field( new Field( 'hidden', 'human', 0 ) );
		$this->output( '$( ' . json_encode( '#' . $form->get_field_id( 'human' ) ) . ' ).val( ' . time() . ' );', 'script', 'javascript' );
		if ( !$this->session->user ) {
			$form->add_field( new Field( 'textbox', 'name', '', $this->language( 'label-contact-name' ), $this->language( 'form-ins-contact-name' ), true ) );
			$form->add_validator( new Validator( 'name', 'stringLength', $this->language( 'form-err-contact-name' ), [ 'from' => 1, 'to' => 100 ] ) );
			$form->add_field( new Field( 'textbox', 'email', '', $this->language( 'label-contact-email' ), $this->language( 'form-ins-contact-email' ), true ) );
			$form->add_validator( new Validator( 'email', 'validEmail', $this->language( 'form-err-contact-email' ) ) );
		} elseif ( !$this->session->user->has_real_email() ) {
			$form->add_html_field( $this->session->user->get_name(), $this->language( 'label-contact-from' ), $this->language( 'form-ins-contact-from' ) );
			$form->add_field( new Field( 'textbox', 'email', '', $this->language( 'label-contact-email' ), $this->language( 'form-ins-contact-email' ), true ) );
			$form->add_validator( new Validator( 'email', 'validEmail', $this->language( 'form-err-contact-email' ) ) );
		} else {
			$form->add_html_field( $this->session->user->get_name(), $this->language( 'label-contact-from' ), $this->language( 'form-ins-contact-from' ) );
		}

		if ( $subject == 'share' ) {
			$form->add_field( new Field( 'textbox', 'recipients', '', $this->language( 'label-contact-recipients' ), $this->language( 'form-ins-contact-recipients' ), true ) );
			// $form->add_validator(new Validator('recipients', 'stringLength', $this->language('form-err-contact-recipients'), array('from' => 1, 'to' => null)));
			$form->add_validator( new Validator( 'recipients', 'validEmail', $this->language( 'form-err-contact-email' ) ) );
			$field = $form->add_field( new Field( 'textarea', 'message', '', $this->language( 'label-contact-message-optional' ), $this->language( 'form-ins-contact-message-optional' ) ) );
			$field->maxlength = 200;
			$form->add_validator( new Validator( 'message', 'stringLength', 'Max 200 chars.', [ 'from' => 0, 'to' => 200 ] ) ); // lang
		} else {
			$form->add_html_field( $user_to ? $user_to->get_linked_name() : 'Cantorion', $this->language( 'label-contact-to' ), $this->language( 'form-ins-contact-to' ) );
			$form->add_field( new Field( 'textarea', 'message', '', $this->language( 'label-contact-message' ), $this->language( 'form-ins-contact-message' ), true ) );
			$form->add_validator( new Validator( 'message', 'stringLength', $this->language( 'form-err-contact-message' ), [ 'from' => 1, 'to' => null ] ) );
		}

		# if(!$this->session->user) {
			$form->add_field( new Field( 'captcha', 'captcha', '', $this->language( 'label-general-captcha' ), $this->language( 'form-ins-general-captcha' ), true ) );
			$form->add_validator( new Validator( 'captcha', 'captcha', $this->language( 'form-err-general-captcha' ) ) );
		# }
		$form->add_button( $this->language( 'button-send', null, false, false ), 'send', 'envelope' );
		if ( $user_to ) {
			$form->add_link_button( $this->language( 'button-back', null, false, false ), 'back', $user_to->get_link(), 'arrow-left', 'alt' );
		} else {
			$form->add_field( new Field( 'hidden', 'referrer', @$_SERVER['HTTP_REFERER'] ) );
		}

		if ( $form->isPostBack() ) {
			$form->validate();
			if ( $form->valid ) {
				if ( time() - $form->data['human'] > 3600 ) {
					// JS test, tell spammers the message has been sent
					$result = 'SENT';
				} else {
					// message credits
					if ( $subject == 'user' ) {
						$this->authenticate( 'message_credits' );
						$this->session->user->set_data( 'message_credits', max( 0, $this->session->user->get_data( 'message_credits' ) - 1 ) );
						$this->session->user->save();
						$this->session->save();
					}

					if ( !$this->session->user ) {
						$name_from = $this->escape_text( $form->data['name'] );
						$email_from = $form->data['email'];
					} elseif ( !$this->session->user->has_real_email() ) {
						$name_from = $this->session->user->get_name();
						$email_from = $form->data['email'];
					} else {
						$name_from = $this->session->user->get_name();
						$email_from = $this->session->user->get_data( 'email' );
					}

					$lang_to = $this->session->set_lang;

					$recipients = [];
					$extra_data = '';
					if ( $subject == 'share' ) {
						$name_to = '';
						// $recipients = array_map('trim', preg_split("/(,|;|\r\n|\r|\n)/", $form->data['recipients']));
						$recipients = [ $form->data['recipients'] ];
						$share_message = $this->language( 'email-contact-share', [ 'sender-name' => $name_from ], false, false ) . "\r\n\r\n";
						$share_message .= $this->livebase . str_replace( ' ', '%20', $uri );
						if ( $form->data['message'] ) {
							$share_message .= "\r\n\r\n" . $this->language( 'email-contact-share-message', null, false, false ) . "\r\n\r\n" . $form->data['message'];
						}
						$form->data['message'] = $share_message;
						$email_subject = 'Cantorion.org';
					} else {
						if ( $user_to ) {
							$lang_to = $user_to->get_data( 'preferred_lang' );
							$name_to = $user_to->get_name();
							$recipients[] = $user_to->has_real_email() ? $user_to->get_data( 'email' ) : $user_to->get_data( 'fb_user_id' );
							$email_subject = $this->language( 'email-subject-from', [ 'sender-name' => $name_from ], $lang_to, false );
						} else {
							$name_to = 'Cantorion';
							$lang_to = 'en';
							$recipients[] = 'contact@cantorion.org';
							$email_subject = 'Cantorion website contact: ' . $subject . ' from ' . $name_from;
							$extra_data = "\r\n\r\nIP: " . @$_SERVER['REMOTE_ADDR'] . "\r\nReferrer: " . @$form->data['referrer'];
						}
					}

					$message =
						$form->data['message'] .
						"\r\n\r\n-----------\r\n" .
						$this->language( 'email-footer', [ 'sender-name' => $name_from, 'sender-email' => $email_from, 'cantorion-url' => $this->livebase ], $lang_to, false ) .
						$extra_data;

					$result = 'SENT';
					$send_count = 0;
					foreach ( $recipients as $email_to ) {
						if ( strpos( $email_to, '@' ) === false ) {
							$fb_message = str_replace( "\r\n", " -- ", $email_subject . "\r\n" . str_replace( "\r\n\r\n-----------", "", $message ) );
							if ( $this->test_environment ) {
								$this->output( '<pre>' . $this->escape_text( "email_to: $email_to\r\nmessage: $fb_message" ) . '</pre><hr />' );
							} else {
								try {
									// $this->facebook_client()->api_client->notifications_send(array($email_to), $fb_message, 'app_to_user');
								} catch ( Exception $e ) {
									$result = 'FAILED';
								}
							}
						} else {
							if ( $email_to ) {
								if ( $this->smtp_mail( [ $email_to, $name_to ], $email_subject, $message, [ $email_from, $name_from ] ) ) {
									$send_count++;
								} else {
									$result = 'FAILED';
								}
							}
						}
					}
				}
			}
		}

		$page_title = '';
		switch ( $subject ) {
			case 'request':
				$title = $this->language( 'title-contact-request' );
				$intro = '<p>' . $this->language( 'help-contact-request' ) . '</p>';
				break;
			case 'submit':
				$this->redirect( $this->base . '/music/upload' );
				break;
			case 'advertise':
				$title = $this->language( 'title-contact-advertise' );
				$intro = '<p>' . $this->language( 'help-contact-advertise' ) . '</p>';
				break;
			case 'user':
				$title = $this->language( 'title-contact-user', [ 'recipient-name' => $user_to->get_name() ] );
				$intro = '';
				break;
			case 'share':
				// force away unless:
				// 1. valid QS, 2. http referrer set, 3. http referrer is cantorion
				if ( !$uri || !$uri_title || !isset( $_SERVER['HTTP_REFERER'] ) || stripos( $_SERVER['HTTP_REFERER'], '//' . $_SERVER['HTTP_HOST'] ) === false ) {
					$this->redirect( $this->base . $uri, true );
				}
				$title = $this->language( 'title-contact-share' );
				$page_title = $title . ' - ' . $this->escape_text( $uri_title );
				$intro = '<p>' . $this->language( 'help-contact-share', [ 'shared-url-and-newline' => '<strong><a href="' . $this->escape_text( $this->base . $uri ) . '">' . $this->escape_text( $uri_title ) . '</a></strong><br /><em>' ] ) . '</em></p><br />';
				break;
			default:
				$title = $this->language( 'title-contact' );
				$intro = '<p>' . $this->language( 'help-contact-title' ) . '</p>';
				break;
		}
		if ( !$page_title ) {
			$page_title = $title;
		}

		$this->write_title( $page_title );
		$this->output( '<h1>' . $title . '</h1>' );
		switch ( $result ) {
			case 'SENT':
				$this->output( '<h3>' . $this->language( 'title-thankyou' ) . '</h3><p>' . $this->language( 'feedback-contact-message-sent' ) . '</p>' );
				break;
			case 'FAILED':
				$this->output( '<h3>' . $this->language( 'title-sorry' ) . '</h3><p>' . $this->language( 'feedback-contact-message-not-sent' ) . '</p>' );
				break;
			default:
				$this->output( $intro );
				$form->render();
				break;
		}
	}
}
new ContactPage();
