<?php

namespace App\Imports;

use App\Models\Student;
use Maatwebsite\Excel\Row;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class StudentsImport implements OnEachRow, WithHeadingRow
{
    public function onRow(Row $row)
    {
        $data = $row->toArray();
        
        // Generate unique temp registration number to avoid conflicts during bulk import
        $regnum = 'TMP_' . uniqid() . '_' . rand(1000, 9999);
        
        $student = Student::create([
            'regnum' => $regnum,
            'first_name' => $data['first_name'] ?? '',
            'last_name' => $data['last_name'] ?? '',
            'class' => $data['class'] ?? '',
            'destination' => $data['destination'] ?? '',
            'status' => $data['status'] ?? 'active',
            'amount_paid' => $data['amount_paid'] ?? 0,
            'payment_date' => isset($data['payment_date']) ? \Carbon\Carbon::parse($data['payment_date']) : null,
        ]);

        // Generate proper format R{YY}{ID}{Random}{CheckLetter}
        $regnum = $this->generateRegnumForStudent($student->id);
        $student->update(['regnum' => $regnum]);
    }

    private function generateRegnumForStudent($id)
    {
        $year = date('y');
        $idStr = (string)$id;
        $idLen = strlen($idStr);
        $randomLen = max(0, 4 - $idLen);
        $randomNumber = '';
        if ($randomLen > 0) {
            for ($i = 0; $i < $randomLen; $i++) {
                $randomNumber .= rand(0, 9);
            }
        }
        $checkLetter = chr(rand(65, 90));

        return 'R' . $year . $idStr . $randomNumber . $checkLetter;
    }
}