<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Validator;
use App\Responses;
use App\Helper;

class LoggerController extends Controller
{
    /**
     * API
     */

    public function logger(Request $req)
    {
        $now = time();
        try {
            $input = [
                "label" => $req->label,
                "level" => $req->level,
                "logtype" => $req->logtype,
                "keys" => $req->keys,
                "act" => "email",
                "to" => ["emirsyafmun@gmail.com"],
                "errors" => $req->errors,
                "vers" => "1.2.1",
                "source" => "service",
                "payloads" => $req->payloads,
            ];
            $rulesInput = [
                "label" => "required|string",
                "level" => "required|numeric",
                "logtype" => "required|string",
                "keys" => "required|array",
                "act" => "required|string",
                "to" => "nullable|array",
                "errors" => "nullable|string",
                "vers" => "required|string",
                "source" => "required|string",
                "payloads" => "nullable|string",
            ];

            // validasi input
            $isValidInput = Validator::make($input, $rulesInput);
            if (!$isValidInput->passes()) {
                $apiResp = Responses::bad_input($isValidInput->messages()->first());
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            $payload = Helper::createPayload([
                "usnme" => "emrsyf",
                "paswd" => 12345678,
            ]);
            $login = Helper::req_post(
                "https://api.simerahputih.com/logger/login",
                ["Content-Type: application/x-www-form-urlencoded"],
                $payload
            );

            // $payload = Helper::createPayload($input);
            // dd($payload);
            $resp = Helper::req_post(
                "https://api.simerahputih.com/logger/log",
                ["Content-Type: application/json", "x-api-key: " . $login["data"]->data->token],
                json_encode($input)
            );

            $apiResp = Responses::success("success send log");
            return new Response($apiResp, $apiResp["meta"]["code"]);
        } catch (\Exception $e) {
            dd($e);
        }
    }
}
