<?php

namespace App\Http\Controllers;

use App\Models\EquityAward;
use App\Models\JobGrade;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class EquityAwardController extends Controller
{
    public function index()
    {
        $organisationId = Auth::user()->organisation_id ?? null;
        $awards = EquityAward::where('organisation_id', $organisationId)->get();

        return view('equity_awards.index', compact('awards'));
    }

    public function create()
    {
        $jobGrades = JobGrade::pluck('name', 'id');
        return view('equity_awards.create', compact('jobGrades'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'job_grade_id' => 'required|exists:job_grades,id',
            'award_type' => 'required|string',
            'performance_rating' => 'nullable|string',
            'equity_type' => 'required|string',
            'value_type' => 'required|string|in:fixed,percentage',
            'value_amount' => 'required|numeric|min:0',
            'vesting_months' => 'nullable|integer|min:0',
        ]);

        $data = $request->all();
        $data['organisation_id'] = Auth::user()->organisation_id;

        EquityAward::create($data);

        return redirect()->back()->with('success', __('Equity award created successfully.'));
    }

    public function edit(EquityAward $equityAward)
    {
        $jobGrades = JobGrade::pluck('name', 'id');
        return view('equity_awards.edit', [
            'award' => $equityAward,
            'jobGrades' => $jobGrades,
        ]);
    }

    public function update(Request $request, EquityAward $equityAward)
    {
        $request->validate([
            'job_grade_id' => 'required|exists:job_grades,id',
            'award_type' => 'required|string',
            'performance_rating' => 'nullable|string',
            'equity_type' => 'required|string',
            'value_type' => 'required|string|in:fixed,percentage',
            'value_amount' => 'required|numeric|min:0',
            'vesting_months' => 'nullable|integer|min:0',
        ]);

        $equityAward->update($request->all());

        return redirect()->back()->with('success', __('Equity award updated successfully.'));
    }

    public function destroy(EquityAward $equityAward)
    {
        $equityAward->delete();
        return redirect()->back()->with('success', __('Equity award deleted successfully.'));
    }
}
