<?php

namespace App\Console\Commands;

use App\Models\ProfileCategory;
use App\Models\ProfileCategoryQuestion;
use App\Models\ProfileQuestion;
use App\Models\ProfileSubQuestion;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use League\Csv\Reader;
use Symfony\Component\HttpKernel\Profiler\Profile;

class ReadCsv extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:read-csv {file?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    function convertTextToLowerAndReplaceSpaces($text)
    {
        $lowercaseText = rtrim(strtolower($text), " ");
        $convertedText = str_replace(' ', '_', $lowercaseText);
        $convertedText = str_replace(',', '_', $lowercaseText);
        $convertedText = trim(str_replace('/', '_', $lowercaseText));
        return $convertedText;
    }
    function convertTextToLowerAndReplaceDashes($text)
    {
        $lowercaseText = rtrim(strtolower($text), " ");
        $convertedText = str_replace(' ', '-', $lowercaseText);
        $convertedText = trim(str_replace('/', '-', $lowercaseText));
        return $convertedText;
    }
    public function handle()
    {


        $fileName = 'question data (5).csv'; // Change this to the name of your CSV file
        $filePath = storage_path($fileName);

        if (!file_exists($filePath)) {
            $this->error('File not found: ' . $filePath);
            return Command::FAILURE;
        }

        $csv = Reader::createFromPath($filePath, 'r');
        $csv->setHeaderOffset(0);

        $records = $csv->getRecords();

        // Get the header row
        $header = $csv->getHeader();

        // Loop through each row
        foreach ($csv->getRecords($header) as $record) {


            $Category = $record['Category'];
            if (count(explode(",", $Category)) > 1) {
                foreach (explode(",", $Category) as $cat) {
                    $ProfileCategory = ProfileCategory::firstOrCreate([
                        'name' => trim($cat),
                        'icon' => $this->convertTextToLowerAndReplaceDashes($cat) . ".png",
                        'category_link' => $this->convertTextToLowerAndReplaceSpaces($cat)
                    ]);
                    $this->insertREcord($ProfileCategory, $record);
                }
            } elseif ($Category) {
                $ProfileCategory = ProfileCategory::firstOrCreate([
                    'name' => trim($Category),
                    'icon' => $this->convertTextToLowerAndReplaceDashes($Category) . ".png",
                    'category_link' => $this->convertTextToLowerAndReplaceSpaces($Category)
                ]);
                $this->insertREcord($ProfileCategory, $record);
            }
        }

        return Command::SUCCESS;
    }
    function insertREcord($ProfileCategory, $record)
    {
        $type = $record['type'];

        $options = rtrim($record['options']);
        $options = serialize(explode(",", $options));
        $Question = $record['Question'];

        $ProfileQuestion = ProfileQuestion::firstOrCreate([
            'question' => $Question,
            'question_options' => $options,
            'question_type' => $type,
        ]);

        try {
            ProfileCategoryQuestion::firstOrCreate([
                'category_id' => $ProfileCategory->id,
                'question_id' => $ProfileQuestion->id
            ]);
        } catch (Exception $e) {
        }

        $BaseQuestionR = $record['Base Question (Reference)'];
        $ProfileQuestion_id = null;
        if ($BaseQuestionR !== "") {
            $ProfileQuestion = ProfileQuestion::where("question", $BaseQuestionR)->first();
            if ($ProfileQuestion)
                $ProfileQuestion_id = $ProfileQuestion->id;
        }


        $SubQuestionR = $record['Sub Question (Reference)'];
        $parent_sub_question_id = null;
        if ($SubQuestionR !== "") {
            $ProfileSubQuestion = ProfileSubQuestion::where("question", $SubQuestionR)->first();
            if ($ProfileSubQuestion)
                $parent_sub_question_id = $ProfileSubQuestion->id;
        }

        $SubQuestion = $record['SubQuestion'];

        $ProfileSubQuestion2 = ProfileSubQuestion::updateOrCreate([
            'category_id' => $ProfileCategory->id,
            'question_id' => $ProfileQuestion_id,
            'question' => $SubQuestion,
            'parent_sub_question_id' => $parent_sub_question_id,
            'sub_question_type' => $type,
            'sub_question_options' => $options,
        ]);
    }
}
