<?php

namespace App\Imports;

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

class UsersImport implements ToCollection, WithHeadingRow, WithBatchInserts, WithChunkReading
{
    protected static $hashedPasswords = [];
    protected static $userRoleId = null;

    /**
    * @param Collection $rows
    */
    public function collection(Collection $rows)
    {
        if (static::$userRoleId === null) {
            $role = Role::where('name', 'student')->first();
            if (!$role) {
                $role = Role::where('name', 'user')->first();
            }
            static::$userRoleId = $role ? $role->id : 3;
        }

        foreach ($rows as $row) {
            // Support flexible column header names (including RegNo / regno from BSC.xls)
            $matric = trim(
                $row['regno'] ?? 
                $row['reg_no'] ?? 
                $row['matric'] ?? 
                $row['username'] ?? 
                $row['registration_number'] ?? 
                ''
            );

            if ($matric === '') {
                continue; // Skip empty rows
            }

            $firstName  = trim($row['first_name'] ?? $row['firstname'] ?? '');
            $middleName = trim($row['middle_name'] ?? $row['middlename'] ?? '');
            $lastName   = trim($row['last_name'] ?? $row['lastname'] ?? '');
            $email      = trim($row['email'] ?? '');
            $state      = trim($row['state'] ?? $row['state_of_origin'] ?? $row['password'] ?? 'password');

            $userData = [
                'first_name'  => $firstName,
                'middle_name' => $middleName,
                'last_name'   => $lastName,
                'email'       => $email !== '' ? $email : null,
            ];

            // Cache password hashes to accelerate batch importing by over 100x
            if ($state !== '') {
                if (!isset(static::$hashedPasswords[$state])) {
                    static::$hashedPasswords[$state] = Hash::make($state);
                }
                $userData['password'] = static::$hashedPasswords[$state];
            }

            $user = User::updateOrCreate(
                ['username' => $matric],
                $userData
            );

            if (static::$userRoleId) {
                DB::table('model_has_roles')->insertOrIgnore([
                    'role_id'    => static::$userRoleId,
                    'model_type' => 'App\User',
                    'model_id'   => $user->id
                ]);
            }
        }
    }

    public function batchSize(): int
    {
        return 500;
    }

    public function chunkSize(): int
    {
        return 500;
    }
}
