<?php

namespace App\Imports;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\SkipsErrors;

class UsersImport implements ToModel, WithHeadingRow, SkipsOnError
{
    use SkipsErrors;

    public function model(array $row)
    {
        // Skip baris kosong atau emel sudah wujud
        if (empty($row['email']) || User::where('email', $row['email'])->exists()) {
            return null;
        }

        // Convert jenis_sekolah to array format
        $jenisSekolah = null;
        if (!empty($row['jenis_sekolah'])) {
            $val = $row['jenis_sekolah'];
            // Map old kod_jenis to nama_jenis
            $map = ['123' => 'SRA', '124' => 'SRAI', '125' => 'KAFAI'];
            // Support comma-separated values like "SRA,KKM"
            $parts = array_map('trim', explode(',', $val));
            $jenisSekolah = array_map(fn($p) => $map[$p] ?? strtoupper($p), $parts);
        }

        return new User([
            'name'          => $row['name'] ?? '',
            'email'         => $row['email'],
            'password'      => Hash::make($row['password'] ?? 'password123'),
            'role'          => $row['role'] ?? 'pemohon',
            'jenis_sekolah' => $jenisSekolah,
            'kod_sekolah'   => $row['kod_sekolah'] ?? null,
            'nama_sekolah'  => $row['nama_sekolah'] ?? null,
            'daerah'        => $row['daerah'] ?? null,
        ]);
    }
}
