<?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 AddController extends Controller
{

    public function __invoke (Request $request)
    {
        Util::ensureDraftElectionAfterCompletedCycle();
    	$this->validateRequest($request);
    	$nominee = $this->insertNominee($request);

        activity()
            ->performedOn($nominee)
            ->withProperties([
                'nominee_id' => $nominee->id,
                'nominee_name' => $nominee->name,
                'election_id' => $nominee->election_id,
                'position_id' => $nominee->position_id,
                'partylist_id' => $nominee->partylist_id,
                'created_by_admin_id' => $request->user() ? (int) $request->user()->id : null,
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("create nominee: {$nominee->name}");
    	return response()->json([
    		'status' => 'success',
    		'message'=> 'Nominee added successfully'
    	]);
    }

    public function validateRequest ($request)
    {
    	$this->validate($request, [
            'name' => [
                'required',
                Rule::unique('nominee')->where(function($query){
                    $query->where('election_id', Util::getCurrentElection());
                })
            ],
            'no_anggota' => [
                'required',
                Rule::unique('nominee')->where(function($query){
                    $query->where('election_id', Util::getCurrentElection());
                })
            ],
    		'unit' => 'required',
    		'position_id' => 'required|exists:position,id',
    		'partylist_id' => 'nullable|exists:partylist,id',
    		'photo' => 'nullable',
    		'umur' => 'nullable|integer|min:1|max:120',
    		'jawatan_sekarang' => 'nullable|string|max:255',
    		'experience' => 'nullable|string',
    		'education' => 'nullable|string',
    	]);
    }

    public function insertNominee ($request)
    {
        $nominee = $request->except(['photo']);
    	$nominee['election_id'] = Util::getCurrentElection();

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

    	return Nominee::create($nominee);
    }
}
