<?php

namespace Origo\Controller;

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

class PlannerController extends ControllerBase implements ControllerInterface {

  public function getResponse(): string {

    // Okie dokie. so here i need to get the users id,
    // then load all the tasks for that user.
    // I guess sorting by their creation date would be good.
    $user = new User();
    $user->loadUserFromSession($this->request->getCookie('ORIGOSESS'));
    $query = $this->database->query("SELECT * FROM tasks WHERE user_id = (:user_id) ORDER BY created_at DESC");
    $user_id = $user->get('id');
    $query->bindParam(':user_id', $user_id);
    $query->execute();
    $results = $query->fetchAll();

    $tasks = '<div class="task-container">';

    if ($results) {
      foreach ($results as $result) {
        $title = htmlspecialchars($result['task']);
        $status = htmlspecialchars($result['status']);
        $description = htmlspecialchars($result['description']);
        $url = htmlspecialchars($result['external_url']);

        $statusClass = (strtolower($status) === 'completed') ? 'status-completed' : 'status-pending';

        $tasks .= '
          <div class="task-card">
          <div class="task-info">
          <h3 class="task-title">' . $title . '</h3>
          <div class="task-description">' . $description . '</div>';

        if ($url) {
          $tasks .= '<a href="' . $url . '" class="btn btn-soft-clay" target="_blank">View Details →</a>';
        }

        $tasks .= '
          </div>
          <div class="task-status ' . $statusClass . '">' . $status . '</div>
          </div>';
      }
    } else {
      $tasks .= '<p style="text-align:center; color:var(--color-medium-gray);">No tasks yet.</p>';
    }

    $tasks .= '</div>';

    $template = new Template('task-list.html');
    return $template->render([
      'tasks' => $tasks,
    ]);
  }

}
