<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Validator;
use App\Responses;
use App\Helper;
use App\Models\Users;

class AuthController extends Controller
{
    // public function view_login(Request $req)
    // {
    // 	return 'Do login';
    // }
    public function view_login_admin(Request $req)
    {
        return view("auth.loginAdmin");
    }
    public function view_login_client(Request $req)
    {
        return view("auth.loginClient");
    }
    public function view_login_vendor(Request $req)
    {
        return view("auth.loginVendor");
    }
    public function view_login_checker(Request $req)
    {
        return view("auth.loginChecker");
    }

    public function api_login(Request $req)
    {
        try {
            $now = time();

            $input = [
                "password" => $req->password,
            ];
            $rulesInput = [
                "password" => "required|string",
            ];

            if ($req->email) {
                $input["email"] = $req->email;
                $rulesInput["email"] = "required|email";
            }
            if ($req->phone) {
                $input["phone"] = $req->phone;
                $rulesInput["phone"] = "required|integer";
            }

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

            $getUser = Users::getUserByEmail($req->email);
            if (count($getUser) < 1) {
                $getUser = Users::getUserByPhone($req->phone);
                if (count($getUser) < 1) {
                    $apiResp = Responses::not_found("akun tidak ditemukan");
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
            }

            $apiResp = Responses::success("sukses login");
            return new Response($apiResp, $apiResp["meta"]["code"]);
        } catch (\Exception $e) {
            $apiResp = Responses::error($e->getMessage());
            return new Response($apiResp, $apiResp["meta"]["code"]);
        }
    }
}
