<?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)
    {
    	$this->validateRequest($request);
    	$this->insertNominee($request);
    	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',
    		'image' => 'nullable|image'
    	]);
    }

    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;
        }

    	Nominee::create($nominee);
        return response()->json(['message' => 'Photo updated successfully']);


    }
}
