<?php

namespace App\Imports;

use App\Models\Classroom;
use App\Models\Student;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;

class StudentsImport implements ToModel, WithHeadingRow, WithValidation, SkipsOnFailure, SkipsEmptyRows
{
    use SkipsFailures;

    protected int $rowsImported = 0;

    /**
     * Normalisasi data sebelum validasi.
     * Excel sering membaca NISN (angka panjang) sebagai float → harus di-cast ke string.
     */
    public function prepareForValidation($data, $index)
    {
        // Cast NISN ke string — mencegah Excel float (1.23456789E+9) gagal validasi 'string'
        if (isset($data['nisn'])) {
            // rtrim '0' tidak dilakukan — cukup format sebagai integer lalu string
            // agar tidak ada desimal (misal 1234567890.0 → "1234567890")
            $nisn = $data['nisn'];
            if (is_numeric($nisn)) {
                $nisn = number_format((float) $nisn, 0, '.', '');
            }
            $data['nisn'] = (string) $nisn;
        }

        // Normalisasi gender ke huruf besar
        if (isset($data['gender'])) {
            $data['gender'] = strtoupper(trim((string) $data['gender']));
        }

        return $data;
    }

    /**
     * @param array $row
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        // Skip baris kosong
        if (empty(trim((string) ($row['name'] ?? '')))) {
            return null;
        }

        $classroomId = Classroom::where('title', $row['classroom'])->value('id');

        $this->rowsImported++;

        return new Student([
            'nisn'         => (string) $row['nisn'],
            'name'         => $row['name'],
            'password'     => $row['password'],
            'gender'       => $row['gender'],
            'classroom_id' => $classroomId,
        ]);
    }

    public function getRowsImported(): int
    {
        return $this->rowsImported;
    }

    /**
     * rules
     *
     * @return array
     */
    public function rules(): array
    {
        return [
            // Validasi sebagai string (setelah prepareForValidation sudah di-cast)
            'nisn'      => ['required', 'string', 'unique:students,nisn'],
            'name'      => ['required', 'string'],
            'password'  => ['required', 'string'],
            'gender'    => ['required', 'in:L,P'],
            'classroom' => ['required', 'string', 'exists:classrooms,title'],
        ];
    }

    /**
     * custom validation messages
     *
     * @return array
     */
    public function customValidationMessages()
    {
        return [
            'nisn.required'      => 'NISN wajib diisi.',
            'nisn.string'        => 'NISN harus berupa teks/angka.',
            'nisn.unique'        => 'NISN :input sudah terdaftar di sistem.',
            'name.required'      => 'Nama siswa wajib diisi.',
            'password.required'  => 'Password wajib diisi.',
            'gender.required'    => 'Jenis kelamin wajib diisi.',
            'gender.in'          => 'Jenis kelamin harus berisi L (Laki-laki) atau P (Perempuan).',
            'classroom.required' => 'Nama kelas wajib diisi.',
            'classroom.exists'   => 'Nama kelas ":input" tidak ditemukan. Pastikan nama kelas sama persis dengan data kelas.',
        ];
    }
}
