<?php

// ***********************
// *                     *
// *  Get Template Data  *
// *                     *
// ***********************

function get_template_data($active=true) {
  include ("db_connection.php");

    $query = "SELECT GROUP_CONCAT(type) AS all_types FROM types";

    $result = $bwb_wiz_dbh->query($query);

    $types = $result->fetch(PDO::FETCH_ASSOC);

      $query = "SELECT t.*, " .
                 "GROUP_CONCAT(DISTINCT type) AS type, " .
                 "GROUP_CONCAT(DISTINCT category) AS category, " .
                 "GROUP_CONCAT(DISTINCT CONCAT('all,aural,braille,embossed,handheld,print,projection,screen,tty,tv')) AS media_label, " .
                 "GROUP_CONCAT(DISTINCT CONCAT_WS(',',tmt.all,tmt.aural,tmt.braille,tmt.embossed,tmt.handheld,tmt.print,tmt.projection,tmt.screen,tmt.tty,tmt.tv)) AS media_value " .
               "FROM templates t, template_types tt, template_categories tc, template_media_types tmt " .
               "WHERE t.ID=tt.template_id " .
                 "AND t.ID=tc.template_id " .
                 "AND t.ID=tmt.template_id ";
    if ($active) {
      $query .=  "AND t.active=1 ";};
    $query .=  "GROUP BY t.ID " .
               "ORDER BY name";

  $result = $bwb_wiz_dbh->query($query);

  $rows = $result->fetchALL(PDO::FETCH_ASSOC);

  // convert GROUP_CONCAT string into array
  foreach ($rows as &$row) {
    if ($row['type']) {
      if (strpos($row['type'], 'All') !== FALSE) {
        $row['type'] = explode(',', $types['all_types']);
      } else {
        $row['type'] = explode(',', $row['type']);
      }
    }
    if ($row['category']) {
      $row['category'] = explode(',', $row['category']);
    }
    if (is_string($row['media_value']) && is_string($row['media_label'])) {
      $row['media'] = array_combine(explode(',', $row['media_label']), explode(',', $row['media_value']));
      unset($row['media_value']);
      unset($row['media_label']);
    }
  }
  unset($row);

/*
print "<pre style=\"text-align:left;\">";
print_r($rows);
print "</pre>";
*/

  return $rows;
}

?>
