<?php

namespace App\Http\Controllers;

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

class EmployeeAdvanceController extends Controller
{
    protected string $module = 'Employee Advances';

    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()
    {
        $advances  = EmployeeAdvance::with('employee')->latest()->paginate(20);
        $employees = Employees::where('status','active')->orderBy('first_name')->get();
        return view('advances.index', compact('advances','employees'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'employee_id'       => 'required|exists:employees,id',
            'amount'            => 'required|numeric|min:1',
            'monthly_deduction' => 'required|numeric|min:0',
            'given_date'        => 'required|date',
            'notes'             => 'nullable|string',
        ]);

        EmployeeAdvance::create($data);
        return back()->with('success','Advance added successfully.');
    }

    public function update(Request $request, EmployeeAdvance $advance)
    {
        $data = $request->validate([
            'amount'            => 'required|numeric|min:1',
            'recovered'         => 'required|numeric|min:0',
            'monthly_deduction' => 'required|numeric|min:0',
            'given_date'        => 'required|date',
            'status'            => 'required|in:active,recovered,cancelled',
            'notes'             => 'nullable|string',
        ]);

        $advance->update($data);
        return back()->with('success','Advance updated.');
    }

    public function destroy(EmployeeAdvance $advance)
    {
        $advance->delete();
        return back()->with('success','Advance deleted.');
    }
}