<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\EmployeeLog;
use Illuminate\Http\Request;

class EmployeeLogController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        if (!$user->company_id) return response()->json(['message' => 'No company'], 403);

        $query = EmployeeLog::where('company_id', $user->company_id)
            ->with('employee:id,name,position');

        if ($request->filled('employee_id')) $query->where('employee_id', $request->employee_id);
        if ($request->filled('log_type')) $query->where('log_type', $request->log_type);

        return response()->json(['data' => $query->latest()->get()]);
    }

    public function store(Request $request)
    {
        $user = $request->user();
        if (!$user->company_id) return response()->json(['message' => 'No company'], 403);

        $validated = $request->validate([
            'employee_id' => 'required|exists:employees,id',
            'log_type' => 'required|string',
            'amount_change' => 'nullable|numeric',
            'effective_date' => 'required|date',
            'end_date' => 'nullable|date|after_or_equal:effective_date',
            'description' => 'nullable|string',
            'notes' => 'nullable|string',
        ]);

        $validated['company_id'] = $user->company_id;
        $validated['created_by'] = $user->id;
        $validated['status'] = 'completed';

        $log = EmployeeLog::create($validated);
        return response()->json(['data' => $log, 'message' => 'Log added'], 201);
    }

    public function destroy(Request $request, $id)
    {
        $user = $request->user();
        $log = EmployeeLog::where('company_id', $user->company_id)->findOrFail($id);
        $log->delete();
        return response()->json(['message' => 'Log deleted']);
    }
}
