<?php

require ("config.php");

//include the js file for the jquery datepicker 
$includeJsArr = array("jquery.datetimepicker");
$smarty->assign('includeJsArr', $includeJsArr);
//include the css file for the tab option
$includeCssArr = array("jquery.datetimepicker");
$smarty->assign('includeCssArr', $includeCssArr);

if (isset($_SESSION["id_users"]) ) {
  $myUser = new User($_SESSION["id_users"]); 
  $smarty->assign('userstat', 'out');
  $smarty->assign('loggedin', 1);

  if ($myUser->get_package() != 2) {
    $smarty->assign('msg_detail', "You do not have access to the Measurement Tools. Please contact one of our Business Development Executives for more information at +971 4 368-8444 or email us at contact@mediastow.com");
    $smarty->display("unauthorized.tpl");
    exit;
  }


  if (isset($_SESSION["userCompanies"])) {
    foreach($_SESSION["userCompanies"] as $c) {
      $tmpC = new Company($c[0]);
      $companyList[] = Array($c[0], str_replace("&", "&amp;", $tmpC->get_name_company()));
    }
    $smarty->assign('companyList', $companyList);
  }
  if (isset($_SESSION["userCountries"])) {
    if ($debug) {
      print "Get countryList from user session<br />";
    }
    foreach($_SESSION["userCountries"] as $c) {
      $tmpC = new Country($c[0]);
      $countryList[] = Array($c[0], str_replace("&", "&amp;", $tmpC->get_name_country()));
      $marketList[] = $c[0];
    }
    $smarty->assign('countryList', $countryList);
  }


}
else {
  $smarty->assign('userstat', 'in');
  $smarty->assign('loggedin', 0);
  $smarty->display('unauthorized.tpl');
  exit;

}

$scriptname = str_replace(".php", $_SERVER["SCRIPT_NAME"], "");

$browse_info = split("/", $_SERVER["PATH_INFO"]);

$smarty->assign('searchString', $_GET["searchWord"]);
$smarty->assign('scriptname', $scriptname);

$smarty->assign('fullname', $_SESSION["fname"].' '.$_SESSION['lname']);


// ***
//
//  This is where the action is!
//
// ***

// okay, instantiate report writer class
if (isset($_GET["action"])) {
  $myArticles = new ReportWriter();
  $myArticles->set_id_users($_SESSION["id_users"]);
}


