<?php

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

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

class UpdateController extends Controller
{
    public function __invoke (Request $request, $id)
    {
    	$this->validateRequest($request, $id);
    	$this->updateNominee($request, $id);
    	return response()->json([
    		'status' => 'success',
    		'message' => 'Nominee updated successfully'
    	]);
    }

    private function validateRequest($request, $id)
    {
    	$this->validate($request, [
    		'name' => [
                'required', 
                Rule::unique('nominee')->ignore($id)->where(function($query){
                    $query->where('election_id', Util::getCurrentElection());
                })
            ],
    		'no_anggota' => [
                'required', 
                Rule::unique('nominee')->ignore($id)->where(function($query){
                    $query->where('election_id', Util::getCurrentElection());
                })
            ],
    		'unit' => 'required',
    		'position_id' => 'required|exists:nominee,position_id',
    		'partylist_id' => 'nullable|exists:nominee,partylist_id'
    	]);
    }

    private function updateNominee ($request, $id)
    {
    	$nominee = Nominee::find($id);

    	$nominee->name = $request->name;
    	$nominee->unit = $request->unit;
    	$nominee->no_anggota = $request->no_anggota;
    	$nominee->position_id = $request->position_id;
    	$nominee->partylist_id = $request->partylist_id;
        $nominee->education = $request->education;
        $nominee->experience = $request->experience;

        if ($request->hasFile('photo')) {
            $imageData = file_get_contents($request->file('photo'));
            $nominee->photo = $imageData;
        }

    	$nominee->save();
    }

}
