<?php
return function($site, $pages, $page) {
  $alert = null;
  if(get('submit')) {
    $data = array(
      'name'  => get('name'),
      'email' => get('email'),
      'text'  => get('text'),
	  'phone' => get('phone')
    );
    $rules = array(
      'email' => array('required', 'email'),
      'text'  => array('required', 'min' => 3, 'max' => 3000),
    );
    $messages = array(
      'email' => l::get('uniform-fields-not-valid'),
      'text'  => l::get('uniform-fields-not-valid')
    );
    // some of the data is invalid
    if($invalid = invalid($data, $rules, $messages)) {
      $alert = $invalid;
    // the data is fine, let's send the email
    } else {
      // create the body from a simple snippet
      $body  = snippet('contactmail', $data, true);
      // build the email
      $email = email(array(
        'to'      => 'siem.linx@gmail.com',
        'from'    => 'info@infiltro.be',
        'subject' => 'Een nieuwe vraag werd gesteld',
        'replyTo' => $data['email'],
        'body'    => $body
      ));
        
      // try to send it and redirect to the
      // thank you page if it worked
      if($email->send()) {
        go('contact/bedankt');
      // add the error to the alert list if it failed
      } else {
        $alert = array($email->error());
      }
    }
  }
  return compact('alert');
};