<?php

namespace Litecms\Faucet\Http\Controllers;

use App\Http\Controllers\Controller as BaseController;
use Litecms\Faucet\Http\Requests\FaucetRequest;
use Litecms\Faucet\Models\Faucet;

/**
 * Admin web controller class.
 */
class FaucetWorkflowController extends BaseController
{

    /**
     * Workflow controller function for faucet.
     *
     * @param Model   $faucet
     * @param step    next step for the workflow.
     *
     * @return Response
     */

    public function putWorkflow(FaucetRequest $request, Faucet $faucet, $step)
    {

        try {

            $faucet->updateWorkflow($step);

            return response()->json([
                'message'  => trans('messages.success.changed', ['Module' => trans('faucet::faucet.name'), 'status' => trans("app.{$step}")]),
                'code'     => 204,
                'redirect' => trans_url('/admin/faucet/faucet/' . $faucet->getRouteKey()),
            ], 201);

        } catch (Exception $e) {

            return response()->json([
                'message'  => $e->getMessage(),
                'code'     => 400,
                'redirect' => trans_url('/admin/faucet/faucet/' . $faucet->getRouteKey()),
            ], 400);

        }

    }

    /**
     * Workflow controller function for faucet.
     *
     * @param Model   $faucet
     * @param step    next step for the workflow.
     * @param user    encrypted user id.
     *
     * @return Response
     */

    public function getWorkflow(Faucet $faucet, $step, $user)
    {
        try {
            $user_id = decrypt($user);

            Auth::onceUsingId($user_id);

            $faucet->updateWorkflow($step);

            $data = [
                'message' => trans('messages.success.changed', ['Module' => trans('faucet::faucet.name'), 'status' => trans("app.{$step}")]),
                'status'  => 'success',
                'step'    => trans("app.{$step}"),
            ];

            return $this->theme->layout('blank')->of('faucet::admin.faucet.message', $data)->render();

        } catch (ValidationException $e) {

            $data = [
                'message' => '<b>' . $e->getMessage() . '</b> <br /><br />' . implode('<br />', $e->validator->errors()->all()),
                'status'  => 'error',
                'step'    => trans("app.{$step}"),
            ];

            return $this->theme->layout('blank')->of('faucet::admin.faucet.message', $data)->render();

        } catch (Exception $e) {

            $data = [
                'message' => '<b>' . $e->getMessage() . '</b>',
                'status'  => 'error',
                'step'    => trans("app.{$step}"),
            ];

            return $this->theme->layout('blank')->of('faucet::admin.faucet.message', $data)->render();

        }

    }
}