<?php

namespace App\Http\Controllers;

use App\Models\Currency;
use App\Models\Employee;
use App\Models\EmployeePayment;
use Illuminate\Http\Request;

class EmployeePaymentController extends Controller
{
    public function index()
    {
        $payments = EmployeePayment::with('employee')->latest()->paginate(15);

        return view('employee_payments.index', compact('payments'));
    }

    public function create()
    {
        $employees = Employee::active()->get();
        $currencies = Currency::all();

        return view('employee_payments.create', compact('employees', 'currencies'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'employee_id' => ['required', 'exists:employees,id'],
            'payment_date' => ['required', 'date'],
            'amount' => ['required', 'numeric', 'min:0'],
            'payment_type' => ['required', 'in:salary,advance,adjustment'],
            'period' => ['required', 'in:daily,weekly,monthly'],
            'notes' => ['nullable', 'string'],
        ]);

        $payment = EmployeePayment::create($data);

        if ($payment->payment_type === 'advance') {
            $employee = $payment->employee;
            $employee->advance_amount += $payment->amount;
            $employee->save();
        }

        return redirect()->route('employee-payments.index')->with('success', __('Employee payment recorded.'));
    }

    public function destroy(EmployeePayment $employeePayment)
    {
        $employeePayment->delete();

        return redirect()->route('employee-payments.index')->with('success', __('Payment record removed.'));
    }
}
