<?php

namespace Hubleto\App\Community\Tasks;

class Loader extends \Hubleto\Erp\App
{

  /**
   * Inits the app: adds routes, settings, calendars, event listeners, menu items, ...
   *
   * @return void
   * 
   */
  public function init(): void
  {
    parent::init();

    $this->router()->get([
      '/^tasks\/api\/create-from-mail\/?$/' => Controllers\Api\CreateFromMail::class,

      '/^tasks\/boards\/my-recent-tasks\/?$/' => Controllers\Boards\MyRecentTasks::class,

      '/^tasks(\/(?<recordId>\d+))?\/?$/' => Controllers\Tasks::class,
      '/^tasks\/add?\/?$/' => ['controller' => Controllers\Tasks::class, 'vars' => [ 'recordId' => -1 ]],

      '/^tasks\/todo(\/(?<recordId>\d+))?\/?$/' => Controllers\Todos::class,
      '/^tasks\/todo\/add?\/?$/' => ['controller' => Controllers\Todos::class, 'vars' => [ 'recordId' => -1 ]],
    ]);

    $this->addSearchSwitch('t', 'tasks');

    /** @var \Hubleto\App\Community\Workflow\Manager */
    $workflowManager = $this->getService(\Hubleto\App\Community\Workflow\Manager::class);
    $workflowManager->addWorkflow($this, 'tasks', Workflow::class);

    /** @var \Hubleto\App\Community\Dashboards\ */
    $boards = $this->getService(\Hubleto\App\Community\Dashboards\Manager::class);
    $boards->addBoard( $this, $this->translate('My recent tasks'), 'tasks/boards/my-recent-tasks');

    /** @var \Hubleto\App\Community\Calendar\Manager $calendarManager */
    $calendarManager = $this->getService(\Hubleto\App\Community\Calendar\Manager::class);
    $calendarManager->addCalendar($this, 'tasks', Calendar::class);

  }

  // upgradeSchema
  public function installApp(int $round): void
  {
    if ($round == 1) {
      $this->getModel(Models\Task::class)->upgradeSchema();
      $this->getModel(Models\Todo::class)->upgradeSchema();
    }
  }

  /**
   * [Description for getSidebarBadgeNumber]
   *
   * @return int
   *
   */
  public function getSidebarBadgeNumber(): int
  {
    /** @var Counter */
    $counter = $this->getService(Counter::class);

    return
      $counter->myDueTodo()
    ;
  }

  /**
   * [Description for renderSecondSidebar]
   *
   * @return string
   *
   */
  public function renderSecondSidebar(): string
  {
    $counter = $this->getService(Counter::class);
    $myDueTodo = $counter->myDueTodo();
    return '
      <div class="flex flex-col gap-2">
        <a class="btn btn-primary-outline btn-square" href="' . $this->env()->projectUrl . '/tasks">
          <span class="icon"><i class="fas fa-list-check"></i></span>
          <span class="text text-primary">' . $this->translate('Tasks') . '</span>
        </a>
        <a class="btn btn-transparent" href="' . $this->env()->projectUrl . '/tasks/todo">
          <span class="icon"><i class="fas fa-receipt"></i></span>
          <span class="text">' . $this->translate('Todo') . '</span>
          ' . ($myDueTodo > 0 ? '<span class="badge badge-danger ml-auto">' . $myDueTodo . '</span>' : '') . '
        </a>
        <a class="btn btn-transparent" href="' . $this->env()->projectUrl . '/calendar?show=tasks">
          <span class="icon"><i class="fas fa-calendar-days"></i></span>
          <span class="text">' . $this->translate('Calendar') . '</span>
        </a>
      </div>
    ';
  }

  /**
   * Implements fulltext search functionality for tasks
   *
   * @param array $expressions List of expressions to be searched and glued with logical 'or'.
   * 
   * @return array
   * 
   */
  public function search(array $expressions): array
  {
    $mTask = $this->getModel(Models\Task::class);
    $qTasks = $mTask->record->prepareReadQuery();
    
    foreach ($expressions as $e) {
    //   $qTasks = $qTasks->whereRaw('
    //     (
    //       tasks.identifier like ?
    //       or tasks.title like ?
    //       or (
    //         select deals_tasks.id from deals_tasks
    //         left join deals on deals.id = deals_tasks.id_deal
    //         where
    //           deals_tasks.id_task = tasks.id
    //           and deals.title like ?
    //       )
    //       or (
    //         select projects_tasks.id from projects_tasks
    //         left join projects on projects.id = projects_tasks.id_project
    //         where
    //           projects_tasks.id_task = tasks.id
    //           and projects.title like ?
    //       )
    //     )
    //     and not tasks.is_closed
    //   ', [
    //     '%' . $e . '%', '%' . $e . '%', '%' . $e . '%',
    //     '%' . $e . '%'
    //   ]);
      $qTasks = $qTasks->having(function($q) use ($e) {
        $q->orHaving('tasks.identifier', 'like', '%' . $e . '%');
        $q->orHaving('tasks.title', 'like', '%' . $e . '%');
        // $q->orHaving('virt_related_to', 'like', '%' . $e . '%');
      })
      ->where('tasks.is_closed', false);
    }

    $tasks = $qTasks->get()->toArray();
    $results = [];

    foreach ($tasks as $task) {
      $results[] = [
        "id" => $task['id'],
        "label" => $task['identifier'] . ' ' . $task['title'],
        "url" => 'tasks/' . $task['id'],
        "description" => $task['virt_related_to'], //($task['PROJECTS'][0]['PROJECT']['title'] ?? ''),
      ];
    }

    return $results;
  }

}
