<?php
  session_start();
  // Returns data to display list of entries to authenticated user
  $uid = $_SESSION['uid'];
  if(!$uid) {
 //   die("User not authenticated!");
  }
  $aid = $_GET['aid'];
  $isAdmin = $_SESSION['admin']==1;
  $mysqli = new mysqli("localhost", "caribanaaccred", "welcome99", "caribanaaccred");
  if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
  }
  // Retrieve list of entries

  $query = "SELECT * from submissions";
  if($aid) {
	$sel[] = "ID=$aid";
  }
  if (!$isAdmin ) {
	$sel[] = "UID='$uid'";
  }
  if(count($sel)>0) {
    $query .= ' WHERE ';
    foreach($sel as $one) {
	$query .= $one .' AND ';
    }
    $query = substr($query, 0, -5);
  } 
  $query .= ' ORDER BY ID';
  if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        // printf ("%s (%s)\n", $row["Name"], $row["formdata"]);
        $ser = $row['formdata'];
        $seru = unserialize($ser);
	$one = array('mid' => $row["ID"],
          'stat' => $row['status'],
          'maj' => $row['modified'],
	  'crea' => $row['created']
        );
        foreach($seru as $key=>$val) {
         $one[$key] = $val;
        }
 	$one['name'] = $row["name"];
         $obj['data'][] = $one;
    }

    /* free result set */
    $result->free();
  } 

  /* close connection */
  $mysqli->close();
  if(!$obj)  {
echo '{
    "sEcho": 1,
    "iTotalRecords": "0",
    "iTotalDisplayRecords": "0",
    "aaData": []
}';
die();
}
  echo json_encode($obj);
?>
