<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class EmployeeController extends Controller
{
    public function index(): JsonResponse
    {
        return response()->json([
            'data' => DB::table('employees')->where('tenant_id', app('tenant.id'))->latest('id')->paginate(25),
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'branch_id' => ['required', 'integer'],
            'department_id' => ['nullable', 'integer'],
            'designation_id' => ['nullable', 'integer'],
            'manager_id' => ['nullable', 'integer'],
            'employee_code' => ['required', 'string', 'max:80'],
            'name' => ['required', 'string', 'max:180'],
            'email' => ['nullable', 'email', 'max:180'],
            'phone' => ['nullable', 'string', 'max:60'],
            'salary_type' => ['required', 'in:monthly,daily,hourly'],
            'basic_salary' => ['required', 'numeric', 'min:0'],
        ]);

        $id = DB::table('employees')->insertGetId($data + [
            'tenant_id' => app('tenant.id'),
            'employment_status' => 'active',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return response()->json(['data' => DB::table('employees')->find($id)], 201);
    }

    public function show(int $employee): JsonResponse
    {
        return response()->json(['data' => DB::table('employees')->where('tenant_id', app('tenant.id'))->find($employee)]);
    }

    public function update(Request $request, int $employee): JsonResponse
    {
        DB::table('employees')
            ->where('tenant_id', app('tenant.id'))
            ->where('id', $employee)
            ->update($request->all() + ['updated_at' => now()]);

        return $this->show($employee);
    }

    public function destroy(int $employee): JsonResponse
    {
        DB::table('employees')
            ->where('tenant_id', app('tenant.id'))
            ->where('id', $employee)
            ->update(['employment_status' => 'inactive', 'updated_at' => now()]);

        return response()->json(status: 204);
    }

    public function transfer(Request $request, int $employee): JsonResponse
    {
        $data = $request->validate([
            'branch_id' => ['nullable', 'integer'],
            'department_id' => ['nullable', 'integer'],
            'designation_id' => ['nullable', 'integer'],
        ]);

        DB::table('employees')
            ->where('tenant_id', app('tenant.id'))
            ->where('id', $employee)
            ->update($data + ['updated_at' => now()]);

        return response()->json(['status' => 'transferred']);
    }
}
