<?php

namespace App\Http\Controllers;

use App\Models\Employee;
use App\Models\User;
use App\Models\Department;
use App\Models\Designation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Symfony\Component\HttpFoundation\StreamedResponse;

class EmployeeImportExportController extends Controller
{
    public function index()
    {
        $importedIds = session('imported_employee_ids', []);
        $importedEmployees = collect();

        if (is_array($importedIds) && count($importedIds)) {
            $importedEmployees = Employee::with(['department', 'designation'])
                ->whereIn('id', $importedIds)
                ->orderBy('id', 'desc')
                ->get();
        }

        $employees = Employee::with(['department', 'designation'])->latest()->paginate(20);

        return view('employees.import_export', compact('employees', 'importedEmployees'));
    }

    public function templateCsv()
    {
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="employees_template.csv"',
        ];

        $callback = function () {
            $handle = fopen('php://output', 'w');
            fputcsv($handle, [
                'employee_code',
                'first_name',
                'last_name',
                'email',
                'phone',
                'gender',
                'date_of_birth',
                'department_name',
                'designation_name',
                'hire_date',
                'status',
                'address',
            ]);
            fputcsv($handle, [
                'EMP001',
                'John',
                'Doe',
                'john@example.com',
                '0500000000',
                'male',
                '1990-01-01',
                'IT',
                'Developer',
                '2026-03-26',
                'active',
                'Riyadh',
            ]);
            fclose($handle);
        };

        return new StreamedResponse($callback, 200, $headers);
    }

    public function exportCsv()
    {
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="employees.csv"',
        ];

        $callback = function () {
            $handle = fopen('php://output', 'w');
            fputcsv($handle, [
                'employee_code',
                'first_name',
                'last_name',
                'email',
                'phone',
                'gender',
                'date_of_birth',
                'department_name',
                'designation_name',
                'hire_date',
                'status',
                'address',
            ]);
            Employee::with(['department', 'designation'])->chunk(200, function ($chunk) use ($handle) {
                foreach ($chunk as $e) {
                    fputcsv($handle, [
                        $e->employee_code,
                        $e->first_name,
                        $e->last_name,
                        $e->email,
                        $e->phone,
                        $e->gender,
                        optional($e->date_of_birth)->format('Y-m-d'),
                        optional($e->department)->name,
                        optional($e->designation)->name,
                        optional($e->hire_date)->format('Y-m-d'),
                        $e->status,
                        $e->address,
                    ]);
                }
            });
            fclose($handle);
        };

        return new StreamedResponse($callback, 200, $headers);
    }

    public function importCsv(Request $request)
    {
        $request->validate([
            'file' => 'required|file|mimes:csv,txt',
        ]);

        $file = $request->file('file');
        $rows = array_map('str_getcsv', file($file->getRealPath()));
        if (!count($rows)) {
            return redirect()->route('employees.import-export')->with('error', 'Empty file.');
        }
        $header = array_map('trim', array_shift($rows));

        $idx = array_flip($header);
        $importedIds = [];

        foreach ($rows as $row) {
            $employee_code = $row[$idx['employee_code']] ?? null;
            $first_name = $row[$idx['first_name']] ?? null;
            $last_name = $row[$idx['last_name']] ?? '';
            $email = $row[$idx['email']] ?? null;
            $phone = $row[$idx['phone']] ?? null;
            $gender = $row[$idx['gender']] ?? null;
            $date_of_birth = $row[$idx['date_of_birth']] ?? null;
            $departmentName = $row[$idx['department_name']] ?? null;
            $designationName = $row[$idx['designation_name']] ?? null;
            $hire_date = $row[$idx['hire_date']] ?? null;
            $status = $row[$idx['status']] ?? 'active';
            $address = $row[$idx['address']] ?? null;

            if (!$employee_code || !$first_name) continue;

            $employee = Employee::firstOrNew(['employee_code' => $employee_code]);
            $employee->first_name = $first_name;
            $employee->last_name = $last_name;
            $employee->email = $email;
            $employee->phone = $phone;
            $employee->gender = $gender;
            $employee->date_of_birth = $date_of_birth ?: null;
            $employee->hire_date = $hire_date ?: null;
            $employee->status = $status ?: 'active';
            $employee->address = $address;

            if ($departmentName) {
                $dept = Department::where('name', $departmentName)->first();
                if ($dept) {
                    $employee->department_id = $dept->id;
                }
            }
            if ($designationName) {
                $des = Designation::where('name', $designationName)->first();
                if ($des) {
                    $employee->designation_id = $des->id;
                }
            }

            if (!$employee->user_id && $email) {
                $user = User::firstOrCreate(
                    ['email' => $email],
                    [
                        'name' => $first_name . ' ' . $last_name,
                        'password' => Hash::make($employee_code),
                        'must_change_password' => true,
                        'is_admin' => false,
                    ]
                );
                $employee->user_id = $user->id;
            }

            $employee->save();
            $importedIds[] = $employee->id;
        }

        return redirect()->route('employees.import-export')
            ->with('success', 'Employees imported successfully.')
            ->with('imported_employee_ids', $importedIds);
    }
}
