<?php

namespace App\Http\Controllers;

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

class EmployeeLoanController extends Controller
{
    protected string $module = 'Employee Loans';

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

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

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

    public function update(Request $request, EmployeeLoan $loan)
    {
        $data = $request->validate([
            'total_amount'       => 'required|numeric|min:1',
            'paid_amount'        => 'required|numeric|min:0',
            'monthly_deduction'  => 'required|numeric|min:0',
            'start_date'         => 'required|date',
            'end_date'           => 'nullable|date',
            'status'             => 'required|in:active,completed,cancelled',
            'notes'              => 'nullable|string',
        ]);

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

    public function destroy(EmployeeLoan $loan)
    {
        $loan->delete();
        return back()->with('success','Loan deleted.');
    }
}