<?php

namespace App\Imports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class StudentsImport implements ToCollection, WithHeadingRow
{
    public $data = [];

    public function collection(Collection $rows)
    {
        foreach ($rows as $row) {
            // Skip rows missing required fields
            if (empty($row['roll_no']) || empty($row['name'])) {
                continue;
            }

            // Normalize and map fields
            $this->data[] = [
                'roll_no' => trim($row['roll_no']),
                'name' => trim($row['name']),
                'phone' => isset($row['phone']) ? trim($row['phone']) : (isset($row['mobile_no']) ? trim($row['mobile_no']) : null),
                'password' => ! empty($row['password']) ? trim($row['password']) : $this->generateRandomPassword(),
                'gender' => $row['gender'] ?? null,
                'religion' => $row['religion'] ?? null,
                'fathers_name' => $row['fathers_name'] ?? null,
                'mothers_name' => $row['mothers_name'] ?? null,
            ];
        }
    }

    protected function generateRandomPassword($length = 8): string
    {
        return substr(str_shuffle('abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789'), 0, $length);
    }
}
