<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class BlockDismissedEmployeeTransactions
{
    public function handle(Request $request, Closure $next)
    {
        // Check if trying to add deduction
        if ($request->route()->getName() === 'deductions.store' && $request->has('employee_id')) {
            $employee = Employee::find($request->employee_id);
            if ($employee && $employee->is_dismissed) {
                return redirect()->back()->with('error', 
                    'Cannot add deductions to a dismissed employee.');
            }
        }
        
        // Check if trying to schedule payment
        if ($request->route()->getName() === 'payments.schedule' && $request->has('employee_id')) {
            $employee = Employee::find($request->employee_id);
            if ($employee && $employee->is_dismissed) {
                return redirect()->back()->with('error', 
                    'Cannot schedule payments for a dismissed employee.');
            }
        }
        
        // Check if trying to assign to station
        if ($request->route()->getName() === 'stations.assign' && $request->has('employee_id')) {
            $employee = Employee::find($request->employee_id);
            if ($employee && $employee->is_dismissed) {
                return redirect()->back()->with('error', 
                    'Cannot assign a dismissed employee to a station.');
            }
        }
        
        return $next($request);
    }
}