<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\RPublication;
use App\Models\User;
use Illuminate\Support\Str;

/**
 * Seeder: RPublicationSeeder
 * 
 * Seeds research publications for SSHIA - South Sudan Health Innovation & Advocacy.
 * Contains professional content related to health advocacy, digital health literacy,
 * and health research in South Sudan context.
 * 
 * @author SSHIA Development Team
 * @version 1.0.0
 */
class RPublicationSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Get users to assign as authors
        $users = User::all();
        
        if ($users->isEmpty()) {
            $this->command->warn('No users found. Please run user seeder first.');
            return;
        }

        $publications = [
            // Clinical Research Publications
            [
                'title' => 'Maternal Health Outcomes in Rural South Sudan: A Community-Based Study',
                'abstract' => 'This study examines maternal health outcomes across rural communities in South Sudan, focusing on access to prenatal care, skilled birth attendance, and emergency obstetric services. Our research involved 2,500 women of reproductive age across five states, revealing significant disparities in healthcare access and outcomes. The findings highlight critical gaps in healthcare infrastructure and propose community-based interventions to improve maternal survival rates.',
                'methodology' => 'We employed a mixed-methods approach combining quantitative surveys with qualitative focus group discussions. Data collection spanned 18 months across five states: Central Equatoria, Eastern Equatoria, Jonglei, Lakes, and Western Bahr el Ghazal. Statistical analysis utilized logistic regression models to identify factors associated with maternal health outcomes.',
                'findings' => 'Only 23% of women reported access to skilled birth attendance. Distance to health facilities (average 15km) and transportation costs were primary barriers. Community health worker interventions showed 40% improvement in prenatal care uptake. Mobile health interventions demonstrated promising results for health education delivery.',
                'references' => "1. WHO. (2023). Maternal Health Indicators in Sub-Saharan Africa.\n2. UNICEF. (2022). South Sudan Health Survey Report.\n3. Ministry of Health, South Sudan. (2023). National Health Strategic Plan.\n4. World Bank. (2023). Health Systems Strengthening in Conflict-Affected Areas.",
                'category' => 'clinical',
                'status' => 'approved',
                'is_featured' => true,
            ],
            [
                'title' => 'Malaria Prevention and Treatment Patterns Among Under-Five Children in Juba',
                'abstract' => 'Malaria remains a leading cause of morbidity and mortality among children under five in South Sudan. This prospective cohort study investigated prevention practices, treatment-seeking behavior, and clinical outcomes among 1,200 children in Juba County. Our findings reveal significant gaps in insecticide-treated net usage and delayed treatment-seeking that contribute to severe malaria cases.',
                'methodology' => 'Prospective cohort study following 1,200 children under five for 12 months. Household surveys collected data on prevention practices, while clinical records tracked malaria episodes and treatment outcomes. Rapid diagnostic tests confirmed malaria cases.',
                'findings' => 'ITN ownership was 67% but consistent usage was only 34%. Average treatment-seeking delay was 3.2 days from symptom onset. Community health worker training reduced severe malaria cases by 28%. Artemisinin-based combination therapy adherence was suboptimal at 61%.',
                'references' => "1. WHO. (2023). World Malaria Report.\n2. National Malaria Control Program. (2023). South Sudan Malaria Strategic Plan.\n3. Roll Back Malaria Partnership. (2022). Progress Report.",
                'category' => 'clinical',
                'status' => 'approved',
                'is_featured' => true,
            ],
            [
                'title' => 'HIV/AIDS Awareness and Testing Uptake Among Youth in South Sudan',
                'abstract' => 'This cross-sectional study assesses HIV/AIDS knowledge, attitudes, and testing practices among youth aged 15-24 in urban and peri-urban South Sudan. With HIV prevalence at 2.7% nationally, understanding youth behavior is critical for prevention strategies. The study reveals important insights into stigma, testing barriers, and educational needs.',
                'methodology' => 'Cross-sectional survey of 3,000 youth across Juba, Wau, and Malakal. Structured questionnaires assessed knowledge, attitudes, and practices. Focus group discussions explored barriers to testing. HIV testing was offered on-site with counseling.',
                'findings' => 'Comprehensive HIV knowledge was 42% among respondents. Stigma remained high with 38% expressing discriminatory attitudes. Testing uptake increased from 18% to 34% following educational interventions. Mobile testing units showed highest acceptance rates.',
                'references' => "1. UNAIDS. (2023). Global AIDS Update.\n2. South Sudan AIDS Commission. (2023). National HIV Strategic Plan.\n3. PEPFAR. (2022). Country Operational Plan.",
                'category' => 'clinical',
                'status' => 'approved',
                'is_featured' => false,
            ],
            [
                'title' => 'Nutritional Status and Feeding Practices of Children in IDP Camps',
                'abstract' => 'Internally displaced persons face heightened nutritional vulnerabilities. This study assessed the nutritional status of children under five in three major IDP camps in South Sudan, examining feeding practices, food security, and anthropometric indicators. The research provides evidence-based recommendations for nutrition programming in humanitarian settings.',
                'methodology' => 'Cross-sectional assessment using standardized anthropometric measurements, 24-hour dietary recalls, and household food security scales. Sample included 1,800 children across three IDP camps. WHO growth standards applied for nutritional classification.',
                'findings' => 'Global acute malnutrition rate was 14.3%, exceeding emergency thresholds. Exclusive breastfeeding rates were 48%. Minimum dietary diversity achieved by only 32% of children. Integrated nutrition programs showed 25% improvement in recovery rates.',
                'references' => "1. WHO. (2023). Child Growth Standards.\n2. WFP. (2023). Nutrition in Humanitarian Settings.\n3. UNICEF. (2022). Nutrition Assessment Report.",
                'category' => 'clinical',
                'status' => 'approved',
                'is_featured' => false,
            ],
            [
                'title' => 'Mental Health Services Accessibility in Post-Conflict South Sudan',
                'abstract' => 'Decades of conflict have created significant mental health needs in South Sudan. This study maps mental health service availability, identifies treatment gaps, and evaluates community-based mental health interventions. With limited psychiatric resources, task-shifting to community health workers presents a viable strategy for service delivery.',
                'methodology' => 'Multi-method study combining health facility assessments, key informant interviews, and community surveys. WHO Assessment Instrument for Mental Health Systems applied. Sample included 40 health facilities and 2,000 community members.',
                'findings' => 'Only 2 psychiatrists serve the entire country. Depression prevalence estimated at 15% in conflict-affected populations. Community health worker-delivered interventions showed 60% symptom improvement. Stigma reduced by 35% through community education.',
                'references' => "1. WHO. (2023). Mental Health Atlas.\n2. International Medical Corps. (2022). Mental Health in South Sudan.\n3. Ministry of Health. (2023). Mental Health Policy Framework.",
                'category' => 'clinical',
                'status' => 'approved',
                'is_featured' => true,
            ],

            // Technology & Innovation Publications
            [
                'title' => 'Mobile Health Interventions for Remote Healthcare Delivery in South Sudan',
                'abstract' => 'This research evaluates the effectiveness of mobile health (mHealth) interventions in overcoming healthcare access barriers in remote South Sudanese communities. The study examines SMS-based health messaging, telemedicine consultations, and mobile data collection systems. Results demonstrate significant potential for technology-enhanced healthcare delivery in resource-limited settings.',
                'methodology' => 'Implementation research across 12 health facilities utilizing mHealth platforms. Pre-post intervention design measured healthcare access indicators. Qualitative interviews with healthcare workers and community members assessed acceptability. Cost-effectiveness analysis conducted.',
                'findings' => 'mHealth interventions increased antenatal care attendance by 45%. Telemedicine reduced referral costs by 60%. Community health worker efficiency improved by 35% through mobile data collection. SMS reminders improved appointment adherence by 52%.',
                'references' => "1. WHO. (2023). Digital Health Guidelines.\n2. GSMA. (2022). Mobile for Development Report.\n3. Ministry of ICT. (2023). Digital South Sudan Strategy.",
                'category' => 'tech',
                'status' => 'approved',
                'is_featured' => true,
            ],
            [
                'title' => 'Digital Health Literacy Assessment Among Healthcare Workers in South Sudan',
                'abstract' => 'As healthcare becomes increasingly digitized, understanding digital health literacy among healthcare workers is essential. This study assessed digital competencies, identified training needs, and developed a capacity-building framework for South Sudanese healthcare professionals. The research informs national digital health strategy implementation.',
                'methodology' => 'Cross-sectional survey of 500 healthcare workers across all ten states. Digital competency assessment using validated tools. Focus group discussions explored barriers and enablers. Training intervention pilot tested with pre-post evaluation.',
                'findings' => 'Basic digital literacy at 34% among healthcare workers. Urban-rural divide significant (58% vs 18%). Training intervention improved digital competencies by 65%. Preferred learning modalities included peer mentoring and hands-on practice.',
                'references' => "1. WHO. (2023). Digital Competency Framework.\n2. ITU. (2022). Digital Skills Assessment.\n3. Health informatics literature review 2020-2023.",
                'category' => 'tech',
                'status' => 'approved',
                'is_featured' => false,
            ],
            [
                'title' => 'Telemedicine Implementation for Specialist Care Access in Remote Regions',
                'abstract' => 'Specialist healthcare services remain largely unavailable outside Juba. This pilot study implemented telemedicine platforms connecting remote health facilities with specialists at Juba Teaching Hospital. The research evaluates clinical outcomes, cost-effectiveness, and sustainability of telemedicine in the South Sudan context.',
                'methodology' => 'Pilot implementation at 6 remote facilities with specialist consultation platform. Retrospective chart review for clinical outcomes. Cost analysis comparing telemedicine to patient travel. Patient and provider satisfaction surveys conducted.',
                'findings' => '1,200 teleconsultations conducted over 18 months. Diagnostic accuracy improved by 28%. Average patient cost savings of $150 per consultation. Provider satisfaction high at 85%. Sustainable model identified through integration with existing systems.',
                'references' => "1. WHO. (2023). Telemedicine Implementation Guide.\n2. American Telemedicine Association. (2022). Best Practices.\n3. Ministry of Health. (2023). E-Health Strategy.",
                'category' => 'tech',
                'status' => 'approved',
                'is_featured' => false,
            ],
            [
                'title' => 'Electronic Health Records Implementation: Challenges and Solutions in South Sudan',
                'abstract' => 'This research documents the implementation of electronic health records (EHR) in selected health facilities in South Sudan. The study identifies infrastructural, human resource, and systemic challenges while proposing context-appropriate solutions. Findings inform national health information system strengthening efforts.',
                'methodology' => 'Implementation case study at 4 health facilities using OpenMRS platform. Process documentation, barrier analysis, and solution testing over 24 months. User acceptance testing and data quality assessments conducted quarterly.',
                'findings' => 'Internet connectivity primary barrier (available 60% of time). User training required average 40 hours per staff. Data quality improved by 75% after 12 months. Paper-electronic hybrid systems most practical approach currently.',
                'references' => "1. OpenMRS. (2023). Implementation Guide.\n2. DHIS2. (2022). Health Information Systems.\n3. WHO. (2023). Health Data Standards.",
                'category' => 'tech',
                'status' => 'approved',
                'is_featured' => false,
            ],
            [
                'title' => 'Community Health Worker Mobile Tools for Disease Surveillance',
                'abstract' => 'Effective disease surveillance requires timely data from community level. This study developed and tested mobile applications for community health workers to report disease indicators. The research evaluates data quality, timeliness, and public health utility of mobile-based surveillance systems.',
                'methodology' => 'Participatory design of mobile surveillance tools with community health workers. Pilot testing in 30 communities. Data quality comparison between paper and mobile reporting. Timeliness analysis and outbreak detection simulation.',
                'findings' => 'Mobile reporting reduced data transmission time from 14 days to same-day. Data completeness improved from 72% to 94%. Outbreak detection time reduced by 65%. Community health worker acceptance high at 91%.',
                'references' => "1. WHO. (2023). IDSR Guidelines.\n2. CDC. (2022). Community Surveillance Framework.\n3. Health Security literature review.",
                'category' => 'tech',
                'status' => 'approved',
                'is_featured' => true,
            ],

            // Social Sciences Publications
            [
                'title' => 'Gender Barriers to Healthcare Access in South Sudan: A Qualitative Study',
                'abstract' => 'Gender inequality significantly impacts healthcare access in South Sudan. This qualitative study explores cultural, economic, and systemic barriers facing women and girls in accessing health services. The research provides recommendations for gender-responsive health programming and policy reform.',
                'methodology' => 'Qualitative study using in-depth interviews and focus group discussions with 200 participants. Purposive sampling across four states. Thematic analysis applied to identify patterns. Gender analysis framework utilized.',
                'findings' => 'Decision-making power concentrated with male heads of household. Distance to facilities poses safety concerns for women. Female healthcare worker availability influences care-seeking. Economic dependence limits healthcare access for women.',
                'references' => "1. UN Women. (2023). Gender and Health Report.\n2. WHO. (2022). Gender Mainstreaming in Health.\n3. Ministry of Gender. (2023). National Gender Policy.",
                'category' => 'social',
                'status' => 'approved',
                'is_featured' => false,
            ],
            [
                'title' => 'Traditional Medicine Practices and Integration with Formal Healthcare',
                'abstract' => 'Traditional medicine remains widely practiced in South Sudan. This study examines traditional healing practices, community perceptions, and potential for integration with formal healthcare systems. The research bridges indigenous knowledge with evidence-based medicine for holistic healthcare delivery.',
                'methodology' => 'Ethnographic study combining participant observation, interviews with traditional healers, and community surveys. Assessment of common traditional practices. Stakeholder dialogue on integration models. Safety and efficacy review of selected practices.',
                'findings' => '85% of rural populations consult traditional healers first. Strong cultural acceptance of traditional medicine. Collaboration models show improved patient outcomes. Training traditional birth attendants reduces maternal complications.',
                'references' => "1. WHO. (2023). Traditional Medicine Strategy.\n2. African Traditional Medicine Research Network.\n3. Ministry of Health. (2023). Traditional Medicine Policy.",
                'category' => 'social',
                'status' => 'approved',
                'is_featured' => false,
            ],
            [
                'title' => 'Youth Health Education Needs Assessment in South Sudanese Schools',
                'abstract' => 'Comprehensive health education in schools lays foundation for lifelong health behaviors. This needs assessment examines current health education delivery, identifies gaps, and proposes curriculum improvements for South Sudanese schools. The research engages students, teachers, and education officials.',
                'methodology' => 'Mixed-methods assessment across 50 primary and secondary schools. Curriculum review, teacher interviews, and student surveys conducted. Knowledge tests on key health topics administered. Stakeholder workshops validated findings.',
                'findings' => 'Health education delivered in only 35% of schools. Teacher training in health topics minimal. Student knowledge on reproductive health at 28%. Peer education programs show promising results for health knowledge transfer.',
                'references' => "1. UNESCO. (2023). Health Education Guidelines.\n2. Ministry of Education. (2023). National Curriculum Framework.\n3. School Health Initiative literature.",
                'category' => 'social',
                'status' => 'approved',
                'is_featured' => false,
            ],
            [
                'title' => 'Community Trust and Health Facility Utilization in Post-Conflict Areas',
                'abstract' => 'Conflict erodes trust in institutions, including healthcare systems. This study examines the relationship between community trust and health facility utilization in post-conflict South Sudan. The research identifies trust-building interventions to improve healthcare access and outcomes.',
                'methodology' => 'Cross-sectional study in 20 conflict-affected communities. Trust scales administered to 2,000 respondents. Health facility utilization data analyzed. Trust-building interventions tested and evaluated.',
                'findings' => 'Trust levels correlated with healthcare utilization (r=0.72). Community engagement initiatives increased trust by 40%. Transparency in resource allocation improved community confidence. Local health committees enhanced accountability.',
                'references' => "1. Social Science & Medicine. Trust in Healthcare Systems.\n2. WHO. (2023). Community Engagement Framework.\n3. Peace and Health literature.",
                'category' => 'social',
                'status' => 'approved',
                'is_featured' => false,
            ],
            [
                'title' => 'Health Communication Strategies for Behavior Change in South Sudan',
                'abstract' => 'Effective health communication drives behavior change and improves health outcomes. This study evaluates various communication channels and messaging strategies for health promotion in South Sudan. The research provides evidence-based recommendations for national health communication programming.',
                'methodology' => 'Multi-channel communication evaluation using pre-post design. Radio, community theater, social media, and interpersonal communication tested. Knowledge, attitude, and practice surveys administered. Cost-effectiveness analysis conducted.',
                'findings' => 'Radio reaches 78% of population with health messages. Community theater most effective for attitude change. Interpersonal communication crucial for behavior adoption. Multi-channel approaches show synergistic effects.',
                'references' => "1. WHO. (2023). Health Communication Guidelines.\n2. Johns Hopkins CCP. (2022). SBCC Best Practices.\n3. BBC Media Action Reports.",
                'category' => 'social',
                'status' => 'approved',
                'is_featured' => false,
            ],
        ];

        $created = 0;
        foreach ($publications as $pub) {
            $author = $users->random();
            $status = $pub['status'];
            $isFeatured = $pub['is_featured'];
            
            $publication = RPublication::create([
                'user_id' => $author->id,
                'title' => $pub['title'],
                'abstract' => $pub['abstract'],
                'methodology' => $pub['methodology'],
                'findings' => $pub['findings'],
                'references' => $pub['references'],
                'category' => $pub['category'],
                'status' => $isFeatured ? 'featured' : $status,
                'is_featured' => $isFeatured,
                'submitted_at' => now()->subDays(rand(30, 180)),
                'approved_at' => now()->subDays(rand(15, 60)),
                'approved_by' => $users->where('id', '!=', $author->id)->random()->id,
                'created_at' => now()->subDays(rand(60, 365)),
            ]);
            $created++;
        }

        $this->command->info("Created {$created} research publications for SSHIA.");
    }
}
