<?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 AddController extends Controller
{
    public function __invoke(Request $request)
    {
        Util::ensureDraftElectionAfterCompletedCycle();
    	$this->validateRequest($request);
    	$voter = $this->insertVoter($request);

        activity()
            ->performedOn($voter)
            ->withProperties([
                'election_id' => $voter->election_id,
                'voter_id' => $voter->id,
                'voter_name' => $voter->name,
                'no_kp' => $voter->no_kp,
                'no_anggota' => $voter->no_anggota,
                'unit' => $voter->unit,
                'created_by_admin_id' => $request->user() ? (int) $request->user()->id : null,
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("create voter: {$voter->name}");
    	return response()->json([
    		'status' => 'success',
    		'message' => 'Voter added successfully'
    	]);
    }

    private function insertVoter($request)
    {
    	$voter = $request->all();
    	$voter['election_id'] = Util::getCurrentElection();
    	return Voter::create($voter);
    }

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