<?php

namespace App\Modules\Workflow;

use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Request;
use App\Http\Controllers\BaseController;

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

    public function index()
    {
        $events = WorkflowEvent::all();

        $this->layout->content = View::make('workflow::index', compact('events'));
    }

    public function create()
    {
        $data = [
            'models'  => WorkflowHelpers::getModels(),
            'events'  => WorkflowHelpers::getEvents(),
            'actions' => WorkflowAction::getActions(),
            'data'    => ['filters' => [], 'condition_true' => [], 'condition_false' => []],
        ];

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

    public function show($id)
    {
        $data = [
            'models'  => WorkflowHelpers::getModels(),
            'events'  => WorkflowHelpers::getEvents(),
            'actions' => WorkflowAction::getActions(),
            'data'    => WorkflowEvent::findOrFail($id)->load('condition_true', 'condition_false')->toArray(),
        ];

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

    public function store(Request $request)
    {
        $event = WorkflowEvent::create($request->all());

        if (! $event->id) {
            return response()->json(['errors' => $event->errors->all()], 400);
        }

        foreach ($request->input('condition_true') as $value) {
            $action = new WorkflowAction($value);
            $action->workflow_event_id = $event->id;
            $action->condition = 1;
            $action->save();
        }

        foreach ($request->input('condition_false') as $value) {
            $action = new WorkflowAction($value);
            $action->workflow_event_id = $event->id;
            $action->condition = 0;
            $action->save();
        }

        return $event;
    }

    public function update($id)
    {
        $event = WorkflowEvent::findOrFail($id);
        $event->fill(Request::all());

        if ($event->save()) {
            $event->actions()->delete();

            // Store all the actions again
            foreach (Request::input('condition_true') as $value) {
                $action = new WorkflowAction($value);
                $action->workflow_event_id = $event->id;
                $action->condition = 1;
                $action->save();
            }

            foreach (Request::input('condition_false') as $value) {
                $action = new WorkflowAction($value);
                $action->workflow_event_id = $event->id;
                $action->condition = 0;
                $action->save();
            }
        } else {
            return response()->json(['errors' => $event->errors->all()], 400);
        }
    }
}
