<?php

namespace Origo\Controller;

use Origo\Entity\User;
use Origo\Controller\ControllerBase;
use Origo\Controller\ControllerInterface;
use Origo\Services\Template;
use Origo\Services\Request;

class UserDashboardController extends ControllerBase implements ControllerInterface {

  public function getResponse(): string {
    $user = new User();
    $user->loadUserFromSession($this->request->getCookie('ORIGOSESS'));
    $user_id = $user->get('id');

    $query = $this->database->query("
      SELECT pv.page, pv.title, pv.referrer, pv.ip, pv.language, pv.screen_res, pv.timestamp
      FROM pageviews pv
      JOIN user_accounts ua ON pv.account_id = ua.account_id
      WHERE ua.user_id = :user_id
      ORDER BY pv.timestamp DESC
    ");
    $query->bindParam(':user_id', $user_id);
    $query->execute();
    $results = $query->fetchAll();

    $rows = '';
    if ($results) {
      foreach ($results as $row) {
        $page = htmlspecialchars($row['page']);
        $title = htmlspecialchars($row['title']);
        $referrer = htmlspecialchars($row['referrer']);
        $ip = htmlspecialchars($row['ip']);
        $language = htmlspecialchars($row['language']);
        $screen_res = htmlspecialchars($row['screen_res']);
        $timestamp = htmlspecialchars($row['timestamp']);

        $rows .= "
          <tr>
            <td>{$title}</td>
            <td>{$page}</td>
            <td>{$referrer}</td>
            <td>{$ip}</td>
            <td>{$language}</td>
            <td>{$screen_res}</td>
            <td>{$timestamp}</td>
          </tr>";
      }
    } else {
      $rows = '<tr><td colspan="7">No pageviews yet.</td></tr>';
    }

    $template = new Template('dashboard.html');
    return $template->render([
      'pageview_rows' => $rows,
    ]);
  }

}
