<?php

namespace Database\Seeders;

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

/**
 * Seeder: RPartnershipDataSeeder
 * 
 * Seeds comprehensive partnership data for SSHIA.
 * Includes partners, partnerships (MOUs), and forum discussions.
 * 
 * @author SSHIA Development Team
 * @version 1.0.0
 */
class RPartnershipDataSeeder extends Seeder
{
    protected int $authorId;
    protected $now;

    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $this->command->info('Seeding Partnership & Collaboration Portal data...');

        $this->authorId = DB::table('users')->first()->id ?? 1;
        $this->now = now();

        // Create Partners
        $partners = $this->createPartners();

        // Create Partner Contacts
        $this->createPartnerContacts($partners);

        // Create Partnerships (MOUs)
        $this->createPartnerships($partners);

        // Create Forum Threads
        $this->createForumThreads();

        $this->command->info('Partnership & Collaboration Portal data seeded successfully!');
    }

    /**
     * Create partner organizations.
     */
    protected function createPartners(): array
    {
        $partners = [];
        $now = $this->now;

        $partnersData = [
            [
                'organization_name' => 'World Health Organization - South Sudan',
                'slug' => 'who-south-sudan',
                'legal_name' => 'World Health Organization Country Office for South Sudan',
                'description' => 'The World Health Organization (WHO) is the directing and coordinating authority for health within the United Nations system. The South Sudan Country Office works closely with the Ministry of Health and partners to strengthen health systems, respond to health emergencies, and improve health outcomes for all South Sudanese people.',
                'mission_statement' => 'To promote health, keep the world safe, and serve the vulnerable in South Sudan through evidence-based policies, technical support, and partnership coordination.',
                'email' => 'southsudan@who.int',
                'phone' => '+211 922 100 100',
                'website' => 'https://www.who.int/countries/ssd',
                'address_line_1' => 'UN House Compound',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'international',
                'category' => 'Public Health',
                'partnership_status' => 'active',
                'partnership_level' => 'platinum',
                'partnership_start_date' => $now->copy()->subYears(10)->format('Y-m-d'),
                'services_offered' => ['Technical Assistance', 'Health Policy Development', 'Disease Surveillance', 'Emergency Response', 'Capacity Building'],
                'social_media' => ['twitter' => '@WHOSouthSudan', 'facebook' => 'WHOSouthSudan'],
                '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, ensure their survival and development, and create a world where every child can thrive. UNICEF South Sudan implements programs in health, nutrition, education, child protection, and water, sanitation and hygiene (WASH) across all 10 states.',
                'mission_statement' => 'To advocate for the protection of children\'s rights, to help meet their basic needs and to expand their opportunities to reach their full potential.',
                'email' => 'juba@unicef.org',
                'phone' => '+211 922 100 200',
                'website' => 'https://www.unicef.org/southsudan',
                'address_line_1' => 'UN House Compound',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'international',
                'category' => 'Child Welfare & Development',
                'partnership_status' => 'active',
                'partnership_level' => 'platinum',
                'partnership_start_date' => $now->copy()->subYears(12)->format('Y-m-d'),
                'services_offered' => ['Child Health', 'Immunization', 'Nutrition Programs', 'Education', 'Child Protection', 'WASH'],
                'social_media' => ['twitter' => '@UNICEFSouthSudan', 'facebook' => 'UNICEFSouthSudan'],
                '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 (CRS) has been working in South Sudan since 1983, providing humanitarian assistance and supporting long-term development. CRS implements programs in health, agriculture, peacebuilding, and emergency response, reaching vulnerable communities across the country.',
                'mission_statement' => 'To assist impoverished and disadvantaged people overseas, working in the spirit of Catholic social teaching to promote the sacredness of human life and the dignity of the human person.',
                'email' => 'juba@crs.org',
                'phone' => '+211 922 100 300',
                'website' => 'https://www.crs.org/our-work-overseas/where-we-work/south-sudan',
                'address_line_1' => 'Hai Jerusalem',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'ngo',
                'category' => 'Humanitarian & Development',
                'partnership_status' => 'active',
                'partnership_level' => 'gold',
                'partnership_start_date' => $now->copy()->subYears(8)->format('Y-m-d'),
                'services_offered' => ['Health Programming', 'Food Security', 'Peace Building', 'Emergency Response', 'Agriculture'],
                'social_media' => ['twitter' => '@CatholicRelief', 'facebook' => 'catholicreliefservices'],
                'is_verified' => true,
                'is_featured' => true,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'International Rescue Committee - South Sudan',
                'slug' => 'irc-south-sudan',
                'legal_name' => 'International Rescue Committee South Sudan Country Program',
                'description' => 'The International Rescue Committee (IRC) has been working in South Sudan since 1989, providing critical support to civilians affected by conflict and displacement. IRC delivers health, nutrition, protection, and livelihoods services in some of the most hard-to-reach areas of the country.',
                'mission_statement' => 'To help people whose lives and livelihoods are shattered by conflict and disaster to survive, recover and gain control of their future.',
                'email' => 'southsudan@rescue.org',
                'phone' => '+211 922 100 400',
                'website' => 'https://www.rescue.org/country/south-sudan',
                'address_line_1' => 'Hai Cinema',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'ngo',
                'category' => 'Humanitarian Assistance',
                'partnership_status' => 'active',
                'partnership_level' => 'gold',
                'partnership_start_date' => $now->copy()->subYears(6)->format('Y-m-d'),
                'services_offered' => ['Primary Healthcare', 'Nutrition', 'Gender-Based Violence Response', 'Child Protection', 'Economic Recovery'],
                'social_media' => ['twitter' => '@theIRC', 'facebook' => 'InternationalRescueCommittee'],
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'Medecins Sans Frontieres (MSF)',
                'slug' => 'msf-south-sudan',
                'legal_name' => 'Medecins Sans Frontieres South Sudan Mission',
                'description' => 'Medecins Sans Frontieres (Doctors Without Borders) provides emergency medical care in South Sudan, operating hospitals, primary healthcare facilities, and emergency response programs. MSF works in areas with limited healthcare access, providing life-saving services to conflict-affected and displaced populations.',
                'mission_statement' => 'To provide medical care where the need is greatest, delivering emergency medical assistance to people affected by conflict, epidemics, and exclusion from healthcare.',
                'email' => 'juba.mission@msf.org',
                'phone' => '+211 922 100 500',
                'website' => 'https://www.msf.org/south-sudan',
                'address_line_1' => 'Hai Amarat',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'ngo',
                'category' => 'Medical & Healthcare',
                'partnership_status' => 'active',
                'partnership_level' => 'gold',
                'partnership_start_date' => $now->copy()->subYears(7)->format('Y-m-d'),
                'services_offered' => ['Emergency Medical Care', 'Surgery', 'Maternal Health', 'Pediatric Care', 'Disease Outbreak Response'],
                'social_media' => ['twitter' => '@MSF', 'facebook' => 'MSF.USA'],
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'University of Juba - College of Medicine',
                'slug' => 'university-juba-medicine',
                'legal_name' => 'University of Juba, College of Medicine',
                'description' => 'The College of Medicine at the University of Juba is the premier medical education institution in South Sudan, training the next generation of healthcare professionals. The college collaborates with health partners on research, clinical training, and health workforce development.',
                'mission_statement' => 'To produce competent health professionals who will serve the people of South Sudan through quality medical education, research, and community service.',
                'email' => 'medcollege@uoj.edu.ss',
                'phone' => '+211 922 100 600',
                'website' => 'https://www.uoj.edu.ss',
                'address_line_1' => 'Juba University Campus',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'academic',
                'category' => 'Medical Education & Research',
                'partnership_status' => 'active',
                'partnership_level' => 'silver',
                'partnership_start_date' => $now->copy()->subYears(5)->format('Y-m-d'),
                'services_offered' => ['Medical Education', 'Health Research', 'Clinical Training', 'Continuing Medical Education', 'Student Internships'],
                'social_media' => ['twitter' => '@UnivofJuba', 'facebook' => 'UniversityOfJuba'],
                'is_verified' => true,
                'is_featured' => true,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'Ministry of Health - Republic of South Sudan',
                'slug' => 'ministry-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, regulation, and service delivery in South Sudan. The Ministry coordinates with development partners, NGOs, and civil society to achieve national health goals and improve health outcomes for all citizens.',
                'mission_statement' => 'To provide equitable, affordable, and quality health services to all people of South Sudan through a strengthened health system.',
                'email' => 'info@moh.gov.ss',
                'phone' => '+211 922 100 700',
                'website' => 'https://www.moh.gov.ss',
                'address_line_1' => 'Ministry of Health Compound',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'government',
                'category' => 'Government Health Authority',
                'partnership_status' => 'active',
                'partnership_level' => 'platinum',
                'partnership_start_date' => $now->copy()->subYears(15)->format('Y-m-d'),
                'services_offered' => ['Health Policy', 'Regulatory Oversight', 'National Health Programs', 'Health System Strengthening', 'Public Health Emergency Response'],
                'social_media' => ['twitter' => '@MOH_SouthSudan', 'facebook' => 'MOHSouthSudan'],
                '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 has been working in South Sudan since 1989, implementing humanitarian and development programs that reach millions of people. World Vision focuses on health, nutrition, WASH, food security, and child protection, with a special emphasis on reaching the most vulnerable children and families.',
                'mission_statement' => 'To follow our Lord and Savior Jesus Christ in working with the poor and oppressed to promote human transformation, seek justice, and bear witness to the good news of the Kingdom of God.',
                'email' => 'southsudan@wvi.org',
                'phone' => '+211 922 100 800',
                'website' => 'https://www.wvi.org/south-sudan',
                'address_line_1' => 'Hai Amarat',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'ngo',
                'category' => 'Humanitarian & Development',
                'partnership_status' => 'active',
                'partnership_level' => 'gold',
                'partnership_start_date' => $now->copy()->subYears(7)->format('Y-m-d'),
                'services_offered' => ['Health Programs', 'Nutrition', 'WASH', 'Food Security', 'Child Protection', 'Education'],
                'social_media' => ['twitter' => '@WorldVision', 'facebook' => 'WorldVision'],
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'AMREF Health Africa - South Sudan',
                'slug' => 'amref-south-sudan',
                'legal_name' => 'AMREF Health Africa South Sudan Country Office',
                'description' => 'AMREF Health Africa is Africa\'s leading health development organization, working in South Sudan to strengthen health systems and train health workers. AMREF focuses on community health, capacity building, and innovative health solutions tailored to the South Sudan context.',
                'mission_statement' => 'To increase sustainable health access to communities in Africa through solutions in human resources for health, health service delivery, and investments in health.',
                'email' => 'southsudan@amref.org',
                'phone' => '+211 922 100 900',
                'website' => 'https://amref.org/south-sudan/',
                'address_line_1' => 'Hai Malakia',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'ngo',
                'category' => 'Health System Strengthening',
                'partnership_status' => 'active',
                'partnership_level' => 'silver',
                'partnership_start_date' => $now->copy()->subYears(4)->format('Y-m-d'),
                'services_offered' => ['Health Worker Training', 'Community Health', 'Telemedicine', 'Health System Strengthening', 'Research'],
                'social_media' => ['twitter' => '@Amref_Worldwide', 'facebook' => 'AmrefHealthAfrica'],
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'Save the Children - South Sudan',
                'slug' => 'save-children-south-sudan',
                'legal_name' => 'Save the Children International South Sudan Country Office',
                'description' => 'Save the Children has been working in South Sudan since 1991, providing life-saving assistance to children and their families. The organization focuses on health, nutrition, education, child protection, and humanitarian response, ensuring children survive, learn, and are protected.',
                '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 101 000',
                'website' => 'https://www.savethechildren.org/south-sudan',
                'address_line_1' => 'Hai Amarat',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'ngo',
                'category' => 'Child Welfare & Development',
                'partnership_status' => 'active',
                'partnership_level' => 'gold',
                'partnership_start_date' => $now->copy()->subYears(6)->format('Y-m-d'),
                'services_offered' => ['Child Health', 'Nutrition', 'Education', 'Child Protection', 'Humanitarian Response'],
                'social_media' => ['twitter' => '@savechildren', 'facebook' => 'SavetheChildren'],
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'South Sudan Red Cross Society',
                'slug' => 'south-sudan-red-cross',
                'legal_name' => 'South Sudan Red Cross Society',
                'description' => 'The South Sudan Red Cross Society is a humanitarian organization providing emergency response, health services, and community-based programs across South Sudan. With volunteers in all states, the Red Cross plays a critical role in disaster response and community health promotion.',
                'mission_statement' => 'To alleviate human suffering wherever it may be found, to protect life and health, and to ensure respect for the human being.',
                'email' => 'info@ssredcross.org',
                'phone' => '+211 922 101 100',
                'website' => 'https://www.ssredcross.org',
                'address_line_1' => 'Hai Malakia',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'ngo',
                'category' => 'Humanitarian & Emergency',
                'partnership_status' => 'active',
                'partnership_level' => 'silver',
                'partnership_start_date' => $now->copy()->subYears(5)->format('Y-m-d'),
                'services_offered' => ['Emergency Response', 'First Aid Training', 'Community Health', 'Disaster Management', 'Blood Donation'],
                'social_media' => ['twitter' => '@SSRedCross', 'facebook' => 'SouthSudanRedCross'],
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'HealthNet TPO South Sudan',
                'slug' => 'healthnet-tpo-south-sudan',
                'legal_name' => 'HealthNet TPO South Sudan',
                'description' => 'HealthNet TPO works in South Sudan to strengthen health systems and improve access to quality healthcare. The organization specializes in mental health and psychosocial support, primary healthcare, and health system strengthening in underserved areas.',
                'mission_statement' => 'To improve the health of populations in fragile settings through innovative health solutions and system strengthening.',
                'email' => 'southsudan@healthnet-tpo.org',
                'phone' => '+211 922 101 200',
                'website' => 'https://www.healthnet-tpo.org',
                'address_line_1' => 'Hai Amarat',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'ngo',
                'category' => 'Health System Strengthening',
                'partnership_status' => 'active',
                'partnership_level' => 'bronze',
                'partnership_start_date' => $now->copy()->subYears(3)->format('Y-m-d'),
                'services_offered' => ['Mental Health', 'Primary Healthcare', 'Health System Strengthening', 'Training', 'Research'],
                'social_media' => ['twitter' => '@HealthNetTPO', 'facebook' => 'HealthNetTPO'],
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'Johns Hopkins University - Center for Global Health',
                'slug' => 'johns-hopkins-global-health',
                'legal_name' => 'Johns Hopkins University Center for Global Health',
                'description' => 'Johns Hopkins University Center for Global Health collaborates with SSHIA on research initiatives, capacity building, and knowledge exchange. The partnership brings academic expertise to support evidence-based health programming in South Sudan.',
                'mission_statement' => 'To address global health challenges through innovative research, education, and practice, working with partners to improve health outcomes worldwide.',
                'email' => 'globalhealth@jhu.edu',
                'phone' => '+1 410 955 3935',
                'website' => 'https://globalhealth.jhu.edu',
                'address_line_1' => 'Baltimore, Maryland',
                'city' => 'Baltimore',
                'country' => 'United States',
                'organization_type' => 'academic',
                'category' => 'Research & Education',
                'partnership_status' => 'active',
                'partnership_level' => 'silver',
                'partnership_start_date' => $now->copy()->subYears(2)->format('Y-m-d'),
                'services_offered' => ['Research Collaboration', 'Technical Assistance', 'Capacity Building', 'Data Science', 'Publications'],
                'social_media' => ['twitter' => '@JHUGlobalHealth', 'facebook' => 'JohnsHopkinsGlobalHealth'],
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
            [
                'organization_name' => 'Juba Teaching Hospital',
                'slug' => 'juba-teaching-hospital',
                'legal_name' => 'Juba Teaching Hospital',
                'description' => 'Juba Teaching Hospital is the largest referral hospital in South Sudan, providing specialized medical services, training for health professionals, and serving as a primary clinical training site for the University of Juba College of Medicine.',
                'mission_statement' => 'To provide quality specialized healthcare services and serve as a center of excellence for medical education and research in South Sudan.',
                'email' => 'info@jubahospital.gov.ss',
                'phone' => '+211 922 101 300',
                'website' => 'https://www.jubahospital.gov.ss',
                'address_line_1' => 'Hai Malakia',
                'city' => 'Juba',
                'country' => 'South Sudan',
                'organization_type' => 'healthcare',
                'category' => 'Healthcare Facility',
                'partnership_status' => 'active',
                'partnership_level' => 'silver',
                'partnership_start_date' => $now->copy()->subYears(8)->format('Y-m-d'),
                'services_offered' => ['Specialized Medical Care', 'Surgery', 'Maternal Health', 'Pediatric Care', 'Clinical Training'],
                'social_media' => [],
                'is_verified' => true,
                'is_featured' => false,
                'show_in_directory' => true,
            ],
        ];

        foreach ($partnersData as $data) {
            $partner = RPartner::firstOrCreate(
                ['slug' => $data['slug']],
                array_merge($data, [
                    'verified_at' => $data['is_verified'] ? $now->copy()->subYears(1) : null,
                    'verified_by' => $data['is_verified'] ? $this->authorId : null,
                    'created_at' => $now->copy()->subDays(rand(30, 500)),
                    'updated_at' => $now,
                ])
            );
            $partners[] = $partner;
        }

        $this->command->info('- Created ' . count($partners) . ' partner organizations');
        return $partners;
    }

    /**
     * Create partner contacts.
     */
    protected function createPartnerContacts(array $partners): void
    {
        $contactNames = [
            ['name' => 'Dr. Elizabeth Akello', 'title' => 'Health Program Coordinator', 'role' => 'primary_contact'],
            ['name' => 'Mr. James Deng', 'title' => 'Partnership Manager', 'role' => 'administrative'],
            ['name' => 'Dr. Nyibol Akech', 'title' => 'Technical Advisor', 'role' => 'technical'],
            ['name' => 'Ms. Grace Loki', 'title' => 'Communications Officer', 'role' => 'communications'],
            ['name' => 'Dr. Santino Arop', 'title' => 'Executive Director', 'role' => 'executive'],
        ];

        $count = 0;
        foreach ($partners as $index => $partner) {
            // Skip contacts for pre-existing partners
            if (!$partner->wasRecentlyCreated) {
                continue;
            }

            // Primary contact
            $primaryContact = $contactNames[$index % count($contactNames)];
            RPartnerContact::create([
                'partner_id' => $partner->id,
                'name' => $primaryContact['name'],
                'title' => $primaryContact['title'],
                'email' => strtolower(str_replace(' ', '.', $primaryContact['name'])) . '@partner.org',
                'phone' => '+211 92' . rand(1000000, 9999999),
                'role' => $primaryContact['role'],
                'is_primary' => true,
                'is_active' => true,
            ]);
            $count++;

            // Secondary contact
            $secondaryContact = $contactNames[($index + 2) % count($contactNames)];
            RPartnerContact::create([
                'partner_id' => $partner->id,
                'name' => $secondaryContact['name'],
                'title' => $secondaryContact['title'],
                'email' => strtolower(str_replace(' ', '.', $secondaryContact['name'])) . '@partner.org',
                'phone' => '+211 92' . rand(1000000, 9999999),
                'role' => $secondaryContact['role'],
                'is_primary' => false,
                'is_active' => true,
            ]);
            $count++;
        }

        $this->command->info('- Created ' . $count . ' partner contacts');
    }

    /**
     * Create partnerships (MOUs/Agreements).
     */
    protected function createPartnerships(array $partners): void
    {
        $now = $this->now;

        $partnershipsData = [
            [
                'partner_index' => 0,
                'title' => 'Memorandum of Understanding for Health System Strengthening',
                'agreement_type' => 'mou',
                'description' => 'This MOU establishes the framework for collaboration between SSHIA and WHO South Sudan for strengthening health systems, improving service delivery, and coordinating emergency response activities.',
                'objectives' => '1. Strengthen health information systems at national and state levels. 2. Build capacity of health workers through joint training programs. 3. Coordinate emergency response and disease surveillance. 4. Support policy development and implementation.',
                'scope' => 'National coverage with focus on priority states for health system strengthening. Includes technical assistance, capacity building, and resource mobilization.',
                'start_date' => $now->copy()->subYears(3)->format('Y-m-d'),
                'end_date' => $now->copy()->addYears(2)->format('Y-m-d'),
                'auto_renew' => true,
                'renewal_period_months' => 24,
                'value' => 5000000.00,
                'currency' => 'USD',
                'status' => 'active',
                'signed_date' => $now->copy()->subYears(3)->format('Y-m-d'),
                'review_date' => $now->copy()->addMonths(6)->format('Y-m-d'),
            ],
            [
                'partner_index' => 1,
                'title' => 'Partnership Agreement for Maternal and Child Health Program',
                'agreement_type' => 'collaboration_agreement',
                'description' => 'This agreement outlines the collaboration between SSHIA and UNICEF for implementing maternal and child health programs across South Sudan, with focus on immunization, nutrition, and antenatal care.',
                'objectives' => '1. Increase immunization coverage to 80% in target states. 2. Reduce maternal mortality through improved antenatal care. 3. Address acute malnutrition among children under 5. 4. Strengthen community health systems.',
                'scope' => 'Implementation of maternal and child health programs in Jonglei, Unity, Upper Nile, and Central Equatoria states.',
                'start_date' => $now->copy()->subYears(2)->format('Y-m-d'),
                'end_date' => $now->copy()->addYear()->format('Y-m-d'),
                'auto_renew' => true,
                'renewal_period_months' => 12,
                'value' => 3500000.00,
                'currency' => 'USD',
                'status' => 'active',
                'signed_date' => $now->copy()->subYears(2)->format('Y-m-d'),
                'review_date' => $now->copy()->addMonths(3)->format('Y-m-d'),
            ],
            [
                'partner_index' => 8,
                'title' => 'Health Worker Training Partnership',
                'agreement_type' => 'mou',
                'description' => 'MOU for collaboration between SSHIA and AMREF Health Africa for training health workers and strengthening community health programs in South Sudan.',
                'objectives' => '1. Train 1,000 community health workers annually. 2. Develop standardized training curricula. 3. Implement e-learning programs. 4. Support career development pathways.',
                'scope' => 'National health worker training programs with focus on primary healthcare and community health.',
                'start_date' => $now->copy()->subMonths(18)->format('Y-m-d'),
                'end_date' => $now->copy()->addMonths(18)->format('Y-m-d'),
                'auto_renew' => true,
                'renewal_period_months' => 24,
                'value' => 800000.00,
                'currency' => 'USD',
                'status' => 'active',
                'signed_date' => $now->copy()->subMonths(18)->format('Y-m-d'),
                'review_date' => $now->copy()->addMonths(3)->format('Y-m-d'),
            ],
            [
                'partner_index' => 5,
                'title' => 'Research and Academic Collaboration Agreement',
                'agreement_type' => 'collaboration_agreement',
                'description' => 'This agreement establishes a research partnership between SSHIA and University of Juba College of Medicine for collaborative research on health systems and digital health interventions in South Sudan.',
                'objectives' => '1. Conduct joint research on health system challenges. 2. Evaluate digital health interventions. 3. Publish research findings in peer-reviewed journals. 4. Support evidence-based policy development.',
                'scope' => 'Collaborative research, data sharing, publication, and capacity building in research methodology.',
                'start_date' => $now->copy()->subYears(2)->format('Y-m-d'),
                'end_date' => $now->copy()->addYear()->format('Y-m-d'),
                'auto_renew' => true,
                'renewal_period_months' => 12,
                'value' => 500000.00,
                'currency' => 'USD',
                'status' => 'active',
                'signed_date' => $now->copy()->subYears(2)->format('Y-m-d'),
                'review_date' => $now->copy()->addMonths(9)->format('Y-m-d'),
            ],
            [
                'partner_index' => 3,
                'title' => 'GBV Prevention and Response Partnership',
                'agreement_type' => 'moa',
                'description' => 'Partnership agreement between SSHIA and IRC for implementing gender-based violence prevention and response programs across South Sudan.',
                'objectives' => '1. Establish safe spaces for women and girls. 2. Train counselors and case workers. 3. Provide survivor support services. 4. Engage communities in prevention.',
                'scope' => 'GBV prevention and response programming in six states with community-based approach.',
                'start_date' => $now->copy()->subYear()->format('Y-m-d'),
                'end_date' => $now->copy()->addYears(2)->format('Y-m-d'),
                'auto_renew' => true,
                'renewal_period_months' => 24,
                'value' => 1200000.00,
                'currency' => 'USD',
                'status' => 'active',
                'signed_date' => $now->copy()->subYear()->format('Y-m-d'),
                'review_date' => $now->copy()->addMonths(6)->format('Y-m-d'),
            ],
        ];

        $count = 0;
        foreach ($partnershipsData as $data) {
            $partnerIndex = $data['partner_index'];
            unset($data['partner_index']);

            if (isset($partners[$partnerIndex])) {
                RPartnership::create(array_merge($data, [
                    'partner_id' => $partners[$partnerIndex]->id,
                    'manager_id' => $this->authorId,
                    'resources_committed' => 'Staff time, office space, local coordination',
                    'expiry_notification_sent' => false,
                    'created_at' => $now->copy()->subDays(rand(30, 500)),
                    'updated_at' => $now,
                ]));
                $count++;
            }
        }

        $this->command->info('- Created ' . $count . ' partnership agreements');
    }

    /**
     * Create forum threads.
     */
    protected function createForumThreads(): void
    {
        $now = $this->now;

        $threads = [
            [
                'title' => 'Best Practices for Community Health Worker Training in South Sudan',
                'slug' => 'best-practices-chw-training',
                'content' => '<p>Dear Colleagues,</p><p>I wanted to start a discussion on best practices for training community health workers (CHWs) in the South Sudan context. As many of us are involved in CHW programs, sharing our experiences could benefit everyone.</p><p>Some key questions to consider:</p><ul><li>What training methodologies have worked best in your experience?</li><li>How do you ensure knowledge retention over time?</li><li>What refresher training schedules have been effective?</li><li>How do you address language and literacy challenges?</li></ul><p>Please share your insights and experiences. Let\'s learn from each other.</p>',
                'category' => 'best_practices',
                'visibility' => 'public',
                'is_pinned' => true,
            ],
            [
                'title' => 'Digital Health Solutions for Remote Areas',
                'slug' => 'digital-health-remote-areas',
                'content' => '<p>Dear Partners,</p><p>With the increasing interest in digital health solutions, I wanted to open a discussion on implementing technology in areas with limited connectivity and electricity.</p><p>Key challenges we\'ve identified:</p><ul><li>Limited mobile network coverage in many counties</li><li>Unreliable electricity for charging devices</li><li>Digital literacy among health workers</li><li>Data security and privacy concerns</li></ul><p>What solutions have worked in your programs? Are there offline-capable applications you recommend?</p>',
                'category' => 'collaboration',
                'visibility' => 'public',
                'is_pinned' => false,
            ],
            [
                'title' => 'Coordination of Emergency Health Response',
                'slug' => 'coordination-emergency-health-response',
                'content' => '<p>Dear Health Partners,</p><p>Effective coordination during health emergencies is critical. This thread is dedicated to discussing coordination mechanisms, sharing contact information, and establishing communication protocols.</p><p>Topics for discussion:</p><ul><li>Emergency contact lists and how to keep them updated</li><li>Coordination meeting schedules during emergencies</li><li>Information sharing protocols</li><li>Resource mapping and surge capacity</li></ul><p>Please share your organization\'s emergency focal points.</p>',
                'category' => 'general',
                'visibility' => 'partners_only',
                'is_pinned' => true,
            ],
            [
                'title' => 'Mental Health and Psychosocial Support Integration',
                'slug' => 'mhps-integration',
                'content' => '<p>Dear Colleagues,</p><p>As mental health becomes increasingly recognized as essential to overall health, many of us are working to integrate MHPSS into primary healthcare.</p><p>I\'d like to discuss:</p><ul><li>Training approaches for non-specialist workers</li><li>Integration into existing health services</li><li>Referral pathways for severe cases</li><li>Monitoring and evaluation frameworks</li><li>Cultural considerations in MHPSS delivery</li></ul><p>What approaches have worked in your programs?</p>',
                'category' => 'best_practices',
                'visibility' => 'public',
                'is_pinned' => false,
            ],
            [
                'title' => 'Upcoming Health Partner Coordination Meeting',
                'slug' => 'upcoming-partner-meeting',
                'content' => '<p>Dear Partners,</p><p>This is to inform you of the upcoming quarterly health partner coordination meeting.</p><p><strong>Details:</strong></p><ul><li>Date: To be confirmed</li><li>Time: 9:00 AM - 4:00 PM</li><li>Venue: Ministry of Health Conference Hall</li><li>Agenda: Review of Q3 activities, planning for Q4, resource mobilization</li></ul><p>Please confirm attendance and submit agenda items. All partners are encouraged to attend.</p>',
                'category' => 'announcements',
                'visibility' => 'partners_only',
                'is_pinned' => true,
            ],
            [
                'title' => 'Sharing: New Training Materials for CHWs',
                'slug' => 'new-chw-training-materials',
                'content' => '<p>Dear Colleagues,</p><p>I\'m pleased to share new training materials we\'ve developed for community health workers. These materials have been field-tested and adapted for the South Sudan context.</p><p><strong>Materials include:</strong></p><ul><li>CHW Reference Guide (English and local languages)</li><li>Training of Trainers Manual</li><li>Job aids for common health conditions</li><li>Assessment tools and checklists</li></ul><p>The materials are available for download on our website. We welcome feedback.</p>',
                'category' => 'resources',
                'visibility' => 'public',
                'is_pinned' => false,
            ],
            [
                'title' => 'Request for Information: Nutrition Program Implementation',
                'slug' => 'rfi-nutrition-program',
                'content' => '<p>Dear Partners,</p><p>Our organization is planning to implement a nutrition program targeting children under 5 and pregnant/lactating women. We would appreciate insights from partners with experience in:</p><ul><li>Community-based management of acute malnutrition (CMAM)</li><li>Infant and young child feeding (IYCF) programming</li><li>Mother support groups</li><li>Nutrition surveillance systems</li></ul><p>Any guidance or documentation you can share would be greatly appreciated.</p>',
                'category' => 'questions',
                'visibility' => 'public',
                'is_pinned' => false,
            ],
            [
                'title' => 'Partnership Opportunity: Joint Health Research Project',
                'slug' => 'partnership-research-opportunity',
                'content' => '<p>Dear Partners,</p><p>SSHIA is seeking partners for a collaborative research project on the effectiveness of digital health interventions in improving maternal health outcomes in South Sudan.</p><p><strong>Project Overview:</strong></p><ul><li>Duration: 24 months</li><li>Study sites: 4 states (to be determined)</li><li>Funding: Pending proposal approval</li></ul><p>Please express interest by responding to this thread.</p>',
                'category' => 'opportunities',
                'visibility' => 'partners_only',
                'is_pinned' => false,
            ],
            [
                'title' => 'Discussion: Improving Vaccine Cold Chain Management',
                'slug' => 'vaccine-cold-chain-discussion',
                'content' => '<p>Dear Colleagues,</p><p>Cold chain management remains one of our biggest challenges in immunization programs. I wanted to start a discussion on practical solutions.</p><p>Topics for discussion:</p><ul><li>Solar refrigeration experiences</li><li>Temperature monitoring technologies</li><li>Strategies for reaching remote areas</li><li>Maintenance and repair of equipment</li><li>Training of health workers</li></ul><p>Please share your experiences and solutions.</p>',
                'category' => 'best_practices',
                'visibility' => 'public',
                'is_pinned' => false,
            ],
            [
                'title' => 'Announcement: Health Worker Training Scholarship Program',
                'slug' => 'training-scholarship-announcement',
                'content' => '<p>Dear Partners,</p><p>We are pleased to announce a scholarship program for health workers seeking advanced training in public health.</p><p><strong>Program Details:</strong></p><ul><li>10 scholarships for Master of Public Health programs</li><li>20 scholarships for certificate courses</li><li>Eligibility: Health workers with 3+ years experience</li><li>Coverage: Tuition, stipend, and research support</li></ul><p>Please share this opportunity with qualified candidates.</p>',
                'category' => 'announcements',
                'visibility' => 'public',
                'is_pinned' => true,
            ],
            [
                'title' => 'Event: World Health Day 2024 Planning',
                'slug' => 'world-health-day-planning',
                'content' => '<p>Dear Partners,</p><p>As World Health Day approaches, we invite all partners to participate in planning joint activities.</p><p><strong>Proposed Activities:</strong></p><ul><li>Health fair and exhibition</li><li>Community awareness events</li><li>Media engagement</li><li>Policy dialogue with government</li></ul><p>A planning meeting is scheduled. Let\'s make World Health Day impactful together!</p>',
                'category' => 'events',
                'visibility' => 'public',
                'is_pinned' => false,
            ],
            [
                'title' => 'Resource Sharing: Health Education Materials Database',
                'slug' => 'health-education-database',
                'content' => '<p>Dear Partners,</p><p>I\'m pleased to share a database of health education materials developed by various partners working in South Sudan. This resource aims to reduce duplication and improve quality.</p><p><strong>The database includes:</strong></p><ul><li>IEC materials in multiple languages</li><li>Training modules</li><li>Job aids</li><li>Community mobilization guides</li><li>Radio scripts</li></ul><p>Partners are encouraged to both use and contribute to this shared resource.</p>',
                'category' => 'resources',
                'visibility' => 'public',
                'is_pinned' => true,
            ],
        ];

        $replyTemplates = [
            'Thank you for starting this important discussion. In our experience, the key to effective CHW training is hands-on practice and regular follow-up supervision.',
            'Great topic! We\'ve implemented a similar approach in our program with good results. The community engagement component is particularly important.',
            'I agree with the points raised. Additionally, we found that regular supervision visits significantly improve retention and quality of care.',
            'This is very relevant to our current work. We would be interested in collaborating on a joint approach to this challenge.',
            'Thank you for sharing these resources. We have developed complementary materials that address similar topics.',
            'Excellent initiative. We have faced similar challenges and found that community ownership is key to sustainability.',
            'Count us in for the upcoming meeting. We have some experiences to share about this topic.',
            'This is a valuable resource. We will contribute our materials and look forward to learning from others.',
        ];

        $threadCount = 0;
        $replyCount = 0;

        foreach ($threads as $threadData) {
            $thread = RForumThread::firstOrCreate(
                ['slug' => $threadData['slug']],
                array_merge($threadData, [
                    'user_id' => $this->authorId,
                    'status' => 'open',
                    'is_approved' => true,
                    'is_featured' => false,
                    'views_count' => rand(50, 500),
                    'replies_count' => 0,
                    'last_reply_at' => null,
                    'tags' => [],
                    'approved_at' => $now->copy()->subDays(rand(1, 30)),
                    'approved_by' => $this->authorId,
                    'created_at' => $now->copy()->subDays(rand(10, 60)),
                    'updated_at' => $now,
                ])
            );
            $threadCount++;

            // Only add replies for newly created threads
            if ($thread->wasRecentlyCreated) {
                $numReplies = rand(2, 5);
                for ($i = 0; $i < $numReplies; $i++) {
                    RForumReply::create([
                        'thread_id' => $thread->id,
                        'user_id' => $this->authorId,
                        'parent_id' => null,
                        'content' => '<p>' . $replyTemplates[$i % count($replyTemplates)] . '</p>',
                        'status' => 'published',
                        'is_approved' => true,
                        'helpful_count' => rand(0, 10),
                        'created_at' => $thread->created_at->copy()->addDays($i + 1),
                        'updated_at' => $thread->created_at->copy()->addDays($i + 1),
                    ]);
                    $thread->increment('replies_count');
                    $replyCount++;
                }

                $thread->update(['last_reply_at' => $thread->created_at->copy()->addDays($numReplies)]);
            }
        }

        $this->command->info('- Created ' . $threadCount . ' forum threads with ' . $replyCount . ' replies');
    }
}
