<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\AccessLog;
use App\Models\Log;

class LogController extends Controller
{
    // for logging
    public function log($type, $action, $description)
    {
        $log = new Log();
        $log->user_id = auth()->user()->id;
        $log->type = $type;
        $log->action = $action;
        $log->description = $description;
        $log->save();
    }

    public function get_access_log($date)
    {
        $tmp = explode('/', $date);
        $month = $tmp[0];
        $year = $tmp[1];
        $access = AccessLog::select('username', 'access_logs.created_at as access', 'ipaddress')
                            ->leftJoin('users', 'users.id', '=', 'access_logs.user_id')
                            ->whereMonth('access_logs.created_at', '=', $month)
                            ->whereYear('access_logs.created_at', '=', $year)
                            ->where('users.id', '!=', '0')
                            ->orderBy('access_logs.created_at')
                            ->get();
        return $access;
    }

    public function access_log()
    {
        $access_log = $this->get_access_log(date('m/Y'));
        return view('log.access')->with([
            'page_title' => 'บันทึกการเข้าระบบ',
            'date' => date('m/Y'),
            'logs' => $access_log,
        ]);
    }

    public function access_log_post(Request $request)
    {
        $access_log = $this->get_access_log($request->date);
        return view('log.access')->with([
            'page_title' => 'บันทึกการเข้าระบบ',
            'date' => $request->date,
            'logs' => $access_log,
        ]);
    }

    public function get_event_log($date)
    {
        $tmp = explode('/', $date);
        $month = $tmp[0];
        $year = $tmp[1];
        $logs = Log::select('username', 'logs.created_at as time', 'type', 'action', 'description')
                            ->leftJoin('users', 'users.id', '=', 'logs.user_id')
                            ->whereMonth('logs.created_at', '=', $month)
                            ->whereYear('logs.created_at', '=', $year)
                            ->where('users.id', '!=', '0')
                            ->orderBy('logs.created_at')
                            ->get();
        return $logs;
    }

    public function event_log()
    {
        $logs = $this->get_event_log(date('m/Y'));
        return view('log.log')->with([
            'page_title' => 'บันทึกการใช้งานระบบ',
            'date' => date('m/Y'),
            'logs' => $logs,
        ]);
    }

    public function event_log_post(Request $request)
    {
        $logs = $this->get_event_log($request->date);
        return view('log.log')->with([
            'page_title' => 'บันทึกการใช้งานระบบ',
            'date' => $request->date,
            'logs' => $logs,
        ]);
    }

}
