<?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 UpdateController extends Controller
{
    public function __invoke(Request $request, $id)
    {
    	$this->validateRequest($request, $id);
    	$this->updateVoter($request, $id);
    	return response()->json([
    		'status' => 'success',
    		'message' => 'Voter updated successfully.'
    	]);
    }

    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'
    	]);
    }

    private function updateVoter($request, $id)
    {
    	$voter = Voter::findOrFail($id);

        $old = $voter->toArray();
        $voter->fill($request->all());
        $voter->save();

        $dirtyKeys = array_keys($voter->getChanges());

        activity()
            ->performedOn($voter)
            ->withProperties([
                'voter_id' => $voter->id,
                'voter_name' => $voter->name,
                'election_id' => Util::getCurrentElection(),
                'changed_keys' => $dirtyKeys,
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("update voter: {$voter->name}");
    }
}
