<?php

namespace App\Contracts;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Laracasts\Flash\Flash;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

/**
 * Class Controller
 */
abstract class Controller extends \Illuminate\Routing\Controller
{
    use AuthorizesRequests;
    use DispatchesJobs;
    use ValidatesRequests;

    /**
     * Write a error to the flash and redirect the user to a route
     *
     *
     * @return mixed
     */
    public function flashError($message, $route)
    {
        Flash::error($message);

        return redirect(route($route))->withInput();
    }

    /**
     * Shortcut function to get the attributes from a request while running the validations
     *
     *
     * @throws BadRequestHttpException
     * @throws ValidationException
     */
    public function getFromReq(Request $request, array $attrs_or_validations, ?array $addtl_fields = null): array
    {
        // See if a list of values is passed in, or if a validation list is passed in
        $is_validation = false;
        if (array_filter(array_keys($attrs_or_validations), \is_string(...)) !== []) {
            $is_validation = true;
        }

        if ($is_validation) {
            $this->validate($request, $attrs_or_validations);
        }

        $fields = [];
        foreach ($attrs_or_validations as $idx => $field) {
            if ($is_validation) {
                $field = $idx;
            }

            if ($request->filled($field)) {
                $fields[$field] = $request->input($field);
            }
        }

        if ($addtl_fields !== null && $addtl_fields !== []) {
            return array_merge($fields, $addtl_fields);
        }

        return $fields;
    }

    /**
     * Simple normalized method for forming the JSON responses
     *
     * @param  null|mixed   $count
     * @param  mixed        $attrs
     * @return JsonResponse
     */
    public function message($message, $count = null, $attrs = [])
    {
        $ret = [
            'message' => $message,
            'attrs'   => $attrs,
        ];

        if ($count !== null) {
            $ret['count'] = $count;
        }

        return response()->json($ret);
    }
}
