<?php

namespace App\Http\Controllers\Pages;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Yajra\Datatables\Datatables;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $page_title = 'Login History';
        $page_description = 'This is Login test page';
        $page_breadcrumbs = [
            ['page' => 'login-history', 'title' => 'Users'],
            ['page' => 'login-history', 'title' => 'History Login']
        ];
        return view('pages.login.index', compact('page_title', 'page_description', 'page_breadcrumbs'));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request)
    {
        $res = '';
        $query = $request->qr;
        $dtfrom = $request->df;
        $dtto = $request->dt;
        $result = DB::table('logins')
            ->join('users', 'logins.iduser', '=', 'users.iduser')
            ->select('logins.*', 'users.name');
        if ($query != null) {
            $res = $result->where('logins.hostname', 'LIKE', '%' . $query . '%')
                ->where(function ($where) use ($query) {
                    $where->orWhere('logins.ipaddress', 'LIKE', '%' . $query . '%')
                        ->orWhere('logins.country', 'LIKE', '%' . $query . '%')
                        ->orWhere('logins.regional', 'LIKE', '%' . $query . '%')
                        ->orWhere('logins.city', 'LIKE', '%' . $query . '%')
                        ->orWhere('logins.longitude', 'LIKE', '%' . $query . '%')
                        ->orWhere('logins.latitude', 'LIKE', '%' . $query . '%')
                        ->orWhere('logins.browser1', 'LIKE', '%' . $query . '%')
                        ->orWhere('logins.browser2', 'LIKE', '%' . $query . '%')
                        ->orWhere('logins.osystem', 'LIKE', '%' . $query . '%')
                        ->orWhere('users.name', 'LIKE', '%' . $query . '%');
                })
                ->get();
        }
        if ($dtfrom != null and $dtto != null) {
            $res = $result->whereBetween(DB::raw('LEFT(logins.created_at,10)'), [$dtfrom, $dtto])->get();
        }

        $i = 0;
        $array = array();
        foreach ($res as $data) {
            $i++;
            $array[] = array(
                'no' => $i,
                'name' => $data->name,
                'ipaddress' => $data->ipaddress,
                'country' => $data->country,
                'regional' => $data->regional,
                'city' => $data->city,
                'browser' => $data->browser1,
                'osystem' => $data->osystem,
                'created_at' => $data->created_at,
            );
        }
        return Datatables::of($array)->make(true);
    }
}
