<?php

namespace App\Http\Controllers;

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

class SiswaController 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);
        if ($request->with !== null) {
            if (is_array($request->with)) {
                $relationships = [];
                foreach ($request->with as $relation) {
                    if ($relation === 'accessLog')
                        $relationships[$relation] = function ($query) use ($request) {
                            $query->where('src', '=', $request->src);
                        };
                    else
                        $relationships[$relation] = function ($query) { $query; };
                }
                $request->with = $relationships;
            }

            $siswa = $siswa->with($request->with);
        }

        $siswa = $siswa->first();

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

        /*
         * Write a new access log
         *
         */
        if ($request->src == 'surat-kelulusan')
            AccessLog::create(['siswa_id' => $siswa->id, 'src' => $request->src]);

        return $siswa;
    }
}
