<?php

namespace App\Http\Controllers\Admin\HR;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\Department;
use App\Models\Designation;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;

class EmployeeController extends Controller
{
    public function index()
    {
        $employees = Employee::with(['department', 'designation', 'reportingManager'])
            ->paginate(15);

        return view('admin.hr.employees.index', compact('employees'));
    }

    public function create()
    {
        $departments = Department::where('is_active', true)->get();
        $designations = Designation::where('is_active', true)->get();
        $managers = User::all();

        return view('admin.hr.employees.create', compact('departments', 'designations', 'managers'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'full_name' => 'required|string|max:255',
            'full_name_ar' => 'nullable|string|max:255',
            'photo' => 'nullable|image|max:2048',
            'nationality' => 'required|string|max:255',
            'gender' => 'required|in:male,female',
            'date_of_birth' => 'required|date',
            'marital_status' => 'required|in:single,married,divorced,widowed',
            'email' => 'nullable|email|unique:employees,email',
            'phone' => 'required|string|max:20',
            'phone_2' => 'nullable|string|max:20',
            'address' => 'nullable|string',
            'emergency_contact_name' => 'nullable|string|max:255',
            'emergency_contact_phone' => 'nullable|string|max:20',
            'emergency_contact_relationship' => 'nullable|string|max:255',
            'department_id' => 'nullable|exists:departments,id',
            'designation_id' => 'nullable|exists:designations,id',
            'reporting_manager_id' => 'nullable|exists:users,id',
            'employment_type' => 'required|in:full-time,part-time,contract,driver,technician',
            'joining_date' => 'required|date',
            'probation_period_days' => 'nullable|integer|min:0',
            'confirmation_date' => 'nullable|date',
            'status' => 'required|in:active,on_leave,suspended,terminated',
        ]);

        $validated['employee_id'] = Employee::generateEmployeeId();

        if ($request->hasFile('photo')) {
            $validated['photo'] = $request->file('photo')->store('employees/photos', 'public');
        }

        Employee::create($validated);

        return redirect()->route('admin.hr.employees.index')
            ->with('success', 'Employee created successfully.');
    }

    public function show(Employee $employee)
    {
        $employee->load(['department', 'designation', 'reportingManager', 'documents', 'currentSalary']);

        return view('admin.hr.employees.show', compact('employee'));
    }

    public function edit(Employee $employee)
    {
        $departments = Department::where('is_active', true)->get();
        $designations = Designation::where('is_active', true)->get();
        $managers = User::all();

        return view('admin.hr.employees.edit', compact('employee', 'departments', 'designations', 'managers'));
    }

    public function update(Request $request, Employee $employee)
    {
        $validated = $request->validate([
            'full_name' => 'required|string|max:255',
            'full_name_ar' => 'nullable|string|max:255',
            'photo' => 'nullable|image|max:2048',
            'nationality' => 'required|string|max:255',
            'gender' => 'required|in:male,female',
            'date_of_birth' => 'required|date',
            'marital_status' => 'required|in:single,married,divorced,widowed',
            'email' => 'nullable|email|unique:employees,email,' . $employee->id,
            'phone' => 'required|string|max:20',
            'phone_2' => 'nullable|string|max:20',
            'address' => 'nullable|string',
            'emergency_contact_name' => 'nullable|string|max:255',
            'emergency_contact_phone' => 'nullable|string|max:20',
            'emergency_contact_relationship' => 'nullable|string|max:255',
            'department_id' => 'nullable|exists:departments,id',
            'designation_id' => 'nullable|exists:designations,id',
            'reporting_manager_id' => 'nullable|exists:users,id',
            'employment_type' => 'required|in:full-time,part-time,contract,driver,technician',
            'joining_date' => 'required|date',
            'probation_period_days' => 'nullable|integer|min:0',
            'confirmation_date' => 'nullable|date',
            'status' => 'required|in:active,on_leave,suspended,terminated',
            'termination_date' => 'nullable|date',
            'termination_reason' => 'nullable|string',
        ]);

        if ($request->hasFile('photo')) {
            if ($employee->photo) {
                Storage::disk('public')->delete($employee->photo);
            }
            $validated['photo'] = $request->file('photo')->store('employees/photos', 'public');
        }

        $employee->update($validated);

        return redirect()->route('admin.hr.employees.index')
            ->with('success', 'Employee updated successfully.');
    }

    public function destroy(Employee $employee)
    {
        if ($employee->photo) {
            Storage::disk('public')->delete($employee->photo);
        }

        $employee->delete();

        return redirect()->route('admin.hr.employees.index')
            ->with('success', 'Employee deleted successfully.');
    }

    public function createUserForm(Employee $employee)
    {
        if ($employee->user_id) {
            return redirect()->route('admin.hr.employees.show', $employee)
                ->with('error', 'This employee already has a user account.');
        }

        if (!$employee->email) {
            return redirect()->route('admin.hr.employees.show', $employee)
                ->with('error', 'Employee must have an email address to create a user account.');
        }

        $roles = Role::all();

        return view('admin.hr.employees.create-user', compact('employee', 'roles'));
    }

    public function createUser(Request $request, Employee $employee)
    {
        if ($employee->user_id) {
            return redirect()->route('admin.hr.employees.show', $employee)
                ->with('error', 'This employee already has a user account.');
        }

        if (!$employee->email) {
            return redirect()->route('admin.hr.employees.show', $employee)
                ->with('error', 'Employee must have an email address to create a user account.');
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:8|confirmed',
            'role' => 'required|exists:roles,name',
        ]);

        $user = User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
        ]);

        $user->assignRole($validated['role']);

        $employee->update(['user_id' => $user->id]);

        return redirect()->route('admin.hr.employees.show', $employee)
            ->with('success', 'User account created successfully. Login credentials: Email: ' . $user->email . ', Password: (as set)');
    }
}
