<?php

namespace Database\Seeders;

use App\FaqLink;
use Illuminate\Database\Seeder;
use App\Faq;
use Illuminate\Support\Facades\DB;

class FaqSeeder extends Seeder
{
	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		// Clear the existing FAQs
		$listLinkItems = FaqLink::all();
		foreach ($listLinkItems as $item) {
			$item->delete();
		}
		
		$listItems = Faq::all();
		foreach ($listItems as $item) {
			$item->delete();
		}
		
		// Import CSV
		$this->importCSV('faq_tab_1.csv', 0); // 0 for type "レンタルについて"
		$this->importCSV('faq_tab_2.csv', 1); // 1 for type "オーナーついて"
		$this->importCSV('faq_tab_3.csv', 2); // 2 for type "保管ついて"
	}
	
	private function importCSV($csvFileName, $group)
	{
		// Define the FAQ types and their corresponding integer values
		// Mapping array for type conversion from string to integer
		$typeMapping = [
			'サービスについて'         => 0,
			'セット内容について'       => 1,
			'汚損・破損・紛失について' => 2,
			'支払いについて'           => 3,
			'注文について'             => 4,
			'配送・返送について'       => 5,
			'変更・キャンセルについて' => 6,
			'金額について'             => 7,
			'補償について'             => 8,
			'利用停止について'         => 9,
			'料金について'             => 10,
		];
		
		// Path to the CSV file
		$csvPath = public_path('csv/' . $csvFileName);
		
		// Check if the file exists
		if (file_exists($csvPath)) {
			// Open the CSV file
			$file = fopen($csvPath, 'r');
			
			// Skip the header row if it exists
			fgetcsv($file);
			
			// Process each row in the CSV
			while (($row = fgetcsv($file)) !== false) {
				if (count($row) >= 3) {
					$typeStr = trim($row[0]);
					$name = trim($row[1]);
					$description = trim($row[2]);
					
					// Convert type string to integer using the mapping
					$type = isset($typeMapping[$typeStr]) ? $typeMapping[$typeStr] : -1;
					
					if ($type !== -1) {
						// Check if a record with the same type and name already exists
						$existingFaq = Faq::where('group', $group)
							->where('type', $type)
							->where('name', $name)
							->first();
						
						if ($existingFaq) {
							// Update the description if the record exists
							$existingFaq->update(['description' => $description]);
						} else {
							// Create a new record if it doesn't exist
							Faq::create([
								'group'       => $group,
								'type'        => $type,
								'name'        => $name,
								'description' => $description,
							]);
						}
					}
				}
			}
			
			fclose($file);
			$this->command->info('FAQs have been seeded successfully from CSV.');
		} else {
			$this->command->error('CSV file not found at: ' . $csvPath);
		}
	}
}
