<?php

namespace App\Controllers;

use App\Services\DashboardService;
use App\Services\TaskService;

class DashboardController extends BaseController
{
    public function index()
    {
        $userId = (int) session()->get('user_id');
        $dash   = new DashboardService();
        $tasks  = new TaskService();
        $resolved = $dash->resolve($userId, (array) $this->request->getGet(), session()->get(DashboardService::SESSION_KEY));
        $filters  = $resolved['filters'];
        $dash->rememberReturn('dashboard', $filters);

        $categories = $tasks->categoriesForUser($userId);

        return view('dashboard/index', [
            'title'          => 'Home',
            'activeNav'      => 'home',
            'dash'           => $dash,
            'filters'        => $filters,
            'filterError'    => $resolved['error'],
            'categories'     => $categories,
            'grouped'        => $dash->groupedByPriority($userId, $filters),
            'emptyMessage'   => $dash->emptyMessage($filters),
            'filterBasePath' => 'dashboard',
            'dateLabel'      => $dash->dateLabel($filters),
            'statusLabel'    => $dash->statusLabel($filters),
            'categoryLabel'  => $dash->categoryLabel($filters, $categories),
        ]);
    }

    public function filter()
    {
        $query = [
            'date'     => (string) $this->request->getPost('date'),
            'status'   => (string) $this->request->getPost('status'),
            'category' => (string) $this->request->getPost('category'),
            'from'     => (string) $this->request->getPost('from'),
            'to'       => (string) $this->request->getPost('to'),
        ];
        $path = (string) $this->request->getPost('path');
        if ($path !== 'dashboard' && preg_match('#^tasks/priority/[1-4]$#', $path) !== 1 && $path !== 'tasks/search') {
            $path = 'dashboard';
        }

        $dash = new DashboardService();
        $merged = array_merge($dash->defaults(), $query);
        $search = $dash->normalizeSearchQuery((string) $this->request->getPost('q'));
        if ($path === 'tasks/search' && $search !== '') {
            $merged['q'] = $search;
        }
        $url = $dash->href($path, $merged);

        return redirect()->to($url);
    }
}
