<?php
// ------------------------------------------------------- //

  // Initialize settings and variables
  $datetime = date("Y-m-d-H-i-s");

  // As each error occurs, append it to this array
  $errors = array();

  $shirts_array = array();
  $shirt_count_limit = 100;

  $valid_fits = array("straight-cut", "fitted");
  $valid_colors = array("maroon", "gray", "blue", "green");
  $valid_sizes = array("YXS", "YS", "YM", "YL", "YXL", "S", "M", "L", "XL", "2XL", "3XL", "4XL");
  $valid_fitted_sizes = array("S", "M", "L", "XL", "2XL", "3XL");
  $valid_statuses = array("undergraduate", "grad student", "faculty", "staff", "other");
  $valid_pays = array("normal_pay", "electronic_pay", "special_pay");

  // http://stackoverflow.com/a/12026863/
  $email_pattern = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';

// ------------------------------------------------------- //

  // Test whether name is set and non-empty

  if(isset($_POST["name"]))
  {
    $name = htmlspecialchars(trim($_POST["name"]));
    
    if($name === '')
    {
      $errors[] = "You didn't enter a name.";
    }
  }
  else
  {
    $errors[] = "You didn't enter a name.";
  }

// ------------------------------------------------------- //

  // Test whether email is set and matches the horrifying regex I stole from stackoverflow

  if(isset($_POST["email"]))
  {
    $email = htmlspecialchars(trim($_POST["email"]));

    if(preg_match($email_pattern, $email) !== 1)
    {
      $errors[] = "You didn't enter a valid email.";
    }
  }
  else
  {
    $errors[] = "You didn't enter an email.";
  }

// ------------------------------------------------------- //

  // Test whether status is set and valid

  if(isset($_POST["status"]))
  {
    $status = htmlspecialchars(trim($_POST["status"]));
    
    if(!in_array($status, $valid_statuses))
    {
      $errors[] = "You didn't enter a valid status.";
    }
  }
  else
  {
    $errors[] = "You didn't enter a status.";
  }

// ------------------------------------------------------- //

  // Test whether payment is set and valid

  if(isset($_POST["payment"]))
  {
    $pays = htmlspecialchars(trim($_POST["payment"]));
    
    if(!in_array($pays, $valid_pays))
    {
      $errors[] = "You didn't enter a valid payment plan.";
    }
  }
  else
  {
    $errors[] = "You didn't enter a payment plan.";
  }

// ------------------------------------------------------- //

  // Test potential t-shirts from 1 to $tshirt_limit

  for ($i = 1; $i <= $shirt_count_limit; $i++)
  {
    // If all three properties (fit, size, and color) are set: proceed to next step.
    // If none of them are, assume it's because there are no more t-shirts: break out of loop.
    // Otherwise, the user filled out a row incompletely: make error, break out of loop.

    if(isset($_POST["fit" . $i]) && isset($_POST["size" . $i]) && isset($_POST["color" . $i]))
    {
      $fit = htmlspecialchars(trim($_POST["fit" . $i]));
      $size = htmlspecialchars(trim($_POST["size" . $i]));
      $color = htmlspecialchars(trim($_POST["color" . $i]));

      // If all three properties are among the allowed options: proceed to next step.
      // Otherwise, the user was sneaky and tried to edit the form: make error, break out of loop.

      if(in_array($fit, $valid_fits) && in_array($size, $valid_sizes) && in_array($color, $valid_colors))
      {
        // If the shirt is fitted but the size isn't one offered for them: make error, break out of loop.
        // Otherwise, everything's good! Append information to array of tshirts.

        if($fit === "fitted" && !in_array($size, $valid_fitted_sizes))
        {
          $errors[] = "Fitted shirts are only available in sizes S through 3XL.";
          break;
        }
        else 
        {
          $shirts_array[] = array('fit' => $fit, 'size' => $size, 'color' => $color);
        }

      }
      else
      {
        $errors[] = "You entered an invalid property on one or more of your shirts.";
        break;
      }

    }
    elseif(!isset($_POST["fit" . $i]) && !isset($_POST["size" . $i]) && !isset($_POST["color" . $i]))
    {
      break;
    }
    else
    {
      $errors[] = "You left a property unspecified on one or more of your shirts.";
      break;
    }
  }


// ------------------------------------------------------- //

  // If no errors occurred, write data to batch XML database

  if(empty($errors))
  {
    $batch_filename = "/ad/tshirts/orders/current-batch/batch.xml";
    $batch_file_pointer = fopen($batch_filename, "r+");
    flock($batch_file_pointer, LOCK_EX);

    if(!$batch_file_pointer)
    {
      $errors[] = "Your order wasn't saved successfully. It's a problem on our end.";
    }

    $batch_xml = simplexml_load_file($batch_filename);

    $customer_xml = $batch_xml->addChild('customer');
    $customer_id = trim('id' . html_entity_decode(file_get_contents('/proc/sys/kernel/random/uuid')));
    $customer_xml->addAttribute('guid', $customer_id);
    $customer_xml->addChild('name', $name);
    $customer_xml->addChild('email', $email);
    $customer_xml->addChild('status', $status);
    
    $order_xml = $batch_xml->addChild('order');
    $order_id = trim('id' . html_entity_decode(file_get_contents('/proc/sys/kernel/random/uuid')));
    $order_xml->addAttribute('guid', $order_id);
    $order_xml->addChild('customer_id', $customer_id);
    $order_xml->addChild('time', date(DATE_ATOM));
    
    $shirts_xml = $order_xml->addChild('shirts');
    
    foreach($shirts_array as $shirt)
    {
      $shirt_xml = $shirts_xml->addChild('shirt');
      $shirt_xml->addChild('size', $shirt['size']);
      $shirt_xml->addChild('color', $shirt['color']);
      $shirt_xml->addChild('fit', $shirt['fit']);
    }

    // Preserves formatting
    // http://stackoverflow.com/a/798986
    $dom = new DOMDocument('1.0');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($batch_xml->asXML());
    $dom->save($batch_filename);
    
    // Send email
    $to      = 'tshirts@math.uchicago.edu';
    $subject = 'new order';
    $message = "Customer:\n" . $name . ' (' . $status. ")\n" . $email . "\n\nShirts:";
    foreach($shirts_array as $shirt)
    {
      $message .= "\n[ " . $shirt['size'] .' / ' . $shirt['color'] .' / ' . $shirt['fit'] . ' ]';
    }
    $headers = 'From: tshirts@math.uchicago.edu' . "\r\n" .
    'Reply-To: tshirts@math.uchicago.edu' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    mail($to, $subject, $message, $headers);
    
    flock($batch_file_pointer, LOCK_UN);
    fclose($batch_file_pointer);
  }

?>

  <div id="form" class="<?php echo (empty($errors)) ? 'success' : 'failure'; ?>">

    <section>

      <h2><?php echo (empty($errors)) ? '' : 'Not '; ?>Submitted Successfully!</h2>

      <?php
        if(!empty($errors))
        {
          echo "<ul>";
          foreach ($errors as $value)
          {
            echo "<li>";
            echo $value;
            echo "</li>";
          }
          echo "</table>";
        }
        else
        {
          
        }
      ?>

    </section>

  </div>

  <?php
        echo "<div class=\"final\">";
        if(!empty($errors))
        {
          echo "<a href=\"https://math.uchicago.edu/~tshirts/order-form/\">Reload this form</a>";
        }
        else
        {
          echo "<a href=\"https://math.uchicago.edu/~tshirts/\">Go back to main page</a>";
        }
        echo "</div>";
  ?>