<?php

namespace App\Imports;

use App\Models\Result;
use App\Models\Student;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;

class ResultsImport implements ToModel, WithHeadingRow, WithValidation
{
    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        // Try to find student by roll, class, and year
        $student = Student::where('roll', $row['roll'])
            ->where('class', $row['class'])
            ->where('year', $row['year'])
            ->first();

        return new Result([
            'student_id' => $student ? $student->id : null,
            'roll' => $row['roll'],
            'class' => $row['class'],
            'year' => $row['year'],
            'student_name' => $row['student_name'],
            'total_marks' => $row['total_marks'],
            'grade' => $row['grade'] ?? Result::calculateGrade($row['total_marks']),
            'remarks' => $row['remarks'] ?? null,
        ]);
    }

    /**
     * Validation rules for import.
     */
    public function rules(): array
    {
        return [
            'roll' => 'required',
            'class' => 'required',
            'year' => 'required',
            'student_name' => 'required',
            'total_marks' => 'required|numeric',
            'grade' => 'nullable',
            'remarks' => 'nullable',
        ];
    }
}

