<?php

namespace App\Http\Controllers;

use App\Models\FinalRatingAction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class FinalRatingActionController extends Controller
{
    public function index()
    {
        $actions = FinalRatingAction::where('organisation_id', Auth::user()->organisation_id)->get();
        return view('final_rating_actions.index', compact('actions'));
    }

    public function create()
    {
        return view('final_rating_actions.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'min_score' => 'required|numeric|between:0,100',
            'max_score' => 'required|numeric|gt:min_score|between:0,100',
            'action_type' => 'required',
            'merit_percent' => 'nullable|string',
            'bonus_multiplier' => 'nullable|string',
            'extra_notes' => 'nullable|string',

        ]);

        FinalRatingAction::create([
            'organisation_id' => Auth::user()->organisation_id,
            'min_score' => $request->min_score,
            'max_score' => $request->max_score,
            'action_type' => $request->action_type,
            'extra_notes' => $request->extra_notes,
            'merit_percent' => $request->merit_percent,
            'bonus_multiplier' => $request->bonus_multiplier,
        ]);

        return redirect()->route('final-rating-actions.index')->with('success', __('Final rating action created successfully.'));
    }

    public function edit(FinalRatingAction $finalRatingAction)
    {
        return view('final_rating_actions.create', ['action' => $finalRatingAction]);
    }

    public function update(Request $request, FinalRatingAction $finalRatingAction)
    {
        $request->validate([
            'min_score' => 'required|numeric|between:0,100',
            'max_score' => 'required|numeric|gt:min_score|between:0,100',
            'action_type' => 'required',
            'extra_notes' => 'nullable|string',
            'merit_percent' => 'nullable|integer',
            'bonus_multiplier' => 'nullable|string',
            'notes' => 'nullable|string'
        ]);

        $finalRatingAction->update([
            'min_score' => $request->min_score,
            'max_score' => $request->max_score,
            'action_type' => $request->action_type,
            'merit_percent' => $request->merit_percent,
            'bonus_multiplier' => $request->bonus_multiplier,
            'extra_notes' => $request->extra_notes
        ]);

        return redirect()->route('final-rating-actions.index')->with('success', __('Final rating action updated successfully.'));
    }

    public function destroy(FinalRatingAction $finalRatingAction)
    {
        $finalRatingAction->delete();

        return redirect()->route('final-rating-actions.index')->with('success', __('Final rating action deleted successfully.'));
    }
}
