<?php

namespace App\Http\Controllers;

use App\Siswa;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class AccessLogController extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {
        /*
         * Count unique logs for the given source
         *
         */
        $logs = DB::table('access_logs')
            ->select(DB::raw('count(*) as num'))
            ->join('siswas', 'access_logs.siswa_id', '=', 'siswas.id')
            ->where('access_logs.src', $request->src)
            ->whereYear('siswas.created_at', date('Y'))
            ->groupBy('access_logs.siswa_id')
            ->get()
            ->count();

        /*
         * Count the total number of siswa
         *
         */
        $resources = Siswa::whereYear('created_at', date('Y'))
                   ->count();

        return response()->json([
            'accessed' => $logs,
            'total' => $resources,
        ]);
    }
}
