<?php

require_once($_SERVER['DOCUMENT_ROOT'] . '/sys/db.php');

function fileDownload ($fileName, $fileContent) {

  $pathName = "download/$fileName.txt";
  $handle = fopen($pathName, "w");
  fwrite($handle, $fileContent);
  fclose($handle);
  
  header("Content-disposition: attachment;filename=$pathName");
  readfile($pathName);
}


foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "selid")
    $selid = $paramValue;
  else if ($paramName == "values")
    $values = $paramValue;
    
}

$dal = new DAL();
$dal = new DAL();
$sql = "SELECT queryselect, queryfrom, querywhere, querycriteria FROM reportquery " .
       "WHERE id = $selid LIMIT 1 ";
       
$report   = $dal->query($sql);
$query    = "SELECT " .  $report->queryselect . " FROM " . $report->queryfrom .  " WHERE " . $report->querywhere ;
$critList = explode (",", $report->querycriteria);
$valuList = explode (",", $values);

$sql =  str_replace ($critList, $valuList, $query);
$result = $dal->query($sql);

foreach ($result as $row) {
  $firstOf = true;
  foreach ($row as $value) {
    if ($firstOf) {
      $expFile .= $value;
      $firstOf = false;
    }
    else
      $expFile .= ",$value";
  }
  $expFile .= "\n";    
}

echo json_encode($expFile);

?>

