<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class EmployeeController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();

        $query = Employee::with(['company', 'department', 'user']);

        if (!$user->isSuperAdmin()) {
            $query->forCompany($user->company_id);
        }

        $employees = $query->when($request->company_id, function ($q) use ($request) {
            $q->where('company_id', $request->company_id);
        })
        ->when($request->department_id, function ($q) use ($request) {
            $q->where('department_id', $request->department_id);
        })
        ->when($request->search, function ($q) use ($request) {
            $q->where(function($query) use ($request) {
                $query->where('first_name', 'like', "%{$request->search}%")
                      ->orWhere('last_name', 'like', "%{$request->search}%")
                      ->orWhere('email', 'like', "%{$request->search}%")
                      ->orWhere('employee_id', 'like', "%{$request->search}%");
            });
        })
        ->when($request->status, function ($q) use ($request) {
            $q->where('status', $request->status);
        })
        ->when($request->employment_type, function ($q) use ($request) {
            $q->where('employment_type', $request->employment_type);
        })
        ->orderBy($request->get('sort_by', 'created_at'), $request->get('sort_order', 'desc'))
        ->paginate($request->get('per_page', 15));

        return response()->json($employees);
    }

    public function store(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'company_id'              => 'nullable|exists:companies,id',
            'department_id'           => 'nullable|exists:departments,id',
            'first_name'              => 'required|string|max:255',
            'last_name'               => 'required|string|max:255',
            'email'                   => 'required|email|unique:employees,email',
            'phone'                   => 'nullable|string|max:20',
            'position'                => 'required|string|max:255',
            'date_of_birth'           => 'nullable|date',
            'hire_date'               => 'nullable|date',
            'employment_type'         => 'nullable|string|max:50',
            'salary'                  => 'nullable|numeric|min:0',
            'status'                  => 'nullable|in:active,on-leave,terminated,resigned',
            'address'                 => 'nullable|string',
            'city'                    => 'nullable|string|max:255',
            'state'                   => 'nullable|string|max:255',
            'country'                 => 'nullable|string|max:255',
            'emergency_contact_name'  => 'nullable|string|max:255',
            'emergency_contact_phone' => 'nullable|string|max:20',
            'avatar'                  => 'nullable|image|max:2048',
        ]);

        // Auto-assign company from user if not provided
        $companyId = $request->company_id ?? $user->company_id;
        if (!$companyId) {
            return response()->json(['message' => 'No company associated with this account'], 403);
        }
        if (!$user->isSuperAdmin() && !$user->canAccessCompany($companyId)) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }
        $request->merge(['company_id' => $companyId]);

        $data = $request->except('avatar');

        if (isset($data['employment_type'])) {
            $data['employment_type'] = str_replace('_', '-', $data['employment_type']);
        }

        if ($request->hasFile('avatar')) {
            $data['avatar'] = $request->file('avatar')->store('avatars', 'public');
        }

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

        activity()
            ->performedOn($employee)
            ->log('Employee created');

        return response()->json([
            'employee' => $employee->load(['company', 'department']),
            'message' => 'Employee created successfully',
        ], 201);
    }

    public function show($id, Request $request)
    {
        $user = $request->user();

        $employee = Employee::with(['company', 'department', 'user'])
            ->findOrFail($id);

        if (!$user->canAccessCompany($employee->company_id)) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        return response()->json($employee);
    }

    public function update(Request $request, $id)
    {
        $user = $request->user();

        $employee = Employee::findOrFail($id);

        if (!$user->canAccessCompany($employee->company_id)) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $request->validate([
            'department_id' => 'sometimes|nullable|exists:departments,id',
            'first_name' => 'sometimes|string|max:255',
            'last_name' => 'sometimes|string|max:255',
            'email' => 'sometimes|email|unique:employees,email,' . $id,
            'phone' => 'sometimes|nullable|string|max:20',
            'position' => 'sometimes|string|max:255',
            'date_of_birth' => 'sometimes|nullable|date',
            'hire_date' => 'sometimes|date',
            'employment_type' => 'sometimes|nullable|string|max:50',
            'salary' => 'sometimes|nullable|numeric|min:0',
            'status' => 'sometimes|in:active,on-leave,terminated,resigned',
            'address' => 'sometimes|nullable|string',
            'city' => 'sometimes|nullable|string|max:255',
            'state' => 'sometimes|nullable|string|max:255',
            'country' => 'sometimes|nullable|string|max:255',
            'emergency_contact_name' => 'sometimes|nullable|string|max:255',
            'emergency_contact_phone' => 'sometimes|nullable|string|max:20',
            'avatar' => 'sometimes|nullable|image|max:2048',
        ]);

        $data = $request->except('avatar');

        if (isset($data['employment_type'])) {
            $data['employment_type'] = str_replace('_', '-', $data['employment_type']);
        }

        if ($request->hasFile('avatar')) {
            if ($employee->avatar) {
                Storage::disk('public')->delete($employee->avatar);
            }
            $data['avatar'] = $request->file('avatar')->store('avatars', 'public');
        }

        $employee->update($data);

        activity()
            ->performedOn($employee)
            ->log('Employee updated');

        return response()->json([
            'employee' => $employee->fresh(['company', 'department']),
            'message' => 'Employee updated successfully',
        ]);
    }

    public function destroy($id, Request $request)
    {
        $user = $request->user();

        $employee = Employee::findOrFail($id);

        if (!$user->canAccessCompany($employee->company_id)) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        if ($employee->avatar) {
            Storage::disk('public')->delete($employee->avatar);
        }

        $employee->delete();

        activity()
            ->performedOn($employee)
            ->log('Employee deleted');

        return response()->json(['message' => 'Employee deleted successfully']);
    }

    public function bulkImport(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'company_id' => 'required|exists:companies,id',
            'employees' => 'required|array',
            'employees.*.first_name' => 'required|string|max:255',
            'employees.*.last_name' => 'required|string|max:255',
            'employees.*.email' => 'required|email|unique:employees,email',
            'employees.*.position' => 'required|string|max:255',
            'employees.*.hire_date' => 'required|date',
            'employees.*.employment_type' => 'required|in:full-time,part-time,contract,intern',
        ]);

        if (!$user->canAccessCompany($request->company_id)) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $createdEmployees = [];

        foreach ($request->employees as $employeeData) {
            $employeeData['company_id'] = $request->company_id;
            $employee = Employee::create($employeeData);
            $createdEmployees[] = $employee;
        }

        return response()->json([
            'employees' => $createdEmployees,
            'message' => count($createdEmployees) . ' employees imported successfully',
        ], 201);
    }
}
