<?php

namespace App\Http\Controllers\API\v1\Voter;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Util;
use App\Voter;

class AttendanceController extends Controller
{
    //
    public function __invoke(Request $request, $id)
    {
    	$this->validateRequest($request, $id);
    	$this->updateAttendance($request, $id);
    	return response()->json([
    		'status' => 'success',
    		'message' => 'Kehadiran anda telah disahkan.'
    	]);
    }

    private function validateRequest($request, $id)
    {
    	$this->validate($request, [
    		'name' => [
                'required', 
                Rule::unique('voter')->ignore($id)->where(function($query){
                    $query->where('election_id', Util::getCurrentElection());
                })
            ],
    		'no_kp' => [
                'required', 
                Rule::unique('voter')->ignore($id)->where(function($query){
                    $query->where('election_id', Util::getCurrentElection());
                })
            ],

    		'unit' => 'required',

            'no_anggota' => [
                'required', 
                Rule::unique('voter')->ignore($id)->where(function($query){
                    $query->where('election_id', Util::getCurrentElection());
                })
            ],

            'kehadiran' => 'required'

    	]);
    }

    private function updateAttendance($request, $id)
    {
    	$voter = $request->all();
    	Voter::find($id)->update($voter);
    }

}
