<?php

namespace App\Http\Controllers;

use App\Employees;
use App\EmployeeOvertime;
use Illuminate\Http\Request;

class EmployeeOvertimeController extends Controller
{
    protected string $module = 'Employee Overtimes';

    public function __construct()
    {
        $module = $this->module;

        $this->middleware("permission:$module list")->only(['index']);
        $this->middleware("permission:$module view")->only(['show']);
        $this->middleware("permission:$module add")->only(['create', 'store']);
        $this->middleware("permission:$module edit")->only(['edit', 'update']);
        $this->middleware("permission:$module delete")->only(['destroy']);
    }
    public function index()
    {
        $overtimes = EmployeeOvertime::with('employee')->orderByDesc('year')->orderByDesc('month')->paginate(20);
        $employees = Employees::where('status','active')->orderBy('first_name')->get();
        return view('overtimes.index', compact('overtimes','employees'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'employee_id'    => 'required|exists:employees,id',
            'year'           => 'required|integer|min:2000|max:2099',
            'month'          => 'required|integer|min:1|max:12',
            'ot_hours'       => 'required|numeric|min:0',
            'ot_multiplier'  => 'required|numeric|min:1',
            'notes'          => 'nullable|string',
        ]);

        // Upsert — one record per employee per month
        $ot = EmployeeOvertime::firstOrNew([
            'employee_id' => $data['employee_id'],
            'year'        => $data['year'],
            'month'       => $data['month'],
        ]);

        $ot->fill($data)->save();   // booted() computes ot_amount

        return back()->with('success', 'OT saved. Amount: ' . number_format($ot->ot_amount, 0));
    }

    public function update(Request $request, EmployeeOvertime $overtime)
    {
        $data = $request->validate([
            'ot_hours'      => 'required|numeric|min:0',
            'ot_multiplier' => 'required|numeric|min:1',
            'notes'         => 'nullable|string',
        ]);

        $overtime->fill($data)->save();
        return back()->with('success', 'OT updated. Amount: ' . number_format($overtime->ot_amount, 0));
    }

    public function destroy(EmployeeOvertime $overtime)
    {
        $overtime->delete();
        return back()->with('success','OT record deleted.');
    }
}