<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\RPartner;
use App\Models\RPartnership;
use App\Models\RPartnerContact;
use App\Models\RForumThread;
use App\Models\RForumReply;
use App\Models\User;
use Illuminate\Support\Str;

/**
 * Seeder: RPartnershipModuleSeeder
 * 
 * Seeds partnership and collaboration content for SSHIA - South Sudan Health Innovation & Advocacy.
 * Contains partners, partnerships, and forum discussions related to health collaboration in South Sudan.
 * 
 * @author SSHIA Development Team
 * @version 1.0.0
 */
class RPartnershipModuleSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $users = User::all();
        
        if ($users->isEmpty()) {
            $this->command->warn('No users found. Please run user seeder first.');
            return;
        }

        // Seed Partners
        $partners = $this->seedPartners($users);
        
        // Seed Partnerships (MOUs/Agreements)
        $this->seedPartnerships($partners, $users);
        
        // Seed Forum Threads
        $this->seedForumThreads($users, $partners);
    }

    /**
     * Seed partner organizations.
     */
    protected function seedPartners($users): array
    {
        $partners = [
            [
                'organization_name' => 'World Health Organization - South Sudan',
                'slug' => 'who-south-sudan',
                'legal_name' => 'World Health Organization Country Office - South Sudan',
                'description' => 'The World Health Organization is the directing and coordinating authority for health within the United Nations system. In South Sudan, WHO works closely with the Ministry of Health and partners to strengthen health systems, respond to health emergencies, and improve access to essential health services for all populations.',
                'mission_statement' => 'To promote health, keep the world safe, and serve the vulnerable in South Sudan through technical leadership, partnership building, and evidence-based health interventions.',
                'email' => 'southsudan@who.int',
                'phone' => '+211 922 000 100',
                'website' => 'https://www.who.int/countries/ssd',
                'address_line_1' => 'United Nations Mission in South Sudan (UNMISS)',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'international',
                'category' => 'Public Health',
                'services_offered' => json_encode(['Technical Assistance', 'Health System Strengthening', 'Disease Surveillance', 'Emergency Response', 'Policy Development']),
                'partnership_level' => 'platinum',
                'is_verified' => true,
                'is_featured' => true,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'UNICEF South Sudan',
                'slug' => 'unicef-south-sudan',
                'legal_name' => 'United Nations Children\'s Fund - South Sudan Country Office',
                'description' => 'UNICEF works in South Sudan to protect children\'s rights and ensure every child has access to health, education, and protection services. UNICEF is a key partner in immunization programs, nutrition interventions, and child health initiatives across the country.',
                'mission_statement' => 'To ensure every child in South Sudan survives, thrives, and fulfills their potential through equitable access to quality health, nutrition, education, and protection services.',
                'email' => 'juba@unicef.org',
                'phone' => '+211 922 000 200',
                'website' => 'https://www.unicef.org/southsudan',
                'address_line_1' => 'UNICEF House, Ministries Complex',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'international',
                'category' => 'Child Health & Protection',
                'services_offered' => json_encode(['Child Health', 'Immunization', 'Nutrition Programs', 'Education', 'Child Protection', 'WASH']),
                'partnership_level' => 'platinum',
                'is_verified' => true,
                'is_featured' => true,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'Ministry of Health - Republic of South Sudan',
                'slug' => 'ministry-of-health-south-sudan',
                'legal_name' => 'Ministry of Health, Republic of South Sudan',
                'description' => 'The Ministry of Health is the government body responsible for health policy, planning, and service delivery in South Sudan. The Ministry leads the health sector and coordinates all health partners to achieve universal health coverage and improve health outcomes for all citizens.',
                'mission_statement' => 'To provide equitable, quality, and accessible health services to all people of South Sudan through strengthened health systems, partnerships, and community engagement.',
                'email' => 'info@moh.gov.ss',
                'phone' => '+211 922 000 300',
                'website' => 'https://www.moh.gov.ss',
                'address_line_1' => 'Ministry of Health Complex',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'government',
                'category' => 'Government Health Services',
                'services_offered' => json_encode(['Health Policy', 'Health Services', 'Disease Control', 'Health Workforce', 'Pharmaceutical Services']),
                'partnership_level' => 'platinum',
                'is_verified' => true,
                'is_featured' => true,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'Catholic Relief Services - South Sudan',
                'slug' => 'crs-south-sudan',
                'legal_name' => 'Catholic Relief Services - South Sudan Program',
                'description' => 'Catholic Relief Services has been working in South Sudan for decades, providing humanitarian assistance and development programs. CRS implements health, nutrition, and WASH programs that reach vulnerable populations across multiple states.',
                'mission_statement' => 'To assist the poor and vulnerable in South Sudan through health, nutrition, and WASH programs that promote human dignity and sustainable development.',
                'email' => 'southsudan@crs.org',
                'phone' => '+211 922 000 400',
                'website' => 'https://www.crs.org/our-work-overseas/where-we-work/south-sudan',
                'address_line_1' => 'Hai Jerusalem, Juba',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'faith_based',
                'category' => 'Humanitarian Health',
                'services_offered' => json_encode(['Primary Health Care', 'Nutrition Programs', 'WASH', 'Emergency Response', 'Community Development']),
                'partnership_level' => 'gold',
                'is_verified' => true,
                'is_featured' => true,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'International Medical Corps - South Sudan',
                'slug' => 'international-medical-corps-south-sudan',
                'legal_name' => 'International Medical Corps - South Sudan Mission',
                'description' => 'International Medical Corps provides medical relief and healthcare training in South Sudan. IMC operates primary healthcare facilities, supports hospitals, and implements community health programs focused on maternal and child health.',
                'mission_statement' => 'To save lives and relieve suffering through healthcare training and medical relief programs in underserved communities of South Sudan.',
                'email' => 'southsudan@internationalmedicalcorps.org',
                'phone' => '+211 922 000 500',
                'website' => 'https://internationalmedicalcorps.org/country/south-sudan',
                'address_line_1' => 'Hai Amarat, Juba',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'ngo',
                'category' => 'Medical Relief',
                'services_offered' => json_encode(['Primary Health Care', 'Emergency Medicine', 'Mental Health', 'Nutrition', 'Health Training']),
                'partnership_level' => 'gold',
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'Doctors Without Borders - South Sudan',
                'slug' => 'msf-south-sudan',
                'legal_name' => 'Médecins Sans Frontières - South Sudan',
                'description' => 'MSF provides emergency medical care in South Sudan, operating hospitals, primary healthcare facilities, and emergency response programs. MSF works in conflict-affected areas and provides specialized care including surgery and treatment for tropical diseases.',
                'mission_statement' => 'To provide impartial medical care to people affected by conflict, epidemics, and disasters in South Sudan.',
                'email' => 'press@msf.org',
                'phone' => '+211 922 000 600',
                'website' => 'https://www.msf.org/south-sudan',
                'address_line_1' => 'Hai Malakal, Juba',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'ngo',
                'category' => 'Emergency Medicine',
                'services_offered' => json_encode(['Emergency Surgery', 'Primary Health Care', 'HIV/TB Treatment', 'Vaccination', 'Mental Health']),
                'partnership_level' => 'gold',
                'is_verified' => true,
                'is_featured' => true,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'World Vision South Sudan',
                'slug' => 'world-vision-south-sudan',
                'legal_name' => 'World Vision International - South Sudan',
                'description' => 'World Vision is a Christian humanitarian organization working in South Sudan to improve child well-being through health, nutrition, WASH, and protection programs. WV implements large-scale community-based health interventions.',
                'mission_statement' => 'To work for the well-being of children in South Sudan through community-based health, nutrition, and protection programs.',
                'email' => 'southsudan@wvi.org',
                'phone' => '+211 922 000 700',
                'website' => 'https://www.wvi.org/south-sudan',
                'address_line_1' => 'Hai Miskeen, Juba',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'faith_based',
                'category' => 'Child Development',
                'services_offered' => json_encode(['Child Health', 'Nutrition', 'WASH', 'Food Security', 'Protection', 'Education']),
                'partnership_level' => 'gold',
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'Juba Teaching Hospital',
                'slug' => 'juba-teaching-hospital',
                'legal_name' => 'Juba Teaching Hospital - Ministry of Health',
                'description' => 'Juba Teaching Hospital is the largest referral hospital in South Sudan, providing specialized medical services and serving as a teaching facility for healthcare professionals. The hospital offers surgical, medical, pediatric, and obstetric services.',
                'mission_statement' => 'To provide quality specialized healthcare services and train healthcare professionals for South Sudan.',
                'email' => 'info@jth.gov.ss',
                'phone' => '+211 922 000 800',
                'website' => 'https://www.jth.gov.ss',
                'address_line_1' => 'Hai Malakal, Near Juba University',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'healthcare',
                'category' => 'Hospital Services',
                'services_offered' => json_encode(['Emergency Services', 'Surgery', 'Internal Medicine', 'Pediatrics', 'Obstetrics', 'Laboratory Services']),
                'partnership_level' => 'gold',
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'University of Juba - College of Medicine',
                'slug' => 'university-of-juba-medicine',
                'legal_name' => 'University of Juba, College of Medicine',
                'description' => 'The College of Medicine at University of Juba trains doctors and health professionals for South Sudan. The college partners with health organizations for research, clinical training, and health workforce development.',
                'mission_statement' => 'To produce competent health professionals and advance medical knowledge through education, research, and community service.',
                'email' => 'medicine@uoj.edu.ss',
                'phone' => '+211 922 000 900',
                'website' => 'https://www.uoj.edu.ss',
                'address_line_1' => 'University Campus, Hai Jalaba',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'academic',
                'category' => 'Medical Education',
                'services_offered' => json_encode(['Medical Education', 'Health Research', 'Clinical Training', 'Continuing Medical Education']),
                'partnership_level' => 'silver',
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'South Sudan Red Cross',
                'slug' => 'south-sudan-red-cross',
                'legal_name' => 'South Sudan Red Cross Society',
                'description' => 'The South Sudan Red Cross is a volunteer-based humanitarian organization providing emergency response, health services, and community programs. SSRC works closely with communities on first aid, disaster response, and health promotion.',
                'mission_statement' => 'To alleviate human suffering through volunteer service and community-based health and disaster response programs.',
                'email' => 'info@ssrc.org.ss',
                'phone' => '+211 922 001 000',
                'website' => 'https://www.ssrc.org.ss',
                'address_line_1' => 'Hai Miskeen, Juba',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'ngo',
                'category' => 'Humanitarian Services',
                'services_offered' => json_encode(['First Aid Training', 'Emergency Response', 'Blood Donation', 'Community Health', 'Disaster Response']),
                'partnership_level' => 'silver',
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'Health Pooled Fund',
                'slug' => 'health-pooled-fund',
                'legal_name' => 'Health Pooled Fund - South Sudan',
                'description' => 'The Health Pooled Fund is a multi-donor funded program supporting primary healthcare delivery in South Sudan. HPF works through implementing partners to strengthen health systems and improve access to essential health services.',
                'mission_statement' => 'To support delivery of quality primary healthcare services through health system strengthening and partner coordination.',
                'email' => 'info@hpfss.org',
                'phone' => '+211 922 001 100',
                'website' => 'https://www.hpfss.org',
                'address_line_1' => 'Hai Amarat, Juba',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'international',
                'category' => 'Health Financing',
                'services_offered' => json_encode(['Health System Strengthening', 'Primary Health Care', 'Capacity Building', 'Health Financing', 'Monitoring & Evaluation']),
                'partnership_level' => 'platinum',
                'is_verified' => true,
                'is_featured' => true,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'AIDS Information Centre - South Sudan',
                'slug' => 'aids-information-centre',
                'legal_name' => 'AIDS Information Centre - South Sudan',
                'description' => 'The AIDS Information Centre provides HIV testing, counseling, and support services across South Sudan. AIC is a key partner in HIV prevention, treatment, and care programs, working to reduce HIV transmission and support those affected.',
                'mission_statement' => 'To reduce HIV transmission and support people affected by HIV through testing, counseling, education, and care services.',
                'email' => 'info@aicaids.org',
                'phone' => '+211 922 001 200',
                'website' => 'https://www.aicaids.org',
                'address_line_1' => 'Hai Malakal, Juba',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'ngo',
                'category' => 'HIV/AIDS Services',
                'services_offered' => json_encode(['HIV Testing', 'Counseling', 'Prevention Education', 'Support Groups', 'ART Linkage']),
                'partnership_level' => 'silver',
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'Crown The Woman - South Sudan',
                'slug' => 'crown-the-woman',
                'legal_name' => 'Crown The Woman - South Sudan',
                'description' => 'Crown The Woman is a women-led organization promoting gender equality and women\'s health in South Sudan. The organization focuses on maternal health, gender-based violence prevention, and women\'s empowerment programs.',
                'mission_statement' => 'To empower women and girls in South Sudan through health programs, education, and advocacy for gender equality.',
                'email' => 'info@crownthewoman.org',
                'phone' => '+211 922 001 300',
                'website' => 'https://www.crownthewoman.org',
                'address_line_1' => 'Hai Cinema, Juba',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'community_based',
                'category' => 'Women\'s Health',
                'services_offered' => json_encode(['Maternal Health', 'GBV Prevention', 'Women\'s Empowerment', 'Health Education', 'Advocacy']),
                'partnership_level' => 'silver',
                'is_verified' => true,
                'is_featured' => true,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'Save the Children - South Sudan',
                'slug' => 'save-the-children-south-sudan',
                'legal_name' => 'Save the Children International - South Sudan',
                'description' => 'Save the Children works to ensure every child in South Sudan survives, learns, and is protected. SC implements comprehensive health, nutrition, education, and protection programs reaching children in the most vulnerable communities.',
                'mission_statement' => 'To inspire breakthroughs in the way the world treats children and to achieve immediate and lasting change in their lives.',
                'email' => 'southsudan@savethechildren.org',
                'phone' => '+211 922 001 400',
                'website' => 'https://www.savethechildren.org/south-sudan',
                'address_line_1' => 'Hai Amarat, Juba',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'ngo',
                'category' => 'Child Development',
                'services_offered' => json_encode(['Child Health', 'Nutrition', 'Education', 'Child Protection', 'Emergency Response']),
                'partnership_level' => 'gold',
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'American Refugee Committee - South Sudan',
                'slug' => 'arc-south-sudan',
                'legal_name' => 'American Refugee Committee - South Sudan',
                'description' => 'ARC provides humanitarian assistance to conflict-affected populations in South Sudan, with programs in health, protection, and economic development. ARC operates health facilities and community health programs in underserved areas.',
                'mission_statement' => 'To help people survive conflict and rebuild their lives through health, protection, and economic opportunity programs.',
                'email' => 'southsudan@arc.org',
                'phone' => '+211 922 001 500',
                'website' => 'https://www.arc.org',
                'address_line_1' => 'Hai Miskeen, Juba',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'ngo',
                'category' => 'Humanitarian Health',
                'services_offered' => json_encode(['Primary Health Care', 'Reproductive Health', 'Gender-Based Violence Response', 'Livelihoods', 'Emergency Response']),
                'partnership_level' => 'silver',
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
        ];

        $createdPartners = [];
        $created = 0;
        foreach ($partners as $partner) {
            $model = RPartner::firstOrCreate(
                ['slug' => $partner['slug']],
                [
                    'user_id' => rand(0, 1) ? $users->random()->id : null,
                    'organization_name' => $partner['organization_name'],
                    'slug' => $partner['slug'],
                    'legal_name' => $partner['legal_name'],
                    'description' => $partner['description'],
                    'mission_statement' => $partner['mission_statement'],
                    'email' => $partner['email'],
                    'phone' => $partner['phone'],
                    'website' => $partner['website'],
                    'address_line_1' => $partner['address_line_1'],
                    'city' => $partner['city'],
                    'country' => $partner['country'],
                    'organization_type' => $partner['organization_type'],
                    'category' => $partner['category'],
                    'services_offered' => $partner['services_offered'],
                    'partnership_level' => $partner['partnership_level'],
                    'partnership_status' => 'active',
                    'is_verified' => $partner['is_verified'],
                    'is_featured' => $partner['is_featured'],
                    'show_in_directory' => $partner['show_in_directory'],
                    'verified_at' => now()->subDays(rand(30, 365)),
                    'verified_by' => $users->random()->id,
                    'partnership_start_date' => now()->subYears(rand(1, 5))->format('Y-m-d'),
                    'created_at' => now()->subDays(rand(365, 730)),
                ]
            );
            $createdPartners[] = $model;
            if ($model->wasRecentlyCreated) {
                $created++;
            }
        }

        $this->command->info("Created {$created} partner organizations.");
        return $createdPartners;
    }

    /**
     * Seed partnerships (MOUs/Agreements).
     */
    protected function seedPartnerships($partners, $users): void
    {
        $partnerships = [
            [
                'title' => 'Digital Health Partnership Agreement',
                'agreement_type' => 'mou',
                'description' => 'Partnership agreement for collaborative digital health initiatives including telemedicine, mHealth applications, and health information systems strengthening in South Sudan.',
                'objectives' => "• Develop and implement telemedicine programs\n• Train healthcare workers on digital health tools\n• Establish health information systems\n• Conduct digital health research\n• Advocate for digital health policy",
                'scope' => 'National coverage with pilot projects in Central Equatoria, Jonglei, and Upper Nile states.',
                'start_date' => '2024-01-01',
                'end_date' => '2026-12-31',
                'auto_renew' => true,
                'renewal_period_months' => 24,
                'value' => 500000.00,
                'resources_committed' => "Technical expertise, training materials, software platforms, monitoring and evaluation support.",
            ],
            [
                'title' => 'Maternal Health Collaboration Framework',
                'agreement_type' => 'collaboration_agreement',
                'description' => 'Framework agreement for joint implementation of maternal health programs including community health worker training, facility strengthening, and referral systems.',
                'objectives' => "• Train community health workers on maternal health\n• Strengthen emergency obstetric care facilities\n• Establish referral transport systems\n• Provide essential maternal health commodities\n• Conduct community awareness campaigns",
                'scope' => 'Focus on high-burden counties in Jonglei, Lakes, and Eastern Equatoria states.',
                'start_date' => '2023-07-01',
                'end_date' => '2025-06-30',
                'auto_renew' => false,
                'value' => 750000.00,
                'resources_committed' => "Medical equipment, training facilities, community health worker incentives, monitoring support.",
            ],
            [
                'title' => 'Health Workforce Development Partnership',
                'agreement_type' => 'mou',
                'description' => 'Memorandum of understanding for joint health workforce development initiatives including pre-service training, continuing education, and capacity building programs.',
                'objectives' => "• Support medical education programs\n• Provide continuing professional development\n• Develop health worker training curricula\n• Establish mentorship programs\n• Support health worker retention initiatives",
                'scope' => 'National coverage through University of Juba and state training institutions.',
                'start_date' => '2023-01-01',
                'end_date' => '2027-12-31',
                'auto_renew' => true,
                'renewal_period_months' => 36,
                'value' => 300000.00,
                'resources_committed' => "Training materials, faculty support, student scholarships, clinical training sites.",
            ],
            [
                'title' => 'Emergency Health Response Partnership',
                'agreement_type' => 'collaboration_agreement',
                'description' => 'Agreement for coordinated emergency health response including disease outbreak control, humanitarian health interventions, and crisis response coordination.',
                'objectives' => "• Coordinate emergency health response\n• Preposition emergency medical supplies\n• Train emergency response teams\n• Establish rapid response mechanisms\n• Support disease surveillance",
                'scope' => 'Nationwide emergency preparedness and response capacity.',
                'start_date' => '2024-01-01',
                'end_date' => null,
                'auto_renew' => true,
                'renewal_period_months' => 12,
                'value' => 200000.00,
                'resources_committed' => "Emergency medical kits, response team support, coordination mechanisms.",
            ],
            [
                'title' => 'Research and Innovation Partnership',
                'agreement_type' => 'mou',
                'description' => 'Memorandum of understanding for collaborative health research including operational research, impact evaluations, and knowledge translation activities.',
                'objectives' => "• Conduct health systems research\n• Evaluate program effectiveness\n• Develop research capacity\n• Publish and disseminate findings\n• Support evidence-based policy",
                'scope' => 'Research activities across all program areas with focus on generating evidence for policy.',
                'start_date' => '2023-06-01',
                'end_date' => '2026-05-31',
                'auto_renew' => true,
                'renewal_period_months' => 24,
                'value' => 150000.00,
                'resources_committed' => "Research expertise, data analysis support, publication assistance, research infrastructure.",
            ],
            [
                'title' => 'Community Health Program Partnership',
                'agreement_type' => 'contract',
                'description' => 'Contract agreement for implementation of community health programs including community health worker networks, health promotion, and community-based service delivery.',
                'objectives' => "• Establish community health worker networks\n• Implement health promotion activities\n• Provide community-based health services\n• Strengthen community-facility linkages\n• Support community health governance",
                'scope' => 'Community health programming in 50 communities across five states.',
                'start_date' => '2024-03-01',
                'end_date' => '2025-02-28',
                'auto_renew' => false,
                'value' => 400000.00,
                'resources_committed' => "Community health worker training, supplies, supervision, community engagement support.",
            ],
            [
                'title' => 'Malaria Prevention and Control Partnership',
                'agreement_type' => 'mou',
                'description' => 'Partnership for malaria prevention and control including net distribution, indoor residual spraying, case management, and surveillance strengthening.',
                'objectives' => "• Distribute insecticide-treated nets\n• Conduct indoor residual spraying\n• Strengthen malaria case management\n• Improve malaria surveillance\n• Support community malaria education",
                'scope' => 'High malaria burden areas in Upper Nile, Jonglei, and Central Equatoria.',
                'start_date' => '2024-01-01',
                'end_date' => '2025-12-31',
                'auto_renew' => true,
                'renewal_period_months' => 24,
                'value' => 600000.00,
                'resources_committed' => "ITNs, IRS equipment and chemicals, antimalarial drugs, training materials.",
            ],
            [
                'title' => 'HIV/AIDS Program Collaboration',
                'agreement_type' => 'collaboration_agreement',
                'description' => 'Collaboration agreement for HIV prevention, testing, treatment, and care services including community-based testing, ART scale-up, and support services.',
                'objectives' => "• Expand HIV testing services\n• Increase ART coverage\n• Provide prevention services\n• Support PLHIV networks\n• Reduce HIV stigma",
                'scope' => 'HIV programming in Central Equatoria, Western Equatoria, and Eastern Equatoria.',
                'start_date' => '2023-10-01',
                'end_date' => '2025-09-30',
                'auto_renew' => false,
                'value' => 450000.00,
                'resources_committed' => "Test kits, ARVs, prevention commodities, support group facilitation.",
            ],
            [
                'title' => 'Mental Health Integration Partnership',
                'agreement_type' => 'mou',
                'description' => 'Memorandum of understanding for mental health integration into primary healthcare including training, service delivery, and community awareness.',
                'objectives' => "• Train health workers on mental health\n• Integrate mental health in PHC\n• Establish community support groups\n• Raise mental health awareness\n• Develop referral pathways",
                'scope' => 'Mental health services in Juba, Wau, and Malakal.',
                'start_date' => '2024-04-01',
                'end_date' => '2026-03-31',
                'auto_renew' => true,
                'renewal_period_months' => 24,
                'value' => 200000.00,
                'resources_committed' => "Training curriculum, psychotropic medicines, supervision support, community awareness materials.",
            ],
            [
                'title' => 'WASH in Healthcare Facilities Partnership',
                'agreement_type' => 'collaboration_agreement',
                'description' => 'Partnership for improving water, sanitation, and hygiene in healthcare facilities including infrastructure, behavior change, and sustainability.',
                'objectives' => "• Construct water points at facilities\n• Build sanitation facilities\n• Promote hygiene practices\n• Train facility staff on WASH\n• Ensure sustainable WASH services",
                'scope' => 'WASH improvements in 100 healthcare facilities across South Sudan.',
                'start_date' => '2024-02-01',
                'end_date' => '2025-01-31',
                'auto_renew' => false,
                'value' => 350000.00,
                'resources_committed' => "Borehole drilling, latrine construction, water treatment systems, hygiene supplies.",
            ],
            [
                'title' => 'Youth Health Program Partnership',
                'agreement_type' => 'mou',
                'description' => 'Memorandum of understanding for youth health programs including adolescent-friendly services, peer education, and youth engagement in health.',
                'objectives' => "• Establish youth-friendly services\n• Train peer educators\n• Develop youth health curriculum\n• Engage youth in health advocacy\n• Support youth health networks",
                'scope' => 'Youth programming in schools and communities across Central Equatoria.',
                'start_date' => '2024-01-15',
                'end_date' => '2025-01-14',
                'auto_renew' => true,
                'renewal_period_months' => 12,
                'value' => 100000.00,
                'resources_committed' => "Training materials, peer educator support, youth-friendly corners, engagement activities.",
            ],
            [
                'title' => 'Supply Chain Strengthening Partnership',
                'agreement_type' => 'contract',
                'description' => 'Contract for strengthening health supply chain including warehousing, distribution, and last-mile delivery of essential health commodities.',
                'objectives' => "• Strengthen warehouse management\n• Improve distribution systems\n• Ensure last-mile delivery\n• Implement inventory management\n• Reduce stockouts",
                'scope' => 'Supply chain improvements at national and state levels.',
                'start_date' => '2023-09-01',
                'end_date' => '2025-08-31',
                'auto_renew' => false,
                'value' => 800000.00,
                'resources_committed' => "Warehousing infrastructure, transport, logistics management systems, capacity building.",
            ],
        ];

        $created = 0;
        foreach ($partnerships as $index => $partnership) {
            if (empty($partners)) continue;
            
            $partner = is_array($partners) ? $partners[$index % count($partners)] : $partners[$index % count($partners)];
            $partnerId = is_object($partner) ? $partner->id : $partner['id'] ?? 1;
            
            RPartnership::create([
                'partner_id' => $partnerId,
                'title' => $partnership['title'],
                'agreement_type' => $partnership['agreement_type'],
                'description' => $partnership['description'],
                'objectives' => $partnership['objectives'],
                'scope' => $partnership['scope'],
                'start_date' => $partnership['start_date'],
                'end_date' => $partnership['end_date'],
                'auto_renew' => $partnership['auto_renew'],
                'renewal_period_months' => $partnership['renewal_period_months'] ?? null,
                'value' => $partnership['value'],
                'currency' => 'USD',
                'resources_committed' => $partnership['resources_committed'],
                'status' => 'active',
                'signed_date' => date('Y-m-d', strtotime($partnership['start_date'] . ' -30 days')),
                'manager_id' => $users->random()->id,
                'created_at' => now()->subDays(rand(30, 365)),
            ]);
            $created++;
        }

        $this->command->info("Created {$created} partnership agreements.");
    }

    /**
     * Seed forum threads and replies.
     */
    protected function seedForumThreads($users, $partners): void
    {
        $threads = [
            [
                'title' => 'Best Practices for Telemedicine Implementation in Remote Areas',
                'slug' => 'best-practices-telemedicine-remote-areas',
                'content' => "Colleagues, I wanted to start a discussion on telemedicine implementation in remote areas of South Sudan. We've been piloting teleconsultations in three facilities in Jonglei State and wanted to share our experiences and learn from others.\n\nKey challenges we've faced:\n1. Internet connectivity is unreliable\n2. Health workers need extensive training\n3. Patient acceptance varies by community\n4. Equipment maintenance is difficult\n\nWhat has worked well:\n- Using offline-capable applications\n- Simple consultation protocols\n- Community sensitization before launch\n- Regular supervision visits\n\nI'd love to hear from others who have implemented similar programs. What challenges did you face and how did you overcome them?\n\nLet's share best practices to improve digital health in South Sudan.",
                'category' => 'best_practices',
                'visibility' => 'public',
                'tags' => json_encode(['telemedicine', 'digital health', 'remote areas', 'best practices']),
            ],
            [
                'title' => 'Community Health Worker Incentive Models - What Works?',
                'slug' => 'chw-incentive-models-discussion',
                'content' => "We've been struggling with community health worker retention in our program. Despite training and supervision, many CHWs leave after 6-12 months. This affects program continuity and community trust.\n\nI'm interested in learning about different incentive models being used across South Sudan:\n\n1. What financial incentives are programs providing?\n2. How do you handle non-monetary incentives?\n3. What career development pathways exist?\n4. How do you measure CHW satisfaction?\n\nIn our program, we provide monthly stipends, but it seems insufficient compared to other opportunities. Some CHWs have mentioned they would value:\n- Transportation support (bicycles/motorcycles)\n- Mobile phones and airtime\n- Opportunities for formal health training\n- Recognition programs\n\nPlease share your experiences and suggestions. This is a critical issue for sustainable community health programming.",
                'category' => 'questions',
                'visibility' => 'public',
                'tags' => json_encode(['community health workers', 'incentives', 'human resources', 'retention']),
            ],
            [
                'title' => 'Upcoming Health Partners Coordination Meeting - January 2025',
                'slug' => 'health-partners-coordination-january-2025',
                'content' => "Dear Partners,\n\nThis is to invite you to the quarterly Health Partners Coordination Meeting scheduled for January 15, 2025, at 9:00 AM at the Ministry of Health Conference Hall in Juba.\n\nAgenda:\n1. Review of Q4 2024 health sector performance\n2. Discussion of 2025 annual operational plans\n3. Disease surveillance update (malaria, cholera, measles)\n4. Health cluster coordination updates\n5. Partner presentations on innovative programs\n6. AOB\n\nAll partners are encouraged to prepare a 5-minute presentation on your organization's key achievements and planned activities for 2025.\n\nPlease confirm attendance by January 10, 2025, by contacting the coordination office.\n\nMeeting materials will be shared in advance. Let's work together for better health outcomes in South Sudan.",
                'category' => 'announcements',
                'visibility' => 'public',
                'tags' => json_encode(['coordination', 'meeting', 'partners', 'ministry of health']),
            ],
            [
                'title' => 'Mental Health Integration into Primary Care - Sharing Our Experience',
                'slug' => 'mental-health-integration-primary-care',
                'content' => "Our organization has been implementing mental health integration into primary healthcare for the past 18 months. I wanted to share our experience and lessons learned.\n\nThe Model:\nWe trained 30 primary care workers using the WHO mhGAP curriculum. They now screen patients for depression, anxiety, and trauma, and provide basic mental health care.\n\nResults:\n- Over 2,000 patients screened\n- 350 patients receiving mental health support\n- Significant reduction in stigma observed\n- Improved patient outcomes for chronic conditions (better adherence)\n\nChallenges:\n1. Initial resistance from health workers\n2. Stigma in communities\n3. Limited psychotropic medication availability\n4. Need for ongoing supervision\n\nRecommendations for others:\n- Start with intensive training and follow-up\n- Engage community leaders first\n- Establish referral pathways before launching\n- Document everything for learning\n\nHappy to answer questions or provide more details on our implementation approach.",
                'category' => 'best_practices',
                'visibility' => 'public',
                'tags' => json_encode(['mental health', 'primary care', 'integration', 'mhGAP']),
            ],
            [
                'title' => 'Digital Health Literacy Training Materials - Request for Sharing',
                'slug' => 'digital-health-literacy-training-materials',
                'content' => "Colleagues,\n\nWe are planning to conduct digital health literacy training for 100 healthcare workers in our project areas. Before developing new materials from scratch, I wanted to reach out to see if any partners have existing training materials they would be willing to share.\n\nWe're particularly looking for:\n1. Basic digital skills curriculum for health workers\n2. Mobile data collection training guides\n3. Telemedicine user guides (in simple language)\n4. Data protection and privacy modules\n5. Pre/post training assessment tools\n\nWe are happy to adapt materials with proper attribution. In return, we can share our adapted versions and any new materials we develop.\n\nIf you have materials to share or know of good open-access resources, please respond to this thread or contact me directly.\n\nLet's avoid duplication and work smarter together!",
                'category' => 'resources',
                'visibility' => 'public',
                'tags' => json_encode(['digital health', 'training materials', 'health literacy', 'resources']),
            ],
            [
                'title' => 'Emergency Response to Disease Outbreaks - Coordination Mechanisms',
                'slug' => 'emergency-response-disease-outbreaks-coordination',
                'content' => "Given the frequent disease outbreaks in South Sudan (cholera, measles, malaria), I believe we need to discuss and strengthen our coordination mechanisms.\n\nCurrent challenges:\n1. Delayed information sharing between partners\n2. Duplication of response efforts\n3. Gaps in geographic coverage\n4. Inconsistent reporting formats\n5. Limited pre-positioned supplies\n\nProposed solutions for discussion:\n1. Establish a partner WhatsApp/Signal group for rapid alerts\n2. Develop standardized outbreak response protocols\n3. Create a shared mapping tool for response coverage\n4. Agree on common reporting templates\n5. Conduct joint simulation exercises\n\nI propose we form a working group to develop these mechanisms. Who would be interested in participating?\n\nWe cannot prevent all outbreaks, but we can respond faster and more effectively through better coordination.",
                'category' => 'collaboration',
                'visibility' => 'public',
                'tags' => json_encode(['emergency response', 'outbreak', 'coordination', 'disease surveillance']),
            ],
            [
                'title' => 'Funding Opportunity: Digital Health Innovation Grants',
                'slug' => 'funding-opportunity-digital-health-innovation',
                'content' => "Dear Partners,\n\nI'm pleased to share information about a funding opportunity that may be of interest to organizations working on digital health innovations.\n\n**Digital Health Innovation Grants**\nDeadline: February 28, 2025\nFunding Range: $50,000 - $200,000\nDuration: 12-24 months\n\nFocus Areas:\n- Telemedicine expansion to underserved areas\n- Mobile health applications for community health\n- Health information systems strengthening\n- Digital health workforce capacity building\n- Innovative financing for digital health\n\nEligibility:\n- Registered organizations working in South Sudan\n- Demonstrated experience in health programming\n- Technical capacity for digital innovation\n- Partnerships with Ministry of Health preferred\n\nApplication Process:\n1. Concept note submission (5 pages)\n2. Full proposal (if shortlisted)\n3. Partner interviews\n\nFor more information and application guidelines, please contact the coordination office.\n\nThis is a great opportunity to scale up digital health innovations. Please share with relevant colleagues.",
                'category' => 'opportunities',
                'visibility' => 'public',
                'tags' => json_encode(['funding', 'digital health', 'innovation', 'grants']),
            ],
            [
                'title' => 'Maternal Health Referral Systems - Challenges and Solutions',
                'slug' => 'maternal-health-referral-systems-challenges',
                'content' => "I want to discuss the challenges with maternal health referral systems in South Sudan and brainstorm potential solutions.\n\nCurrent situation:\nIn our project area, pregnant women with complications often cannot reach facilities in time. The referral system is broken at multiple levels.\n\nKey problems:\n1. No ambulances available at most facilities\n2. No communication system between facilities\n3. Communities don't know when to refer\n4. Transport costs are prohibitive\n5. Roads are often impassable\n\nWhat we've tried:\n- Motorcycle ambulances (limited success - can't carry women in labor)\n- Community transport funds (sustainability issues)\n- Radio communication (works but limited coverage)\n\nI'm interested in learning about innovative referral solutions that others have implemented. Has anyone had success with:\n- Mobile phone-based alert systems?\n- Community transport cooperatives?\n- Facility-based waiting homes?\n- Air transport partnerships?\n\nLet's share ideas and potentially collaborate on improved referral systems.",
                'category' => 'questions',
                'visibility' => 'public',
                'tags' => json_encode(['maternal health', 'referral systems', 'emergency transport', 'innovation']),
            ],
            [
                'title' => 'Health Data Quality Improvement - A Collaborative Approach',
                'slug' => 'health-data-quality-improvement-collaborative',
                'content' => "Quality data is essential for effective health programming and decision-making. However, data quality remains a significant challenge in South Sudan.\n\nCommon data quality issues:\n1. Incomplete reporting (missing facilities)\n2. Inaccurate data (reporting errors)\n3. Inconsistent definitions across partners\n4. Delayed submission\n5. Limited verification mechanisms\n\nWe propose a collaborative approach to improve data quality:\n\n1. Joint Data Quality Audits\n- Conduct quarterly audits across partner facilities\n- Share findings and develop improvement plans\n- Harmonize indicators and definitions\n\n2. Capacity Building\n- Train facility staff on data collection\n- Develop job aids and standard operating procedures\n- Mentoring and supportive supervision\n\n3. Technology Solutions\n- Expand mobile reporting tools\n- Implement data validation checks\n- Create dashboards for feedback\n\nWho would be interested in participating in a data quality improvement working group? We could start with a pilot in one state and expand.\n\nBetter data means better programs and better health outcomes.",
                'category' => 'collaboration',
                'visibility' => 'public',
                'tags' => json_encode(['data quality', 'HMIS', 'monitoring', 'collaboration']),
            ],
            [
                'title' => 'Community Engagement in Health Programs - Success Stories',
                'slug' => 'community-engagement-success-stories',
                'content' => "I wanted to start a thread for sharing community engagement success stories. When communities are truly engaged, health programs are much more effective.\n\nOur success story:\nIn Wau County, we were struggling with low immunization coverage. Traditional approaches weren't working. We decided to try something different.\n\nWhat we did:\n1. Identified and engaged key community influencers (religious leaders, women leaders, youth)\n2. Held community dialogues to understand barriers\n3. Worked with communities to develop local solutions\n4. Established community health committees\n5. Celebrated small wins publicly\n\nResults:\n- Immunization coverage increased from 35% to 75% in 12 months\n- Community now monitors and reports on health activities\n- Sustainable community structures established\n- Word spread to neighboring communities\n\nKey lessons:\n- Listen before acting\n- Build on existing community structures\n- Be patient with process\n- Share credit with community\n\nPlease share your community engagement success stories. What approaches worked in your context?",
                'category' => 'best_practices',
                'visibility' => 'public',
                'tags' => json_encode(['community engagement', 'immunization', 'success stories', 'participation']),
            ],
            [
                'title' => 'Health Worker Safety During Disease Outbreaks',
                'slug' => 'health-worker-safety-disease-outbreaks',
                'content' => "The safety of our health workers during disease outbreaks is paramount. I want to discuss measures we can take to protect them.\n\nRecent concerns:\nDuring the recent measles outbreak response, several health workers were exposed due to inadequate PPE and training. This should not happen.\n\nEssential safety measures:\n1. Adequate PPE provision and training\n2. Vaccination of health workers (where applicable)\n3. Clear infection prevention protocols\n4. Mental health support\n5. Insurance/compensation mechanisms\n\nQuestions for discussion:\n1. What PPE standards do different partners use?\n2. Do you have health worker insurance programs?\n3. How do you support health worker mental health?\n4. What training do you provide on infection prevention?\n5. Are there standard operating procedures we can harmonize?\n\nI propose we develop minimum standards for health worker safety that all partners can adopt. No health worker should be endangered while serving their communities.\n\nPlease share your current practices and suggestions.",
                'category' => 'general',
                'visibility' => 'public',
                'tags' => json_encode(['health worker safety', 'PPE', 'infection prevention', 'outbreak response']),
            ],
            [
                'title' => 'Partnership for Capacity Building in Laboratory Services',
                'slug' => 'partnership-laboratory-services-capacity',
                'content' => "Laboratory services are critical for diagnosis and treatment, yet remain underdeveloped in South Sudan. I'm looking for partners interested in collaborating on laboratory capacity building.\n\nCurrent situation:\n- Most primary facilities have no laboratory\n- Limited diagnostic capacity at county level\n- Quality assurance systems weak\n- Laboratory technician shortage\n- Equipment maintenance challenges\n\nWhat we're planning:\n1. Upgrade 10 county laboratories with basic equipment\n2. Train laboratory technicians\n3. Establish sample referral networks\n4. Implement quality management systems\n5. Strengthen supply chain for lab commodities\n\nLooking for partners who can contribute:\n- Laboratory equipment\n- Training expertise\n- Quality management experience\n- Supply chain support\n- Monitoring and evaluation\n\nIf your organization has laboratory expertise or complementary programs, let's discuss collaboration. Together we can build a stronger diagnostic network.\n\nPlease contact me directly or respond to this thread.",
                'category' => 'collaboration',
                'visibility' => 'public',
                'tags' => json_encode(['laboratory', 'diagnostics', 'capacity building', 'partnership']),
            ],
            [
                'title' => 'Upcoming Training: Leadership and Management for Health Managers',
                'slug' => 'training-leadership-management-health-managers',
                'content' => "Dear Partners,\n\nWe are pleased to announce an upcoming training opportunity for health managers.\n\n**Leadership and Management for Health Managers**\nDates: February 5-16, 2025\nLocation: Juba, South Sudan\nFacilitators: Regional health management experts\n\nCourse Content:\n- Health systems thinking\n- Leadership styles and team management\n- Planning and budgeting for health programs\n- Performance monitoring and quality improvement\n- Communication and coordination\n- Change management\n\nTarget Participants:\n- County Health Directors\n- Facility In-charges\n- Program Managers\n- Health team leaders\n\nCost: Tuition covered for nominated participants. Partners are responsible for participant transport and accommodation.\n\nNomination Process:\nPlease submit nominations by January 20, 2025. Include:\n- Participant name and position\n- Brief justification for nomination\n- Contact information\n\nThis is an excellent opportunity to build leadership capacity within our health workforce. Please share with relevant colleagues.\n\nFor nominations and inquiries, contact the training coordination office.",
                'category' => 'events',
                'visibility' => 'public',
                'tags' => json_encode(['training', 'leadership', 'health management', 'capacity building']),
            ],
            [
                'title' => 'Adolescent Health Program Design - Input Needed',
                'slug' => 'adolescent-health-program-design-input',
                'content' => "We are designing a new adolescent health program and would value input from partners with relevant experience.\n\nProposed program components:\n1. School-based health education\n2. Youth-friendly health services\n3. Peer education networks\n4. Community support for adolescent health\n5. Advocacy for adolescent health policies\n\nQuestions for partners:\n1. What has worked well in your adolescent health programs?\n2. How do you engage out-of-school youth?\n3. What services are most demanded by adolescents?\n4. How do you address sensitive topics (SRH, substance use)?\n5. What partnerships have been most valuable?\n\nWe particularly want to learn about:\n- Effective peer education models\n- Youth-friendly service approaches\n- Community acceptance strategies\n- Sustainability mechanisms\n\nYour input will help shape a program that truly meets adolescent needs. Please share your experiences and suggestions.\n\nWe're also open to collaboration with partners who have complementary adolescent health initiatives.",
                'category' => 'questions',
                'visibility' => 'public',
                'tags' => json_encode(['adolescent health', 'youth', 'program design', 'peer education']),
            ],
            [
                'title' => 'Quarterly Program Review Meeting - Sharing Format and Tools',
                'slug' => 'quarterly-program-review-format-tools',
                'content' => "I wanted to share our quarterly program review format in case it's useful for other partners. We've refined this over two years and found it effective for learning and improvement.\n\n**Quarterly Program Review Format**\n\n1. Achievement Summary (2 pages)\n   - Key indicators vs targets\n   - Highlights and lowlights\n   - Success stories\n\n2. Financial Summary (1 page)\n   - Budget vs actual\n   - Variance explanation\n\n3. Challenges and Lessons Learned (1 page)\n   - Top 3 challenges\n   - Root causes\n   - Mitigation actions\n\n4. Next Quarter Plan (2 pages)\n   - Priority activities\n   - Resource requirements\n   - Risk mitigation\n\nReview Meeting Agenda:\n- Presentation (30 min)\n- Discussion (30 min)\n- Action items (15 min)\n\nTools we use:\n- Dashboard for indicators\n- Standardized reporting template\n- Action tracking spreadsheet\n\nBenefits we've seen:\n- Improved accountability\n- Better problem-solving\n- Team learning\n- Stakeholder confidence\n\nI'm happy to share our templates if anyone is interested. Also curious what formats others use for program reviews.\n\nContinuous improvement requires structured reflection.",
                'category' => 'resources',
                'visibility' => 'public',
                'tags' => json_encode(['program review', 'monitoring', 'tools', 'templates']),
            ],
        ];

        $createdThreads = [];
        $created = 0;
        foreach ($threads as $thread) {
            $model = RForumThread::firstOrCreate(
                ['slug' => $thread['slug']],
                [
                    'user_id' => $users->random()->id,
                    'title' => $thread['title'],
                    'slug' => $thread['slug'],
                    'content' => $thread['content'],
                    'category' => $thread['category'],
                    'visibility' => $thread['visibility'],
                    'status' => 'open',
                    'is_locked' => false,
                    'is_pinned' => in_array($thread['category'], ['announcements', 'opportunities']),
                    'is_featured' => false,
                    'is_approved' => true,
                    'approved_by' => $users->random()->id,
                    'approved_at' => now()->subDays(rand(5, 60)),
                    'tags' => $thread['tags'],
                    'views_count' => rand(50, 500),
                    'replies_count' => rand(1, 8),
                    'created_at' => now()->subDays(rand(15, 180)),
                ]
            );
            $createdThreads[] = $model;
            if ($model->wasRecentlyCreated) {
                $created++;
            }
        }

        $this->command->info("Created {$created} forum threads.");

        // Seed forum replies
        $this->seedForumReplies($users, $createdThreads);
    }

    /**
     * Seed forum replies.
     */
    protected function seedForumReplies($users, $threads): void
    {
        $replies = [
            "Thank you for sharing this valuable information. We've had similar experiences in our program and found that community engagement is key to success. Would love to discuss further.",
            "This is a great initiative. Our organization has been working on similar challenges and we've found that involving local leadership from the start makes a significant difference.",
            "Excellent post! I particularly agree with your point about sustainability. Too often, programs end when funding ends. Building community ownership is essential.",
            "We implemented a similar approach in our project area last year. The results were encouraging - we saw a 40% improvement in outcomes. Happy to share our detailed findings.",
            "This discussion is very timely. We've been grappling with these same issues and it's helpful to see how others are approaching them. Collaboration would definitely benefit all of us.",
            "Great insights shared here. I would add that regular follow-up and supportive supervision are critical components that often get overlooked.",
            "Thank you for raising this important topic. Our experience suggests that investing in capacity building of local staff yields the best long-term returns.",
            "This aligns well with the Ministry's strategic priorities. I encourage all partners to coordinate their approaches through the existing coordination mechanisms.",
            "Very practical suggestions. We've incorporated some of these approaches and seen improvements in our program indicators. Sharing experiences like this really helps.",
            "Excellent analysis. The challenges you've identified are common across many project areas. Perhaps we could organize a learning session to share solutions more systematically.",
            "I appreciate you sharing this openly. Learning from each other's successes and failures is how we improve as a sector. More posts like this please!",
            "This is exactly the kind of collaboration we need. Our organization would be interested in participating in any working group or joint initiatives that come out of this discussion.",
        ];

        $created = 0;
        foreach ($threads as $thread) {
            if (!$thread->wasRecentlyCreated) {
                continue;
            }
            $numReplies = rand(2, 6);
            for ($i = 0; $i < $numReplies; $i++) {
                RForumReply::create([
                    'thread_id' => $thread->id,
                    'user_id' => $users->random()->id,
                    'parent_id' => null,
                    'content' => $replies[array_rand($replies)],
                    'status' => 'published',
                    'is_approved' => true,
                    'helpful_count' => rand(0, 15),
                    'is_best_answer' => $i === 0 && rand(0, 1),
                    'created_at' => now()->subDays(rand(5, 90)),
                ]);
                $created++;
            }
        }

        $this->command->info("Created {$created} forum replies.");
    }
}