// if this is a report request
if ($_GET["action"] == "Report") {
    
  if (!$_GET["topics"]) {
    $msg = 'You need to select a topic or more in order to generate reports!';
    $smarty->assign('msg', $msg);
    $smarty->display('reports.tpl');
    exit;
  }

  // get the dates
  if (isset($_GET["date1"]) AND isset($_GET["date2"])) {
    $myArticles->set_date_start($_GET["date1"]);
    $myArticles->set_date_end($_GET["date2"]);
  }
  // deal with the topics
  if (isset($_GET["topics"])) {
    $topics = implode($_GET["topics"], ",");
    $myArticles->set_topics($topics);
  }
  $markets = implode($marketList, ",");
  $myArticles->set_markets($markets);

  // be sure the limit is set to 0
  $myArticles->set_limit(0);

  // get the articles
  $theArticles = $myArticles->getArticles();
  $tm = setup_workbook($mainpath, $hosturl);
  list($workbook, $formattings, $wbfile, $wburl) = $tm;
  list($format_title, $format_total,
	$fmt_address, 
	$fmt_even, $fmt_currency_even, $fmt_number_even, $fmt_last_even,
	$fmt_odd, $fmt_currency_odd, $fmt_number_odd, $fmt_last_odd,
	$fmt_currency_total, $fmt_decimal_total,  $fmt_number_total, 
	$fmt_last) = $formattings;
  $startRow = 9;
  $startCol = 0;

  $worksheet =& $workbook->addWorksheet('Media Coverage Report');

  mediastow_header($worksheet, $mainpath);
  mcr_worksheet_titles($startRow, $startCol, $worksheet, $formattings);


  // set up variabels for penetration calculation
  
  $pLanguages = array();
  $pMarkets = array();
  $pGenres = array();
  $pATypes = array();
  $pMTypes = array();

  for ($i=1; $i <= $theArticles[0]; $i++) {
    $n = $i-1;

    if ($i % 2) { 
        $fmt = $fmt_even; 
        $fmt_currency = $fmt_currency_even; 
      	$fmt_number = $fmt_number_even;
    }
    else {
       $fmt = $fmt_odd;
       $fmt_currency = $fmt_currency_odd;
       $fmt_number = $fmt_number_odd;
    }

    $tone = 'Neutral';
    $tmpArticle = new Article($theArticles[1][$n]['id_article']);
    $tmpArticle->set_id_users($_SESSION["id_users"]);
    $tmpArticle->find_custom_article();
 
    // start compiling data for penetrations
    $pLanguages[$tmpArticle->get_language()][0] += 1;
    $pLanguages[$tmpArticle->get_language()][1] += $tmpArticle->get_ave();

    $clipUrl = $hosturl.'clipping/'.$theArticles[1][$n]['id_article'].'/id_mar/'.$_SESSION["id_mar"];
    $niceDate = strftime("%B %d, %Y", strtotime($theArticles[1][$n]['publication_date']));
    $worksheet->write($i+$startRow, 0, $theArticles[1][$n]['publication_date'], $fmt);
    $worksheet->write($i+$startRow, 1, $theArticles[1][$n]['name_publication_en'], $fmt);
    $worksheet->writeUrl($i+$startRow, 2, $clipUrl, $tmpArticle->get_headline_en(), $fmt);
    $worksheet->write($i+$startRow, 3, $theArticles[1][$n]['name_country_en'], $fmt);

    $pMarkets[$theArticles[1][$n]['name_country_en']][0] += 1;
    $pMarkets[$theArticles[1][$n]['name_country_en']][1] += $tmpArticle->get_ave();

    $articleType = new articleType($theArticles[1][$n]['id_article_type']);
    $worksheet->write($i+$startRow, 4, $articleType->get_name_article_type(), $fmt);
    $pATypes[$articleType->get_name_article_type()][0] += 1;
    $pATypes[$articleType->get_name_article_type()][1] += $tmpArticle->get_ave();

    if ($theArticles[1][$n]['id_article_impression'] == 1) { $tone = 'Favorable'; }
    if ($theArticles[1][$n]['id_article_impression'] == 3) { $tone = 'Unfavorable'; }
    $worksheet->write($i+$startRow, 5, $tone, $fmt);

    if ($tmpArticle->get_ave()) {
      $worksheet->write($i+$startRow, 6, $tmpArticle->get_ave(), $fmt_currency);
    }
    else {
      $worksheet->write($i+$startRow, 6, $theArticles[1][$n]['ave'], $fmt);
    }
    
    if ($tmpArticle->get_pr_value()) {
      $worksheet->write($i+$startRow, 7, $tmpArticle->get_pr_value(), $fmt);
    }
    else {
      $worksheet->writeBlank($i+$startRow, 7, $fmt);
     }


    if ($tmpArticle->get_author()) {
      $worksheet->write($i+$startRow, 8, $tmpArticle->get_author(), $fmt);
    }
    else {
      $worksheet->writeBlank($i+$startRow, 8, $fmt);
     }


    if ($tmpArticle->get_spokesperson()) {
      $worksheet->write($i+$startRow, 9, $tmpArticle->get_spokesperson(), $fmt);
    }
    else {
      $worksheet->writeBlank($i+$startRow, 9,  $fmt);
     }

    $worksheet->write($i+$startRow, 10, $theArticles[1][$n]['language'], $fmt);
    $publicationGenre = new publicationGenre($theArticles[1][$n]['id_publication_genre']);
    $worksheet->write($i+$startRow, 11, $publicationGenre->get_name_publication_genre(), $fmt);
    $pGenres[$publicationGenre->get_name_publication_genre()][0] += 1;
    $pGenres[$publicationGenre->get_name_publication_genre()][1] += $tmpArticle->get_ave();
    $pubType = '';
    if ($theArticles[1][$n]['id_publication_type'] == 1) { $pubType = 'Newspaper'; }
    else if ($theArticles[1][$n]['id_publication_type'] == 2) { $pubType = 'Magazine'; }
    else if ($theArticles[1][$n]['id_publication_type'] == 3) { $pubType = 'Website'; }
    else if ($theArticles[1][$n]['id_publication_type'] == 4) { $pubType = 'TV'; }
    else if ($theArticles[1][$n]['id_publication_type'] == 5) { $pubType = 'Radio'; }
    else { $pubType = 'Unknown'; }
    $worksheet->write($i+$startRow, 12, $pubType, $fmt);
    $pMTypes[$pubType][0] += 1;
    $pMTypes[$pubType][1] += $tmpArticle->get_ave();
    $worksheet->write($i+$startRow, 13, $theArticles[1][$n]['circulation'], $fmt_number);
    $freq = '';
    if ($theArticles[1][$n]['id_frequency'] == 1) { $freq = 'Morning Daily'; }
    else if ($theArticles[1][$n]['id_frequency'] == 2) { $freq = 'Weekly'; }
    else if ($theArticles[1][$n]['id_frequency'] == 3) { $freq = 'Bi-Monthly'; }
    else if ($theArticles[1][$n]['id_frequency'] == 4) { $freq = 'Monthly'; }
    else if ($theArticles[1][$n]['id_frequency'] == 5) { $freq = 'Quarterly'; }
    else if ($theArticles[1][$n]['id_frequency'] == 6) { $freq = 'Annually'; }
    else if ($theArticles[1][$n]['id_frequency'] == 7) { $freq = 'Evening Daily'; }
    else if ($theArticles[1][$n]['id_frequency'] == 8) { $freq = 'Fortnightly'; }
    else { $freq = 'N/A'; }
    $worksheet->write($i+$startRow, 14, $freq, $fmt); 
    $tmPage = (int) $theArticles[1][$n]["real_size"];
    if ($theArticles[1][$n]['size'] AND !$tmPage) {
      if ($tmpArticle->get_custom_size_cc()) {
        $worksheet->write($i+$startRow, 15, $tmpArticle->get_custom_size_cc(), $fmt);
      }
      else {
        $worksheet->write($i+$startRow, 15, $theArticles[1][$n]['size'], $fmt);
      }
    }
    else {
      $worksheet->writeBlank($i+$startRow, 15, $fmt);
     }



    if ($theArticles[1][$n]["real_size"]) {
      if ($tmpArticle->get_custom_size_page()) {
        $worksheet->write($i+$startRow, 16, $tmpArticle->get_custom_size_page(), $fmt);
      }
      else {
        $worksheet->write($i+$startRow, 16, $theArticles[1][$n]['real_size'], $fmt);
      }
    }
    else {
      $worksheet->writeBlank($i+$startRow, 16,  $fmt);
     }



    if ($theArticles[1][$n]['adrate_color'] > 0) {
      $worksheet->write($i+$startRow, 17, $theArticles[1][$n]['adrate_color'], $fmt_currency);
    }
    else {
      $worksheet->write($i+$startRow, 17, $theArticles[1][$n]['adrate_bw'], $fmt_currency);
    }

    if ($tmpArticle->get_custom_note()) {
      $worksheet->write($i+$startRow, 18, $tmpArticle->get_custom_note(), $fmt);
    }
    else {
      $worksheet->writeBlank($i+$startRow, 18, $fmt);
     }


    if ($theArticles[1][$n]['published']) { $worksheet->write($i+$startRow, 19, 'Processed', $fmt); }
    elseif (!$theArticles[1][$n]['id_summary'] AND !$theArticles[1][$n]['published']) { $worksheet->write($i+$startRow, 19, 'Unsummarized', $fmt); }
    else {  $worksheet->write($i+$startRow, 19, 'inProcess', $fmt); }

    $worksheet->writeNumber($i+$startRow, 20, $theArticles[1][$n]['id_article'], $fmt);
    $worksheet->writeString($i+$startRow, 21, $tmpArticle->get_created(), $fmt);

  }

    $s = $startRow + 2;
    $e = $startRow + $i;
    $aveCols = 'G'.$s.':G'.$e;
    $prvalueCols = 'H'.$s.':H'.$e;
    $ccCols = 'P'.$s.':P'.$e;
    $pageCols = 'Q'.$s.':Q'.$e;
    $worksheet->write($i+$startRow, 0, "Total", $format_total);
    for ($n=1;$n<7;$n++) {
      $worksheet->writeBlank($i+$startRow, $n, $format_total);
    }
    $worksheet->writeFormula($i+$startRow, 6, "=SUM(".$aveCols.")", $fmt_currency_total);
    $worksheet->writeFormula($i+$startRow, 7, "=SUM(".$prvalueCols.")", $fmt_currency_total);

    for ($n=8;$n<16;$n++) {
      $worksheet->writeBlank($i+$startRow, $n, $format_total);
    }

    $worksheet->writeFormula($i+$startRow, 15, "=SUM(".$ccCols.")", $fmt_number_total);
    $worksheet->writeFormula($i+$startRow, 16, "=SUM(".$pageCols.")", $fmt_decimal_total);

    for ($n=17;$n<22;$n++) {
      $worksheet->writeBlank($i+$startRow, $n, $format_total);
    }


// Second worksheet for Penetrations
   $worksheet2 =& $workbook->addWorkSheet('Penetrations');
   $worksheet2->setHeader("Penetrations");
   $worksheet2->setFooter("(c) Copyright 2012, Mediastow");
   $worksheet2->setPortrait();
   $worksheet2->setZoom(90);
   $worksheet2->hideGridLines();
   $worksheet2->fitToPages(1,1);

   $worksheet2->writeString(1,3, "Office 1303, Thuraya Tower II");
   $worksheet2->writeString(2,3, "Dubai Media City");
   $worksheet2->writeString(3,3, "PO Box 502561");
   $worksheet2->writeString(4,3, "Dubai, United Arab Emirates");
   $worksheet2->writeString(5,3, "Tel: +971 4 368-8444");
   $worksheet2->writeString(6,3, "Fax: +971 4 368-8443");
   $worksheet2->writeUrl(7,3, "mailto:contact@mediastow.com", "contact@mediastow.com");
   $worksheet2->insertBitmap(0, 0, $mainpath.'htdocs/imagefiles/mediastow.bmp', 0, 0, 1, 1);

   $worksheet2->setColumn(3,3,25);
   $worksheet2->setColumn(4,6, 15);
   $startRow += 3;
   $worksheet2->writeString($startRow, 3, "Language", $format_title);
   $worksheet2->writeString($startRow, 4, "# of Clippings", $format_title);
   $worksheet2->writeString($startRow, 5, "AVE", $format_title);

   $r = $startRow + 1;
   foreach($pLanguages as $key => $value) {
     $worksheet2->writeString($r, 3, $key, $fmt_even);
     $worksheet2->writeNumber($r, 4, $value[0], $fmt_number_even);
     $worksheet2->writeNumber($r, 5, $value[1], $fmt_currency_even);
     $r++;
   }

   $r += 2;
  
   $worksheet2->writeString($r, 3, "Markets", $format_title);
   $worksheet2->writeString($r, 4, "# of Clippings", $format_title);
   $worksheet2->writeString($r, 5, "AVE", $format_title);
   $r += 1;
   foreach($pMarkets as $key => $value) {
     $worksheet2->writeString($r, 3, $key, $fmt_even);
     $worksheet2->writeNumber($r, 4, $value[0], $fmt_number_even);
     $worksheet2->writeNumber($r, 5, $value[1], $fmt_currency_even);
     $r++;
   }

  $r += 2;

   $worksheet2->writeString($r, 3, "Genres", $format_title);
   $worksheet2->writeString($r, 4, "# of Clippings", $format_title);
   $worksheet2->writeString($r, 5, "AVE", $format_title, $fmt_currency_even);
   $r += 1;
   foreach($pGenres as $key => $value) {
     $worksheet2->writeString($r, 3, $key, $fmt_even);
     $worksheet2->writeNumber($r, 4, $value[0], $fmt_number_even);
     $worksheet2->writeNumber($r, 5, $value[1], $fmt_currency_even);
     $r++;
   }

   $r += 2;
   $worksheet2->writeString($r, 3, "Clipping Type", $format_title);
   $worksheet2->writeString($r, 4, "# of Clippings", $format_title);
   $worksheet2->writeString($r, 5, "AVE", $format_title);
   $r += 1;
   foreach($pATypes as $key => $value) {
     $worksheet2->writeString($r, 3, $key, $fmt_even);
     $worksheet2->writeNumber($r, 4, $value[0], $fmt_number_even);
     $worksheet2->writeNumber($r, 5, $value[1], $fmt_currency_even);
     $r++;
   }

   $r += 2;

   $worksheet2->writeString($r, 3, "Media Type", $format_title);
   $worksheet2->writeString($r, 4, "# of Clippings", $format_title);
   $worksheet2->writeString($r, 5, "AVE", $format_title);
   $r += 1;
   foreach($pMTypes as $key => $value) {
     $worksheet2->writeString($r, 3, $key, $fmt_even);
     $worksheet2->writeNumber($r, 4, $value[0], $fmt_number_even);
     $worksheet2->writeNumber($r, 5, $value[1], $fmt_currency_even);
     $r++;
   }

  $workbook->close();
  $smarty->assign('workbookurl', $wburl);
  $smarty->display('reports-download.tpl' );
  exit;
}
else if ($_GET["action"] == "Master Report") {
  if (!$_GET["topics"]) {
    $msg = 'You need to select a topic or more in order to generate reports!';
    $smarty->assign('msg', $msg);
    $smarty->display('reports.tpl');
    exit;
  }

  // get the dates
  if (isset($_GET["date1"]) AND isset($_GET["date2"])) {
    $myArticles->set_date_start($_GET["date1"]);
    $myArticles->set_date_end($_GET["date2"]);
  }
  // deal with the topics
  if (isset($_GET["topics"])) {
    $topics = implode($_GET["topics"], ",");
    $myArticles->set_topics($topics);
  }
  $markets = implode($marketList, ",");
  $myArticles->set_markets($markets);

  // be sure the limit is set to 0
  $myArticles->set_limit(0);

  // get the articles

    $tm = setup_workbook($mainpath, $hosturl);
    list($workbook, $formattings, $wbfile, $wburl) = $tm;
    list($format_title, $format_total,
        $fmt_address,
        $fmt_even, $fmt_currency_even, $fmt_number_even, $fmt_last_even,
        $fmt_odd, $fmt_currency_odd, $fmt_number_odd, $fmt_last_odd,
        $fmt_currency_total, $fmt_decimal_total,  $fmt_number_total,
        $fmt_last) = $formattings;
    $startRow = 9;
    $startCol = 0;
  foreach($_GET["topics"] as $topic) {
    $myArticles->set_topics($topic);
    $topicInfo = new Company($topic);
    $theArticles = $myArticles->getArticles();

    if ($theArticles[0]) {
      if (strlen($topicInfo->get_name_company()) > 31) {
         $worksheet =& $workbook->addWorksheet(substr($topicInfo->get_name_company(), 0, 30));
       }
       else {
         $worksheet =& $workbook->addWorksheet($topicInfo->get_name_company());
       }

    mediastow_header($worksheet);
    mastersheet_titles($startRow, $startCol, $worksheet, $formattings);


    // Penetration Stuff
    $pLanguages[$topic] = array();
    $pMarkets[$topic] = array();
    $pGenres[$topic] = array();
    $pATypes[$topic] = array();
    $pMTypes[$topic] = array();

    for ($i=1; $i <= $theArticles[0]; $i++) {
      $n = $i-1;

      if ($i % 2) {
        $fmt = $fmt_even;
        $fmt_currency = $fmt_currency_even;
        $fmt_number = $fmt_number_even;
      }
      else {
        $fmt = $fmt_odd;
        $fmt_currency = $fmt_currency_odd;
        $fmt_number = $fmt_number_odd;
      }

      $tone = 'Neutral';
      $tmpArticle = new Article($theArticles[1][$n]['id_article']);
      $tmpArticle->set_id_users($_SESSION["id_users"]);
      $tmpArticle->find_custom_article();
      $tagInfo = $tmpArticle->find_tag_details($topic);
      $publicationGenre = new publicationGenre($theArticles[1][$n]['id_publication_genre']);
      $freq = '';
      if ($theArticles[1][$n]['id_frequency'] == 1) { $freq = 'Morning Daily'; }
      else if ($theArticles[1][$n]['id_frequency'] == 2) { $freq = 'Weekly'; }
      else if ($theArticles[1][$n]['id_frequency'] == 3) { $freq = 'Bi-Monthly'; }
      else if ($theArticles[1][$n]['id_frequency'] == 4) { $freq = 'Monthly'; }
      else if ($theArticles[1][$n]['id_frequency'] == 5) { $freq = 'Quarterly'; }
      else if ($theArticles[1][$n]['id_frequency'] == 6) { $freq = 'Annually'; }
      else if ($theArticles[1][$n]['id_frequency'] == 7) { $freq = 'Evening Daily'; }
      else if ($theArticles[1][$n]['id_frequency'] == 8) { $freq = 'Fortnightly'; }
      else { $freq = 'N/A'; }

      $pubType = '';
      if ($theArticles[1][$n]['id_publication_type'] == 1) { $pubType = 'Newspaper'; }
      else if ($theArticles[1][$n]['id_publication_type'] == 2) { $pubType = 'Magazine'; }
      else if ($theArticles[1][$n]['id_publication_type'] == 3) { $pubType = 'Website'; }
      else if ($theArticles[1][$n]['id_publication_type'] == 4) { $pubType = 'TV'; }
      else if ($theArticles[1][$n]['id_publication_type'] == 5) { $pubType = 'Radio'; }
      else { $pubType = 'Unknown'; }


      // -----
      // Sorting out customized data
      // -----

      if ($tagInfo['mention_score']) {
        if ($tagInfo['mention_score'] == 1) { $myMention = 'Marginal'; }
        else if ($tagInfo['mention_score'] == 2) { $myMention = 'Prominent'; }
        else { $myMention = 'Headline'; }
        $imention = $tagInfo['mention_score'];
      }
      else {
        $imention = 1;
        $myMention = 'Marginal';
      }
      if ($tagInfo['visual_score']) {
        if ($tagInfo['visual_score'] == -99) { $myVisual = 'None';  $ivisual = 0; }
        else if ($tagInfo['visual_score'] == 1) { $myVisual = 'Black/White'; }
        else { $myVisual = 'Color'; }
        $ivisual = $tagInfo['visual_score'];
      }
      else {
        $ivisual = 0;
        $myVisual = 'None';
      }

      // Custom AVE
      if ($tagInfo['ave']) {
        $myAVE = $tagInfo['ave'];
      }
      else if ($tmpArticle->get_ave()) {
        $myAVE = $tmpArticle->get_ave();
      }
      else {
        $myAVE = $theArticles[1][$n]['ave'];
      }

      // tone
      if ($tagInfo['tone_score']) { $itone = $tagInfo['tone_score']; } else { $itone = $theArticles[1][$n]['id_article_impression']; }

      if ($itone == 2) { $myTone = 'Favorable'; }
      else if ($itone == -2) { $myTone = 'Unfavorable'; }
      else { $myTone = 'Neutral'; }


      // Custom Size
      $tmPage = (int) $theArticles[1][$n]["real_size"];
      if ($theArticles[1][$n]['size'] AND !$tmPage) {
        if ($tagInfo["size_cc"]) {
          $mySizeCc = $tagInfo['size_cc'];
        }
        else if ($tmpArticle->get_custom_size_cc()) {
          $mySizeCc = $tmpArticle->get_custom_size_cc();
        }
        else {
          $mySizeCc = $theArticles[1][$n]['size'];
        }
      }
      if ($theArticles[1][$n]["real_size"]) {
        if ($tagInfo["size_page"]) {
          $mySizePage = $tagInfo['size_page'];
        }
        else {
          if ($tmpArticle->get_custom_size_page()) {
            $mySizePage = $tmpArticle->get_custom_size_page();
          }
          else {
            $mySizePage = $theArticles[1][$n]['real_size'];
          }
        }
      }

      $pIndex = (($imention + $ivisual) / 5 ) * $itone;

      $pLanguages[$topic][$tmpArticle->get_language()][0] += 1;
	  //      $pLanguages[$topic][$tmpArticle->get_language()][1] += $tmpArticle->get_ave();
	  $pLanguages[$topic][$tmpArticle->get_language()][1] += $myAVE;

      $clipUrl = $hosturl.'clipping/'.$theArticles[1][$n]['id_article'].'/id_mar/'.$_SESSION["id_mar"];
      $niceDate = strftime("%B %d, %Y", strtotime($theArticles[1][$n]['publication_date']));
      $worksheet->write($i+$startRow, 0, $theArticles[1][$n]['publication_date'], $fmt);
      $worksheet->write($i+$startRow, 1, $theArticles[1][$n]['name_publication_en'], $fmt);
      $worksheet->writeUrl($i+$startRow, 2, $clipUrl, $tmpArticle->get_headline_en(), $fmt);
      $worksheet->write($i+$startRow, 3, $theArticles[1][$n]['name_country_en'], $fmt);

      $pMarkets[$topic][$theArticles[1][$n]['name_country_en']][0] += 1;
      $pMarkets[$topic][$theArticles[1][$n]['name_country_en']][1] += $myAVE;

      $articleType = new articleType($theArticles[1][$n]['id_article_type']);
      $worksheet->write($i+$startRow, 4, $articleType->get_name_article_type(), $fmt);
      $pATypes[$topic][$articleType->get_name_article_type()][0] += 1;
      $pATypes[$topic][$articleType->get_name_article_type()][1] += $myAVE;

      $worksheet->write($i+$startRow, 5, $myTone, $fmt);
      $worksheet->write($i+$startRow, 6, $myMention, $fmt);
      $worksheet->write($i+$startRow, 7, $myVisual, $fmt);
      $worksheet->write($i+$startRow, 8, $myAVE, $fmt_currency);
      if ($tagInfo['note']) {
//        $worksheet->write($i+$startRow, 9, $tagInfo['note'], $fmt);
$worksheet->write($i+$startRow, 9, "lala", $fmt);
      }
      else {
        $worksheet->writeBlank($i+$startRow, 9, $fmt);
      }

      $worksheet->write($i+$startRow, 10, $theArticles[1][$n]['language'], $fmt);

      if ($tmpArticle->get_author()) {
        $worksheet->write($i+$startRow, 11, $tmpArticle->get_author(), $fmt);
      }
      else {
        $worksheet->writeBlank($i+$startRow, 11, $fmt);
      }

      if ($tmpArticle->get_spokesperson()) {
        $worksheet->write($i+$startRow, 12, $tmpArticle->get_spokesperson(), $fmt);
      }
      else {
        $worksheet->writeBlank($i+$startRow, 12,  $fmt);
       }

      $worksheet->write($i+$startRow, 13, $publicationGenre->get_name_publication_genre(), $fmt);
      $pGenres[$topic][$publicationGenre->get_name_publication_genre()][0] += 1;
      $pGenres[$topic][$publicationGenre->get_name_publication_genre()][1] += $myAVE;

      $worksheet->write($i+$startRow, 14, $pubType, $fmt);
      $pMTypes[$topic][$pubType][0] += 1;
      $pMTypes[$topic][$pubType][1] += $myAVE;

      $worksheet->write($i+$startRow, 15, $theArticles[1][$n]['circulation'], $fmt_number);
      $worksheet->write($i+$startRow, 16, $freq, $fmt);

      if ($mySizeCc) {
        $worksheet->write($i+$startRow, 17, $mySizeCc, $fmt);
      }
      else {
        $worksheet->writeBlank($i+$startRow, 17, $fmt);
      }
      if ($mySizePage) {
        $worksheet->write($i+$startRow, 18, $mySizePage, $fmt);
      }
      else {
        $worksheet->writeBlank($i+$startRow, 18,  $fmt);
      }


      if ($theArticles[1][$n]['adrate_color'] > 0) {
        $worksheet->write($i+$startRow, 19, $theArticles[1][$n]['adrate_color'], $fmt_currency);
      }
      else {
        $worksheet->write($i+$startRow, 19, $theArticles[1][$n]['adrate_bw'], $fmt_currency);
      }

      if ($tmpArticle->get_custom_note()) { // no changes
        $worksheet->write($i+$startRow, 20, $tmpArticle->get_custom_note(), $fmt);
      }
      else {
        $worksheet->writeBlank($i+$startRow, 20, $fmt);
      }

      if ($theArticles[1][$n]['published']) { $worksheet->write($i+$startRow, 21, 'Processed', $fmt); }
      elseif (!$theArticles[1][$n]['id_summary'] AND !$theArticles[1][$n]['published']) {	    $worksheet->write($i+$startRow, 21, 'Unsummarized', $fmt); }
      else {  $worksheet->write($i+$startRow, 21, 'inProcess', $fmt); }

      $worksheet->writeNumber($i+$startRow, 22, $imention, $fmt);
      $worksheet->writeNumber($i+$startRow, 23, $ivisual, $fmt);
      $worksheet->writeNumber($i+$startRow, 24, $itone, $fmt);
      $worksheet->writeNumber($i+$startRow, 25, $pIndex, $fmt);

      $worksheet->writeNumber($i+$startRow, 26, $theArticles[1][$n]['id_article'], $fmt);
      $worksheet->writeString($i+$startRow, 27, $tmpArticle->get_created(), $fmt);
    }

    $s = $startRow + 2;
    $e = $startRow + $i;
    $aveCols = 'I'.$s.':I'.$e;
    $ccCols = 'R'.$s.':R'.$e;
    $pageCols = 'S'.$s.':S'.$e;
    $pIndexCols = 'Z'.$s.':Z'.$e;
    $worksheet->write($i+$startRow, 0, "Total", $format_total);
    for ($n=1;$n<8;$n++) {
      $worksheet->writeBlank($i+$startRow, $n, $format_total);
    }
    $worksheet->writeFormula($i+$startRow, 8, "=SUM(".$aveCols.")", $fmt_currency_total);

    for ($n=9;$n<17;$n++) {
      $worksheet->writeBlank($i+$startRow, $n, $format_total);
    }

    $worksheet->writeFormula($i+$startRow, 17, "=SUM(".$ccCols.")", $fmt_number_total);
    $worksheet->writeFormula($i+$startRow, 18, "=SUM(".$pageCols.")", $fmt_decimal_total);

    for ($n=19;$n<25;$n++) {
      $worksheet->writeBlank($i+$startRow, $n, $format_total);
    }

    $worksheet->writeFormula($i+$startRow, 25, "=SUM((".$pIndexCols.")/".$theArticles[0].")", $fmt_decimal_total);
    for ($n=26;$n<28;$n++) {
      $worksheet->writeBlank($i+$startRow, $n, $format_total);
    }


// Second worksheet for Penetrations

   $startRow += $i + 5;
   $worksheet->writeString($startRow, 3, "Language", $format_title);
   $worksheet->writeString($startRow, 4, "# of Clippings", $format_title);
   $worksheet->writeString($startRow, 5, "AVE", $format_title);

   $r = $startRow + 1;
   foreach($pLanguages[$topic] as $key => $value) {
     $worksheet->writeString($r, 3, $key, $fmt_even);
     $worksheet->writeNumber($r, 4, $value[0], $fmt_number_even);
     $worksheet->writeNumber($r, 5, $value[1], $fmt_currency_even);
     $r++;
   }

   $r += 2;

   $worksheet->writeString($r, 3, "Markets", $format_title);
   $worksheet->writeString($r, 4, "# of Clippings", $format_title);
   $worksheet->writeString($r, 5, "AVE", $format_title);
   $r += 1;
   foreach($pMarkets[$topic] as $key => $value) {
     $worksheet->writeString($r, 3, $key, $fmt_even);
     $worksheet->writeNumber($r, 4, $value[0], $fmt_number_even);
     $worksheet->writeNumber($r, 5, $value[1], $fmt_currency_even);
     $r++;
   }

  $r += 2;

   $worksheet->writeString($r, 3, "Genres", $format_title);
   $worksheet->writeString($r, 4, "# of Clippings", $format_title);
   $worksheet->writeString($r, 5, "AVE", $format_title, $fmt_currency_even);
   $r += 1;
   foreach($pGenres[$topic] as $key => $value) {
     $worksheet->writeString($r, 3, $key, $fmt_even);
     $worksheet->writeNumber($r, 4, $value[0], $fmt_number_even);
     $worksheet->writeNumber($r, 5, $value[1], $fmt_currency_even);
     $r++;
   }

   $r += 2;
   $worksheet->writeString($r, 3, "Clipping Type", $format_title);
   $worksheet->writeString($r, 4, "# of Clippings", $format_title);
   $worksheet->writeString($r, 5, "AVE", $format_title);
   $r += 1;
   foreach($pATypes[$topic] as $key => $value) {
     $worksheet->writeString($r, 3, $key, $fmt_even);
     $worksheet->writeNumber($r, 4, $value[0], $fmt_number_even);
     $worksheet->writeNumber($r, 5, $value[1], $fmt_currency_even);
     $r++;
   }

   $r += 2;

   $worksheet->writeString($r, 3, "Media Type", $format_title);
   $worksheet->writeString($r, 4, "# of Clippings", $format_title);
   $worksheet->writeString($r, 5, "AVE", $format_title);
   $r += 1;
   foreach($pMTypes[$topic] as $key => $value) {
     $worksheet->writeString($r, 3, $key, $fmt_even);
     $worksheet->writeNumber($r, 4, $value[0], $fmt_number_even);
     $worksheet->writeNumber($r, 5, $value[1], $fmt_currency_even);
     $r++;
   }
   $startRow=9;
	}}
// END OF PENETRATION


   $workbook->close();
   $smarty->assign('workbookurl', $wburl);
   $smarty->display('reports-download.tpl' );
   exit;
}
else {
  $smarty->display('reports.tpl');
}


?>
