<?php

namespace App\Http\Controllers;

use App\HasilBelajar;
use App\Siswa;
use App\AccessLog;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use Illuminate\Http\Request;

class HasilBelajarController extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {
        /*
         * Validate user inputs
         *
         */
        Validator::make($request->all(), [
            'nisn' => 'required|regex:/^[0-9]+$/',
            'tanggalLahir' => 'required|regex:/^[0-9]+$/',
        ], [
            'required' => 'Kolom :attribute harus diisi.',
            'regex' => 'Kolom :attribute tidak sesuai.',
        ])->validate();

        /*
         * Look for the given inputs in the resource
         *
         */
        try {
            $tanggalLahir = Carbon::parse($request->tanggalLahir)->format('Y-m-d');
        } catch(Exception $e) {
            return response()->json([
                'message' => 'The given data was invalid.',
                'errors' => [
                    'tanggalLahir' => ['Kolom tanggal lahir tidak sesuai.'],
                ]
            ], 422);
        }
        $siswa = Siswa::where('nisn', $request->nisn)
                                              ->where('tanggal_lahir', $tanggalLahir)
                                              ->with('hasilBelajar')
                                              ->first();

        /*
         * Redirect with error if not found
         *
         */
        if (!$siswa || $siswa == null) {
            return response()->json(['errors' => ['siswa' => ['Siswa tidak ditemukan.']]], 404);
        }

        return $siswa;
    }
}
