<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employee;
use App\Models\User;
use App\Models\Department;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;

class EmployeeController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('role:super_admin,hr_admin')->except(['show', 'editProfile', 'updateProfile']);
    }

    public function index(Request $request)
    {
        $query = Employee::with(['user', 'department']);

        if ($request->department_id) {
            $query->where('department_id', $request->department_id);
        }
        if ($request->status) {
            $query->where('status', $request->status);
        }
        if ($request->search) {
            $s = $request->search;
            $query->where(fn($q) =>
                $q->where('first_name', 'like', "%$s%")
                  ->orWhere('last_name', 'like', "%$s%")
                  ->orWhere('employee_number', 'like', "%$s%")
                  ->orWhere('position', 'like', "%$s%")
            );
        }
        if ($request->employment_type) {
            $query->where('employment_type', $request->employment_type);
        }

        $employees   = $query->latest()->paginate(15)->withQueryString();
        $departments = Department::where('is_active', true)->orderBy('name')->get();

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

    public function create()
    {
        $departments = Department::where('is_active', true)->orderBy('name')->get();
        return view('employees.create', compact('departments'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'first_name'        => 'required|string|max:100',
            'last_name'         => 'required|string|max:100',
            'email'             => 'required|email|unique:users,email',
            'position'          => 'required|string|max:200',
            'department_id'     => 'required|exists:departments,id',
            'date_of_employment'=> 'required|date',
            'employment_type'   => 'required|in:full_time,part_time,contract,temporary',
            'salary_usd'        => 'nullable|numeric|min:0',
        ]);

        DB::transaction(function () use ($request) {
            $employeeNumber = 'UL-' . date('Y') . '-' . str_pad(
                Employee::whereYear('created_at', date('Y'))->count() + 1, 4, '0', STR_PAD_LEFT
            );

            $user = User::create([
                'name'            => $request->first_name . ' ' . $request->last_name,
                'email'           => $request->email,
                'password'        => Hash::make($request->input('password', 'password123')),
                'role'            => $request->input('role', 'employee'),
                'employee_number' => $employeeNumber,  // plain string, not a FK
                'phone'           => $request->phone,
            ]);

            $employee = Employee::create(array_merge(
                $request->except(['email', 'password', 'role', '_token']),
                ['user_id' => $user->id, 'employee_number' => $employeeNumber]
            ));

            // Save education records
            if ($request->has('education')) {
                foreach ($request->education as $edu) {
                    if (!empty($edu['institution_name'])) {
                        $employee->education()->create($edu);
                    }
                }
            }

            // Save employment history
            if ($request->has('employment_history')) {
                foreach ($request->employment_history as $hist) {
                    if (!empty($hist['employer_name'])) {
                        $employee->employmentHistory()->create($hist);
                    }
                }
            }

            // Save references
            if ($request->has('references')) {
                foreach ($request->references as $ref) {
                    if (!empty($ref['name'])) {
                        $employee->references()->create($ref);
                    }
                }
            }
        });

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

    public function show(Employee $employee)
    {
        $employee->load([
            'user', 'department', 'education', 'employmentHistory',
            'references', 'documents', 'leaves.leaveType',
            'evaluations.period', 'disciplineRecords', 'trainings',
        ]);

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

    public function edit(Employee $employee)
    {
        $departments = Department::where('is_active', true)->orderBy('name')->get();
        $employee->load(['education', 'employmentHistory', 'references']);
        return view('employees.edit', compact('employee', 'departments'));
    }

    public function update(Request $request, Employee $employee)
    {
        $request->validate([
            'first_name'    => 'required|string|max:100',
            'last_name'     => 'required|string|max:100',
            'department_id' => 'required|exists:departments,id',
            'position'      => 'required|string|max:200',
        ]);

        DB::transaction(function () use ($request, $employee) {
            $employee->update($request->except(['email', 'password', '_token', '_method', 'education', 'employment_history', 'references']));

            // Update user — department is stored on the employee record, not on users
            $employee->user->update([
                'name'  => $request->first_name . ' ' . $request->last_name,
                'phone' => $request->phone,
            ]);

            if ($request->email && $request->email !== $employee->user->email) {
                $employee->user->update(['email' => $request->email]);
            }
        });

        return redirect()->route('employees.show', $employee)
            ->with('success', 'Employee record updated successfully.');
    }

    public function destroy(Employee $employee)
    {
        DB::transaction(function () use ($employee) {
            $employee->update(['status' => 'terminated']);
            $employee->delete();
            $employee->user->update(['is_active' => false]);
            $employee->user->delete();
        });

        return redirect()->route('employees.index')
            ->with('success', 'Employee record deactivated successfully.');
    }

    public function editProfile()
    {
        $employee = auth()->user()->employee;
        if (!$employee) {
            return redirect()->route('dashboard')->with('error', 'Profile not set up.');
        }
        $departments = Department::where('is_active', true)->orderBy('name')->get();
        return view('employees.profile', compact('employee', 'departments'));
    }

    public function updateProfile(Request $request)
    {
        $employee = auth()->user()->employee;
        $request->validate([
            'present_address' => 'nullable|string|max:500',
            'phone'           => 'nullable|string|max:30',
        ]);

        $employee->update($request->only([
            'present_address', 'permanent_address', 'phone',
            'emergency_contact_name', 'emergency_contact_phone', 'emergency_contact_relation',
            'special_skills', 'professional_memberships',
        ]));

        if ($request->phone) {
            $employee->user->update(['phone' => $request->phone]);
        }

        return redirect()->route('profile')->with('success', 'Profile updated successfully.');
    }

    public function uploadDocument(Request $request, Employee $employee)
    {
        $request->validate([
            'document_type' => 'required|string',
            'document_name' => 'required|string',
            'file'          => 'required|file|max:10240',
        ]);

        $path = $request->file('file')->store("employee_documents/{$employee->id}", 'local');

        $employee->documents()->create([
            'document_type' => $request->document_type,
            'document_name' => $request->document_name,
            'file_path'     => $path,
            'file_size'     => $request->file('file')->getSize(),
            'expiry_date'   => $request->expiry_date,
        ]);

        return back()->with('success', 'Document uploaded successfully.');
    }
}
