<?php

namespace App\Imports;

use App\Models\User;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class UsersImport implements ToCollection, WithHeadingRow
{
    private $importType;
    private $importedCount = 0;
    private $updatedCount = 0;
    private $failedCount = 0;
    private $errors = [];

    public function __construct($importType = 'create')
    {
        $this->importType = $importType;
    }

    public function collection(Collection $rows)
    {
        foreach ($rows as $index => $row) {
            try {
                $row = $row->toArray();
                
                // Validate row data
                $validator = Validator::make($row, [
                    'name' => 'required|string|max:255',
                    'email' => 'required|email|max:255',
                    'phone' => 'nullable|string|max:20',
                    'password' => $this->importType === 'create' ? 'required|string' : 'nullable|string',
                    'roles' => 'required|string',
                    'department' => 'nullable|string|max:100',
                    'position' => 'nullable|string|max:100',
                    'employee_id' => 'nullable|string|max:50',
                    'status' => 'required|in:active,inactive,1,0,true,false',
                ]);

                if ($validator->fails()) {
                    $this->failedCount++;
                    $this->errors[] = "Row " . ($index + 2) . ": " . implode(', ', $validator->errors()->all());
                    continue;
                }

                DB::beginTransaction();

                // Prepare user data
                $userData = [
                    'name' => $row['name'],
                    'email' => $row['email'],
                    'phone' => $row['phone'] ?? null,
                    'department' => $row['department'] ?? null,
                    'position' => $row['position'] ?? null,
                    'employee_id' => $row['employee_id'] ?? null,
                    'status' => $this->parseStatus($row['status']),
                ];

                // Set password for new users
                if ($this->importType === 'create') {
                    $userData['password'] = Hash::make($row['password']);
                }

                if ($this->importType === 'create') {
                    // Check if user already exists
                    if (User::where('email', $row['email'])->exists()) {
                        throw new \Exception("User with email {$row['email']} already exists");
                    }

                    $user = User::create($userData);
                    $this->importedCount++;
                } else {
                    // Update existing user
                    $user = User::where('email', $row['email'])->first();
                    if (!$user) {
                        throw new \Exception("User with email {$row['email']} not found");
                    }
                    
                    $user->update($userData);
                    $this->updatedCount++;
                }

                // Assign roles
                $roleNames = array_map('trim', explode(',', $row['roles']));
                $roles = Role::whereIn('name', $roleNames)->get();
                
                if ($roles->isEmpty()) {
                    throw new \Exception("No valid roles found: " . $row['roles']);
                }
                
                $user->syncRoles($roles);

                DB::commit();

            } catch (\Exception $e) {
                DB::rollBack();
                $this->failedCount++;
                $this->errors[] = "Row " . ($index + 2) . ": " . $e->getMessage();
            }
        }
    }

    private function parseStatus($status)
    {
        if (in_array($status, ['active', '1', 'true'])) {
            return true;
        }
        return false;
    }

    public function getImportedCount()
    {
        return $this->importedCount;
    }

    public function getUpdatedCount()
    {
        return $this->updatedCount;
    }

    public function getFailedCount()
    {
        return $this->failedCount;
    }

    public function getErrors()
    {
        return $this->errors;
    }
}