<?php
  header("Content-Type: application/xhtml+xml");
  echo "<?xml version='1.0' encoding='utf-8'?>\n";
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title>CSCI-90.3 Magic Matrix</title>
    <link rel="stylesheet" type="text/css" href="../css/assignment_2.css" />
    <style type="text/css">body {max-width:927px;min-width:810px;overflow:hidden}</style>
<?php
  //  Process the message
  $message = 'This is not a message.';
  if ( isset($_GET['message']) && strlen(trim($_GET['message'])) !== 0) $message = $_GET['message'];
  $num_rows = sqrt(strlen($message));
  $message .= ' ';
  //  Process the color
  $color = '';
  if ( isset($_GET['color']) )
  {
    $color = strtolower(trim($_GET['color']));
  }
  if ( '' === trim($color) ) $color ='white';
  $red = 255; $green = 255; $blue = 255;
  //  look up hex for color name
  $fd = fopen('../resources/color_names.txt', 'r') or die("oh, shucks");
  while ($line = fgets($fd))
  {
    $line = trim($line);
    if ('' === $line) continue;
    $parts = explode(' ', $line);
    if (strtolower($parts[0]) === $color)
    {
      $color = $parts[1];
      break;
    }
  }
  if ('#' === $color[0])
  {
    if (4 === strlen($color))
    {
      $red    = '0x'.$color[1].$color[1];
      $green  = '0x'.$color[2].$color[2];
      $blue   = '0x'.$color[3].$color[3];
    }
    else if (7 === strlen($color))
    {
      $red    = '0x'.$color[1].$color[2];
      $green  = '0x'.$color[3].$color[4];
      $blue   = '0x'.$color[5].$color[6];
    }
  }
  //  Background color channels:
  $bred   = 0 + $red;
  $bgreen = 0 + $green;
  $bblue  = 0 + $blue;
  //  Foreground color:
  $color = (($bred + $bgreen + $bblue) > 384) ? "#222" : "#ddd";
  echo <<< EOT
  <style type='text/css'>
    a, body {
      background-color: rgb($bred, $bgreen, $bblue);
      color:            $color;
    }
    table, td { border: 1px solid $color; }
    table { 
      -moz-box-shadow: rgb($bred, $bgreen, $bblue) 0.25em 0.25em 0.25em;
      box-shadow: 0.25em 0.25em 0.25em rgb($bred, $bgreen, $bblue);
    }
    </style>
EOT;
?>
  </head>
  <body>
    <h1><?php echo $message; ?></h1>
    <table>
      <?php
        $n = 0;
        for ($row = 0; $row < $num_rows; $row++)
        {
          echo "  <tr>\n";
          for ($col = 0; $col < $num_rows; $col++)
          {
            echo "    <td>{$message[$n]}</td>\n";
            if ($n < (strlen($message) - 1) ) $n++;
          }
          echo "  </tr>\n";
        }
      ?>
    </table>
    <footer>
      <a href="http://validator.w3.org/check?uri=referer">XHTML5</a>
      <a href="http://jigsaw.w3.org/css-validator/check/referer?profile=css3&amp;vextwarning=true">CSS3</a>
    </footer>
  </body>
</html>