<?php

namespace App\Imports;

use App\Models\Video_Quiz_Question;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Exception;

class Video_Question_Import implements ToModel, WithHeadingRow
{
    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        try {
            $url = $row['image'];
            $ext = pathinfo($row['image']);

            $image = "";
            if ($url && isset($ext['extension'])) {

                $filename = 'video_img_' . date('Y_m_d_') . uniqid() . '.' . $ext['extension'];
                $path = storage_path() . '/app/public/question/';

                file_put_contents($path . $filename, file_get_contents($url));
                if ($filename) {
                    $image = $filename;
                }
            }

            return new Video_Quiz_Question([
                'category_id' => $row['category_id'] ?? 0,
                'skill_id' => $row['skill_id'] ?? 0,
                'classification_id' => $row['classification_id'] ?? 0,
                'level_id' => $row['level_id'] ?? 0,
                'question' => $row['question'],
                'option_a' => $row['option_a'],
                'option_b' => $row['option_b'],
                'option_c' => $row['option_c'],
                'option_d' => $row['option_d'],
                'correct_answer' => $row['correct_answer'],
                'note' => $row['note'] ?? "",
                'image' => $image,
                'video_type' => 'external_url',
                'video' => $row['video'] ?? "",
                'status' => 1
            ]);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
}
