<?php

namespace App\Libraries;

/**
 * Class Response
 *
 * @package App\Libraries
 */
class Response
{
    /**
     * @var null
     */
    protected $response = null;

    protected $errors = null;

    protected $message = null;

    protected $success = false;

    /**
     * Set response
     *
     * @param array $data
     * @return $this
     */
    public function setResponse($data = [])
    {
        if (is_null($this->response)) {
            $this->response = [];
        }
        $this->response = (is_array($data) ? array_merge($this->response, (array)$data) : $data);

        return $this;
    }

    /**
     * Set message
     *
     * @param array|null $data
     * @return $this
     */
    public function setMessage($data = null)
    {
        if (is_array($this->message) || is_array($data)) {
            $this->message = (is_array($this->message) ? array_merge($data, $this->message) : $data);
        } else {
            $this->message = $data;
        }

        return $this;
    }

    /**
     * Set errors
     *
     * @param object $fromValidator
     * @return $this
     */
    public function setErrors($fromValidator = null)
    {
        if (is_object($fromValidator) && method_exists($fromValidator, 'all')) {
            $this->errors = (count($fromValidator->all()) === 0 ? null : $fromValidator);
        } else {
            $this->errors = (is_array($fromValidator) && count($fromValidator) === 0 ? null : $fromValidator);
        }

        return $this;
    }

    /**
     * Set success
     *
     * @param bool $success
     * @return $this
     */
    public function setSuccess($success = false)
    {
        $this->success = $success;

        return $this;
    }

    /**
     * Response to json
     *
     * @param int $status
     * @param array $headers
     * @return \Illuminate\Http\JsonResponse
     */
    public function toJson($status = 200, array $headers = [])
    {
        $response = [
            'response' => $this->response,
            'message' => $this->message,
            'errors' => $this->errors,
            'success' => $this->success
        ];

        if (starts_with(request()->root(), 'http://localhost:8000')) {
            $response['debug'] = \DB::getQueryLog();
        }

        return response()->json($response, $status, $headers);
    }
}