<?php

namespace App\Modules\Bookings;

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

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

    /**
     *	Returns the index page.
     */
    public function getIndex($id = 0)
    {
        if (! $id) {
            return Redirect::to('/');
        }

        $qa = QA::find($id);

        // Redirect back to the dashboard if the ID was not
        // found or the task is not a followup one.
        if (! $qa or $qa->type != 'qa') {
            return Redirect::to('/');
        }

        // Get the original job that the QA is for
        $task = Task::findOrFail($qa->qa_id);

        // Check to see if the user has permission to read the QA
        if ($qa->assigned_to != getAuthUserId()) {
            switch ($task->type) {
                case 'support':
                    if (! Auth::user()->hasPermission('read_qa_support')) {
                        return Redirect::to('/');
                    }
                    break;

                case 'repair':
                    if (! Auth::user()->hasPermission('read_qa_repairs')) {
                        return Redirect::to('/');
                    }
                    break;

                case 'onsite':
                    if (! Auth::user()->hasPermission('read_qa_onsite')) {
                        return Redirect::to('/');
                    }
                    break;
            }
        }

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

        $data = [
            'users'      => User::getActiveList(),
            'severities' => $severities,
            'statuses'   => Status::repairs()->get(),
            'task'       => $task,
            'qa'         => $qa,
        ];

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