<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Task;
use App\Project;
use Request;
use Illuminate\Support\Facades\DB;


class TodoController extends Controller {

  public function getT($from, $to) {
    
  }

  public function getIndex() {
    return view('todo.list');
  }

  
 //return all the projects in json format
  public function postAllProjects() {
    
    $projects = Project::getProjectsByUser(1);;//todo: change by the logged user
    return response()->json($projects);
    
  }
  
    //return all task in json format
  public function postAllTasks($project){
    
    //todo: set it in a model
    $tasks = Task::where('project_id', $project)
            ->orderBy('priority')
            ->get();
    return response()->json($tasks);
    
  }

  public function postUpdatePriority($from, $to) {

    $step = ($from > $to) ? 1 : -1;
    $taskFrom = Task::where('priority', $from)->first();
    $taskTo = Task::where('priority', $to)->first();
    $priority = $taskTo->priority + $step;
    Task::where('priority', '>', min([$from, $to]))
            ->where('priority', '<', max([$from, $to]))
            ->increment('priority', $step);

    $taskFrom->priority = $taskTo->priority;
    $taskTo->priority = $priority;
    $taskTo->save();
    $taskFrom->save();
  }

  public function postAdd() {

    $task = [
        'user_id' => 1,
        'description' => Request::input('task.description'),
        'status' => 0,
        'priority' => DB::table('task')->max('priority') + 1
    ];

    Task::create($task);
  }

}
