<?php

namespace App\Http\Controllers;

use App\Exceptions\BalaghatException;
use App\Http\Traits\Api_Trait;
use App\Models\Employee;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class EmployeeController extends Controller
{
    use Api_Trait;
    public function index(Request $request)
    {
        $perPage = 10;
        $employees = Employee::paginate($perPage);
        return $this->paginatedResponse($employees, __('messages.employees'), 200);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string',
            'email' => 'required|email|unique:employees,email',
            'password' => 'nullable|string|min:6',
            'is_admin' => 'required|boolean',
        ]);

        $data['password'] = Hash::make($data['password'] ?? '123456');

        $employee = Employee::create($data);

        return response()->json([
            'message' => __('messages.employee_created'),
            'data' => $employee
        ], 201);
    }

    public function show(Employee $employee)
    {
        return $employee;
    }

    public function update(Request $request, Employee $employee)
    {
        $data = $request->validate([
            'name' => 'required|string',
            'email' => 'required|email|unique:employees,email,' . $employee->id,
            'password' => 'nullable|string|min:6',
            'is_admin' => 'required|boolean',
        ]);

        if (!empty($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        } else {
            unset($data['password']);
        }

        $employee->update($data);

        return response()->json([
            'message' => __('messages.employee_updated'),
            'data' => $employee
        ]);
    }

    public function destroy(Employee $employee)
    {
        $employee->delete();

        return response()->json([
            'message' => __('messages.employee_deleted')
        ]);
    }
}
