<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\Employee;
use Illuminate\Http\Request;

class EmployeeController extends Controller
{
    public function index(Request $request)
    {
        $query = Employee::withCount('faceTemplates')->orderBy('emp_id');

        if ($search = $request->query('q')) {
            $query->where(function ($q) use ($search) {
                $q->where('emp_id', 'like', "%{$search}%")->orWhere('name', 'like', "%{$search}%");
            });
        }

        $employees = $query->paginate(20)->withQueryString();

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

    public function create()
    {
        return view('employees.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'emp_id' => 'required|string|unique:employees,emp_id',
            'name' => 'required|string',
            'consent_on' => 'nullable|date',
        ]);
        $data['active'] = $request->boolean('active', true);

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

        AuditLog::record($request->user()->id, 'employee.create', 'Employee', $employee->id, null, $employee->toArray());

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

    public function edit(Employee $employee)
    {
        return view('employees.edit', compact('employee'));
    }

    public function update(Request $request, Employee $employee)
    {
        $data = $request->validate([
            'name' => 'required|string',
            'consent_on' => 'nullable|date',
        ]);
        $data['active'] = $request->boolean('active');

        $before = $employee->toArray();
        $employee->update($data);

        AuditLog::record($request->user()->id, 'employee.update', 'Employee', $employee->id, $before, $employee->fresh()->toArray());

        return redirect()->route('employees.index')->with('status', 'Employee updated.');
    }

    public function destroy(Request $request, Employee $employee)
    {
        $before = $employee->toArray();
        $employee->delete();

        AuditLog::record($request->user()->id, 'employee.delete', 'Employee', $employee->id, $before, null);

        return redirect()->route('employees.index')->with('status', 'Employee removed.');
    }

    public function importForm()
    {
        return view('employees.import');
    }

    public function import(Request $request)
    {
        $request->validate(['csv_file' => 'required|file']);

        $handle = fopen($request->file('csv_file')->getRealPath(), 'r');
        $header = array_map(fn ($h) => strtolower(trim($h)), fgetcsv($handle));

        $imported = 0;
        $updated = 0;

        while (($row = fgetcsv($handle)) !== false) {
            if (count($row) < count($header)) {
                continue;
            }

            $rowAssoc = array_combine($header, $row);

            if (empty($rowAssoc['emp_id'])) {
                continue;
            }

            $data = [
                'name' => $rowAssoc['name'] ?? '',
                'active' => isset($rowAssoc['active']) ? filter_var($rowAssoc['active'], FILTER_VALIDATE_BOOLEAN) : true,
                'consent_on' => ! empty($rowAssoc['consent_on']) ? $rowAssoc['consent_on'] : null,
            ];

            $employee = Employee::withTrashed()->where('emp_id', $rowAssoc['emp_id'])->first();

            if ($employee) {
                $employee->update($data);
                $updated++;
            } else {
                Employee::create(array_merge(['emp_id' => $rowAssoc['emp_id']], $data));
                $imported++;
            }
        }

        fclose($handle);

        AuditLog::record($request->user()->id, 'employee.csv_import', 'Employee', null, null, ['imported' => $imported, 'updated' => $updated]);

        return redirect()->route('employees.index')->with('status', "Imported {$imported}, updated {$updated} employees.");
    }
}
