<?php

namespace Database\Seeders;

use App\ProductCategory;
use Illuminate\Database\Seeder;
use App\Category;
use App\Helpers\Helper;

class CategoryCsvSeeder extends Seeder
{
	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		$csvFile = public_path('csv/category.csv');
		
		if (!file_exists($csvFile)) {
			$this->command->error("CSV file not found: {$csvFile}");
			return;
		}
		
		$this->command->info('Starting CSV import for categories...');
		
		// Delete all existing product categories
		$listProductCategories = ProductCategory::all();
		foreach ($listProductCategories as $category) {
			$category->delete();
		}
		
		// Delete all existing categories
		$listCategories = Category::all();
		foreach ($listCategories as $category) {
			$category->delete();
		}
		
		// Read CSV file
		$handle = fopen($csvFile, 'r');
		
		if ($handle === false) {
			$this->command->error("Could not open CSV file: {$csvFile}");
			return;
		}
		
		// Skip header row
		$header = fgetcsv($handle);
		
		$parentCategories = [];
		$processedCount = 0;
		$skippedCount = 0;
		
		// First pass: collect all data
		while (($data = fgetcsv($handle)) !== false) {
			if (count($data) >= 2) {
				$parentName = trim($data[0]);
				$childName = trim($data[1]);
				
				if (!empty($parentName) && !empty($childName)) {
					if (!isset($parentCategories[$parentName])) {
						$parentCategories[$parentName] = [];
					}
					$parentCategories[$parentName][] = $childName;
				}
			}
		}
		
		fclose($handle);
		
		// Second pass: process and insert categories
		foreach ($parentCategories as $parentName => $children) {
			// Check if parent category exists
			$parentCategory = Category::where('name', $parentName)
				->where('parent_id', 0)
				->where('is_deleted', false)
				->first();
			
			if (!$parentCategory) {
				// Get max position for parent categories
				$maxPosition = Category::where('parent_id', 0)
					->where('is_deleted', false)
					->max('position') ?? 0;
				
				// Create parent category
				$parentCategory = Category::create([
					'name'         => $parentName,
					'slug'         => Helper::slug($parentName),
					'parent_id'    => 0,
					'image'        => '',
					'sub_title'    => '',
					'group'        => null,
					'description'  => '',
					'rank'         => null,
					'position'     => $maxPosition + 1,
					'is_activated' => true,
					'is_deleted'   => false,
					'created_at'   => now(),
					'updated_at'   => now()
				]);
				
				$this->command->info("Created parent category: {$parentName}");
				$processedCount++;
			} else {
				$this->command->info("Parent category already exists: {$parentName}");
				$skippedCount++;
			}
			
			// Process child categories
			foreach ($children as $childName) {
				$childCategory = Category::where('name', $childName)
					->where('parent_id', $parentCategory->id)
					->where('is_deleted', false)
					->first();
				
				if (!$childCategory) {
					// Get max position for child categories of this parent
					$maxChildPosition = Category::where('parent_id', $parentCategory->id)
						->where('is_deleted', false)
						->max('position') ?? 0;
					
					// Create child category
					Category::create([
						'name'         => $childName,
						'slug'         => Helper::slug($childName),
						'parent_id'    => $parentCategory->id,
						'image'        => '',
						'sub_title'    => '',
						'group'        => null,
						'description'  => '',
						'rank'         => null,
						'position'     => $maxChildPosition + 1,
						'is_activated' => true,
						'is_deleted'   => false,
						'created_at'   => now(),
						'updated_at'   => now()
					]);
					
					$this->command->info("  Created child category: {$childName} under {$parentName}");
					$processedCount++;
				} else {
					$this->command->info("  Child category already exists: {$childName} under {$parentName}");
					$skippedCount++;
				}
			}
		}
		
		$this->command->info("CSV import completed!");
		$this->command->info("Processed: {$processedCount} categories");
		$this->command->info("Skipped (already exist): {$skippedCount} categories");
	}
}