<?php

namespace App\Http\Controllers\Admin\Hr;

use App\Http\Controllers\Controller;
use App\Models\Hr\EmployeeProfile;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class EmployeeProfileController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = EmployeeProfile::query()->with('user');
        $query->when($request->user_id, fn($q, $v) => $q->where('user_id', $v));
        $query->when($request->has('status'), fn($q) => $q->where('status', $request->status));

        return $this->paginate($query->latest()->paginate($request->input('per_page', 15)));
    }

    public function store(Request $request): JsonResponse
    {
        $v = $request->validate([
            'user_id' => 'required|exists:users,id',
            'employee_no' => 'nullable|string|max:30',
            'hire_date' => 'nullable|date',
            'birth_date' => 'nullable|date',
            'gender' => 'nullable|integer|in:0,1,2',
            'id_card' => 'nullable|string|max:20',
            'education' => 'nullable|string|max:30',
            'emergency_contact' => 'nullable|string|max:50',
            'emergency_phone' => 'nullable|string|max:20',
            'base_salary' => 'nullable|numeric|min:0',
            'position_salary' => 'nullable|numeric|min:0',
            'status' => 'nullable|integer|in:1,2,3',
        ]);

        return $this->success(EmployeeProfile::create($v));
    }

    public function show(EmployeeProfile $employeeProfile): JsonResponse
    {
        return $this->success($employeeProfile->load('user'));
    }

    public function update(Request $request, EmployeeProfile $employeeProfile): JsonResponse
    {
        $v = $request->validate([
            'employee_no' => 'nullable|string|max:30',
            'hire_date' => 'nullable|date',
            'birth_date' => 'nullable|date',
            'gender' => 'nullable|integer|in:0,1,2',
            'id_card' => 'nullable|string|max:20',
            'education' => 'nullable|string|max:30',
            'emergency_contact' => 'nullable|string|max:50',
            'emergency_phone' => 'nullable|string|max:20',
            'base_salary' => 'nullable|numeric|min:0',
            'position_salary' => 'nullable|numeric|min:0',
            'status' => 'nullable|integer|in:1,2,3',
            'left_date' => 'nullable|date',
        ]);
        $employeeProfile->update($v);

        return $this->success($employeeProfile);
    }

    public function destroy(EmployeeProfile $employeeProfile): JsonResponse
    {
        $employeeProfile->delete();
        return $this->success(null);
    }
}
