<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Category;
use Illuminate\Support\Str;

class CategorySeeder extends Seeder
{
    /**
     * Run the database seeds.
     * This seeder is safe to run multiple times.
     */
    public function run(): void
    {
        // Define categories with their sub-categories
        $categories = [
            'Technology' => [
                'AI & Robotics',
                'Gadgets',
                'Cybersecurity',
                'Software',
                'Mobile'
            ],
            'Business' => [
                'Markets',
                'Economy',
                'Startups',
                'Corporate'
            ],
            'World News' => [
                'Politics',
                'Environment',
                'Human Rights',
                'Conflicts'
            ],
            'Lifestyle' => [
                'Health & Wellness',
                'Travel',
                'Food & Drink',
                'Fashion & Beauty'
            ],
            'Entertainment' => [
                'Movies',
                'Television',
                'Music',
                'Celebrity News'
            ],
            'Sports' => [
                'Football',
                'Basketball',
                'Tennis',
                'Motorsport'
            ],
            'Science' => [], // A parent category with no children
        ];

        // Loop through each parent category and its children
        foreach ($categories as $parentName => $children) {
            
            // Create or find the parent category
            $parentCategory = Category::updateOrCreate(
                ['slug' => Str::slug($parentName)], // Check if a category with this slug exists
                ['name' => $parentName, 'parent_id' => null] // Data to insert or update
            );

            // If there are children, create them
            if (!empty($children)) {
                foreach ($children as $childName) {
                    Category::updateOrCreate(
                        ['slug' => Str::slug($childName)], // Check for child slug
                        [
                            'name' => $childName,
                            'parent_id' => $parentCategory->id // Assign the parent's ID
                        ]
                    );
                }
            }
        }
    }
}