<?php

namespace App\Modules\Bookings;

use Illuminate\Support\Facades\View;
use App\Models\User;
use App\Models\Severity;
use Illuminate\Support\Facades\Redirect;
use App\Models\Status;
use App\Http\Controllers\BaseController;

class TasksController extends BaseController
{
    /**
     *	The layout that should be used for responses.
     */
    protected $layout = 'layouts.master';

    /**
     *	Returns the index page.
     */
    public function getIndex()
    {
        $data = [
            'subtypes'      => TaskSubtype::support()->get(),
            'users'         => User::with('profile_photo')->where('active', 1)->orderBy('first_name', 'asc')->get(),
            'severities'    => Severity::all(),
            'statuses'      => Status::repairs()->get(),
            'types'         => TaskType::getTaskTypes(),
        ];
        $this->layout->content = View::make('bookings::tasks', $data);
    }

    /**
     *	Returns a page for a single task.
     */
    public function showTask($id = 0)
    {
        if (! $id) {
            return Redirect::to('/');
        }

        $task = Task::find($id);

        $severities = [];
        foreach (Severity::all() as $severity) {
            $severities[$severity->id] = $severity->name;
        }

        $data = [
            'users'      => User::with('profile_photo')->where('active', 1)->orderBy('first_name', 'asc')->get(),
            'severities' => $severities,
            'statuses'   => Status::repairs()->get(),
            'task'       => $task,
        ];

        $this->layout->content = View::make('bookings::task', $data);
    }

    /**
     * Displays a printer friendly format of a task.
     *
     * @param  int $id
     *
     * @return mixed
     */
    public function showPrintView($id = 0)
    {
        if (! $id) {
            return Redirect::to('/');
        }

        if (! $task = Task::find($id)) {
            return Redirect::to('/');
        }

        $task->load('devices.model_number', 'devices.model_number.manufacturer');

        $this->layout->content = View::make('bookings::print-view', compact('task'));
    }

    /**
     * Displays a printer friendly format of a task.
     *
     * @param  int $id
     *
     * @return mixed
     */
    public function showPrintReport($id = 0)
    {
        if (! $id) {
            return Redirect::to('/');
        }

        if (! $task = Task::find($id)) {
            return Redirect::to('/');
        }

        $task->load('devices.model_number.manufacturer');

        $task->load(['devices.revisionHistory' => function ($q) use ($task) {
            $q->where('created_at', '>=', $task->created_at);
        }, 'comments' => function ($q) {
            $q->where('public', 1);
        }, 'completed_template_items', ]);

        return View::make('bookings::print-report', compact('task'));
    }
}
