<?php

namespace App\Modules\Bookings;

use App\Http\Controllers\BaseController;
use App\Modules\Bookings\Requests\AssignTasksToProjectRequest;
use App\Modules\Bookings\Requests\RemoveTaskFromProjectRequest;
use Illuminate\Http\Request;

class HelpersControllerREST extends BaseController
{
    public function getValidateTaskId(Request $request, $id)
    {
        $task = Task::query()->find($id);

        if (is_object($task) && $task->type == $request->input('type')) {
            return response()->json(['success' => true, 'task' => $task]);
        } else {
            return response()->json(['success' => false]);
        }
    }

    public function postAssignTasksToProject(AssignTasksToProjectRequest $request)
    {
        foreach ($request->input('tasks') as $id) {
            $task = Task::query()->find($id);
            $task->project_id = $request->input('project_id');
            $task->save();
        }

        $project = Project::query()->find($request->input('project_id'));
        $project->load('tasks', 'tasks.user', 'tasks.status', 'tasks.severity');

        return $project->tasks;
    }

    /**
     *	Removes a task from a project.
     */
    public function postRemoveTaskFromProject(RemoveTaskFromProjectRequest $request)
    {
        $task = Task::query()->find($request->input('id'));

        // Check to see if the task is assigned to the given project
        if ($task->project_id != $request->input('project_id')) {
            return response()->json(['error' => 'This task is not assigned to this project.'], 400);
        }

        // Remove the project id from the task
        $task->project_id = null;

        return $task->save() ? response()->json($task) : response()->json(['error' => 'Unable to update task'], 400);
    }
}
