<?php

namespace App\Imports;

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

class Ultimate_Challenge_Question_Import implements ToModel, WithHeadingRow
{
    protected $challenge_id;

    public function __construct($challenge_id)
    {
        $this->challenge_id = $challenge_id;
    }

    public function model(array $row)
    {
        try {
            $url = $row['image'];
            $ext = pathinfo($row['image']);

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

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

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

            return new Ultimate_Challenge_Question([
                'ultimate_challenge_id' => $this->challenge_id,
                '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,
                'status' => 1
            ]);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
}
