<?php

namespace App\Http\Middleware;

use Closure;
use \App\Http\Controllers\Util;

class ElectionMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if ($this->isElection($request)) {
            return response()->json([
                'status'  =>  'failed',
                'message'  => 'Anda tidak boleh menambah, mengemas kini, atau menghapus semasa sesi mengundi.'
            ]);
        }

        return $next($request);
    }

    private function isElection($request)
    {
        return
            !$request->isMethod('get')
            && Util::getElectionStatus() == 2
            && !$request->is('api/v1/election/*')
            // Allow paperless allowance flows during election (cash counter needs this)
            && !$request->is('api/v1/allowance/*')
            // Allow admin to update voter info during election (edit screen uses PUT /api/v1/voter/{id})
            && !($request->is('api/v1/voter/*') && $request->isMethod('put'))
            // Allow admin to add voter during election (manual add uses POST /api/v1/voter)
            && !($request->is('api/v1/voter') && $request->isMethod('post'))
            // Allow updating applicable voters list during election (add page uses POST /api/v1/voter/sync-applicable)
            && !($request->is('api/v1/voter/sync-applicable') && $request->isMethod('post'))
            && !$request->is('api/v1/voter/*/verify-fizikal-registration')
            // Pentadbir utama: urus akaun (tambah/kemaskini/padam) semasa mengundi
            && !$request->is('api/v1/admin')
            && !$request->is('api/v1/admin/*');
    }
}
