<?php

namespace App\Http\Controllers\Api;

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

class EmployeeController extends Controller
{
    public function index(Request $request)
    {
        return Employee::where('tenant_id', $request->user()->tenant_id)->latest()->paginate(25);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'employee_code' => ['required', 'string'],
            'name' => ['required', 'string'],
            'email' => ['nullable', 'email'],
            'phone' => ['nullable', 'string'],
            'branch_id' => ['nullable', 'integer'],
            'department_id' => ['nullable', 'integer'],
            'designation_id' => ['nullable', 'integer'],
            'salary_info' => ['array'],
        ]);

        $data['tenant_id'] = $request->user()->tenant_id;
        $data['employment_status'] = 'active';

        return Employee::create($data);
    }

    public function show(Request $request, Employee $employee)
    {
        abort_unless($employee->tenant_id === $request->user()->tenant_id, 404);

        return $employee;
    }

    public function update(Request $request, Employee $employee)
    {
        abort_unless($employee->tenant_id === $request->user()->tenant_id, 404);
        $employee->update($request->all());

        return $employee->fresh();
    }

    public function destroy(Request $request, Employee $employee)
    {
        abort_unless($employee->tenant_id === $request->user()->tenant_id, 404);
        $employee->update(['employment_status' => 'inactive']);

        return response()->noContent();
    }
}
