<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\SelfPaced\Course;
use App\Models\SelfPaced\ExamQuestion;

/**
 * SelfPacedExamSeeder
 *
 * Seeds 12 exam questions per course with correct answers and explanations.
 * Questions are aligned with the course content seeded by SelfPacedTopicSeeder.
 * Depends on SelfPacedCourseSeeder having run first.
 *
 * Requirements: 15.4
 */
class SelfPacedExamSeeder extends Seeder
{
    public function run(): void
    {
        $courses = Course::whereIn('slug', [
            'community-health-promotion-disease-prevention',
            'health-sector-leadership-management',
            'health-communication-community-engagement',
        ])->get()->keyBy('slug');

        foreach ($this->getQuestionsData() as $courseSlug => $questions) {
            $course = $courses->get($courseSlug);
            if (!$course) {
                continue;
            }

            foreach ($questions as $order => $q) {
                ExamQuestion::firstOrCreate(
                    ['course_id' => $course->id, 'question_text' => $q['question_text']],
                    [
                        'option_a'       => $q['option_a'],
                        'option_b'       => $q['option_b'],
                        'option_c'       => $q['option_c'],
                        'option_d'       => $q['option_d'],
                        'correct_answer' => $q['correct_answer'],
                        'explanation'    => $q['explanation'],
                        'sort_order'     => $order + 1,
                        'is_active'      => true,
                    ]
                );
            }
        }

        $this->command->info('SelfPacedExamSeeder: Exam questions seeded (12 per course).');
    }

    private function getQuestionsData(): array
    {
        return [
            'community-health-promotion-disease-prevention' => $this->healthQuestions(),
            'health-sector-leadership-management'           => $this->leadershipQuestions(),
            'health-communication-community-engagement'     => $this->communicationQuestions(),
        ];
    }

    // =========================================================================
    // HEALTH COURSE QUESTIONS (12)
    // =========================================================================
    private function healthQuestions(): array
    {
        return [
            [
                'question_text'  => 'According to the Ottawa Charter for Health Promotion (1986), which of the following is NOT one of the five key action areas?',
                'option_a'       => 'Build healthy public policy',
                'option_b'       => 'Create supportive environments',
                'option_c'       => 'Establish national health insurance',
                'option_d'       => 'Strengthen community action',
                'correct_answer' => 'C',
                'explanation'    => 'The Ottawa Charter identifies five action areas: Build healthy public policy, Create supportive environments, Strengthen community action, Develop personal skills, and Reorient health services. Establishing national health insurance is not one of them.',
            ],
            [
                'question_text'  => 'Which of the following best describes the concept of "empowerment" in community health promotion?',
                'option_a'       => 'Health workers making decisions on behalf of communities',
                'option_b'       => 'Enabling individuals and communities to take control of their health decisions',
                'option_c'       => 'Providing free medicines to all community members',
                'option_d'       => 'Building new health facilities in underserved areas',
                'correct_answer' => 'B',
                'explanation'    => 'Empowerment in health promotion means enabling individuals and communities to take control of their health decisions and the factors that influence their health, rather than making decisions for them.',
            ],
            [
                'question_text'  => 'In South Sudan, which disease is the leading cause of morbidity and mortality?',
                'option_a'       => 'Tuberculosis',
                'option_b'       => 'HIV/AIDS',
                'option_c'       => 'Malaria',
                'option_d'       => 'Cholera',
                'correct_answer' => 'C',
                'explanation'    => 'Malaria is the leading cause of morbidity and mortality in South Sudan. It is transmitted by the Anopheles mosquito and caused primarily by Plasmodium falciparum.',
            ],
            [
                'question_text'  => 'What is the recommended first-line treatment for uncomplicated malaria in South Sudan?',
                'option_a'       => 'Chloroquine monotherapy',
                'option_b'       => 'Artemisinin-based combination therapy (ACT)',
                'option_c'       => 'Quinine alone',
                'option_d'       => 'Doxycycline',
                'correct_answer' => 'B',
                'explanation'    => 'Artemisinin-based combination therapy (ACT) is the WHO-recommended and South Sudan national protocol first-line treatment for uncomplicated malaria caused by Plasmodium falciparum.',
            ],
            [
                'question_text'  => 'Which of the following is a social determinant of health?',
                'option_a'       => 'Blood pressure level',
                'option_b'       => 'Genetic predisposition to disease',
                'option_c'       => 'Access to clean water and sanitation',
                'option_d'       => 'Presence of malaria parasites in the blood',
                'correct_answer' => 'C',
                'explanation'    => 'Social determinants of health are the conditions in which people are born, grow, live, work, and age. Access to clean water and sanitation is a key social determinant. Blood pressure, genetics, and parasites are biological/clinical factors.',
            ],
            [
                'question_text'  => 'According to the South Sudan Expanded Programme on Immunisation (EPI), which vaccines are given at birth?',
                'option_a'       => 'BCG, OPV0, and Hepatitis B',
                'option_b'       => 'Measles, Yellow Fever, and Vitamin A',
                'option_c'       => 'OPV1, Pentavalent1, and PCV1',
                'option_d'       => 'BCG and Measles only',
                'correct_answer' => 'A',
                'explanation'    => 'According to the South Sudan EPI schedule, BCG (for tuberculosis), OPV0 (oral polio vaccine), and Hepatitis B vaccine are given at birth.',
            ],
            [
                'question_text'  => 'What does DOTS stand for in the context of tuberculosis treatment?',
                'option_a'       => 'Daily Oral Treatment Strategy',
                'option_b'       => 'Directly Observed Treatment, Short-course',
                'option_c'       => 'Disease Outbreak Treatment System',
                'option_d'       => 'Diagnostic and Outpatient Treatment Service',
                'correct_answer' => 'B',
                'explanation'    => 'DOTS stands for Directly Observed Treatment, Short-course. It is the WHO-recommended strategy for TB treatment where a health worker or trained volunteer watches the patient swallow each dose of medication.',
            ],
            [
                'question_text'  => 'Which of the following is the most effective prevention measure for cholera?',
                'option_a'       => 'Taking antibiotics prophylactically',
                'option_b'       => 'Wearing face masks in public',
                'option_c'       => 'Access to safe water, handwashing with soap, and proper sanitation',
                'option_d'       => 'Avoiding contact with animals',
                'correct_answer' => 'C',
                'explanation'    => 'Cholera is a waterborne disease. The most effective prevention measures are access to safe drinking water, handwashing with soap at critical times, and proper sanitation (safe disposal of faeces).',
            ],
            [
                'question_text'  => 'A community health worker notices an unusual cluster of fever cases in a village. What is the MOST appropriate immediate action?',
                'option_a'       => 'Treat all cases with antibiotics without reporting',
                'option_b'       => 'Wait to see if more cases develop before taking action',
                'option_c'       => 'Report the cluster to the health facility supervisor immediately',
                'option_d'       => 'Advise community members to leave the village',
                'correct_answer' => 'C',
                'explanation'    => 'Disease surveillance requires prompt reporting of unusual illness clusters. The CHW should immediately report to the health facility supervisor so that investigation and response can be initiated. Waiting or treating without reporting delays the public health response.',
            ],
            [
                'question_text'  => 'Which of the following best describes "vaccine hesitancy"?',
                'option_a'       => 'A shortage of vaccines at health facilities',
                'option_b'       => 'Delay in acceptance or refusal of vaccines despite availability',
                'option_c'       => 'An allergic reaction to a vaccine',
                'option_d'       => 'The process of storing vaccines at the correct temperature',
                'correct_answer' => 'B',
                'explanation'    => 'Vaccine hesitancy refers to delay in acceptance or refusal of vaccines despite their availability. It is influenced by factors such as complacency, inconvenience, and lack of confidence in vaccines.',
            ],
            [
                'question_text'  => 'In the context of behaviour change communication, what does "KAP" stand for?',
                'option_a'       => 'Knowledge, Attitude, and Practice',
                'option_b'       => 'Key Action Points',
                'option_c'       => 'Knowledge Assessment Programme',
                'option_d'       => 'Community Health Action Plan',
                'correct_answer' => 'A',
                'explanation'    => 'KAP stands for Knowledge, Attitudes, and Practices. KAP surveys are used to assess what a target audience knows, believes, and does regarding a specific health issue, informing the design of behaviour change communication interventions.',
            ],
            [
                'question_text'  => 'Which of the following is a key principle of community health promotion?',
                'option_a'       => 'Health workers should make all health decisions for communities',
                'option_b'       => 'Health promotion should focus only on individual behaviour change',
                'option_c'       => 'Equity means ensuring fair access to health resources for all',
                'option_d'       => 'Community participation is optional in health promotion programmes',
                'correct_answer' => 'C',
                'explanation'    => 'Equity is a core principle of community health promotion, meaning addressing health disparities and ensuring fair access to health resources for all people, regardless of their social, economic, or geographic circumstances.',
            ],
        ];
    }

    // =========================================================================
    // LEADERSHIP COURSE QUESTIONS (12)
    // =========================================================================
    private function leadershipQuestions(): array
    {
        return [
            [
                'question_text'  => 'Which leadership style is MOST appropriate when a health facility manager needs to drive major organisational change?',
                'option_a'       => 'Transactional leadership',
                'option_b'       => 'Laissez-faire leadership',
                'option_c'       => 'Transformational leadership',
                'option_d'       => 'Autocratic leadership',
                'correct_answer' => 'C',
                'explanation'    => 'Transformational leadership is most appropriate for driving major change. It inspires and motivates staff through a compelling vision, encourages innovation, and builds commitment to organisational goals.',
            ],
            [
                'question_text'  => 'In a SWOT analysis, which of the following is an example of an "Opportunity"?',
                'option_a'       => 'High staff turnover at the health facility',
                'option_b'       => 'A new donor funding programme for health facility improvement',
                'option_c'       => 'Lack of essential medicines at the facility',
                'option_d'       => 'Strong community trust in the health facility',
                'correct_answer' => 'B',
                'explanation'    => 'In SWOT analysis, Opportunities are external factors that the organisation can leverage. A new donor funding programme is an external opportunity. High staff turnover and lack of medicines are weaknesses (internal). Community trust is a strength (internal).',
            ],
            [
                'question_text'  => 'What does "SMART" stand for in the context of setting strategic objectives?',
                'option_a'       => 'Simple, Manageable, Achievable, Realistic, Timely',
                'option_b'       => 'Specific, Measurable, Achievable, Relevant, Time-bound',
                'option_c'       => 'Strategic, Meaningful, Actionable, Results-oriented, Trackable',
                'option_d'       => 'Systematic, Monitored, Approved, Reviewed, Tested',
                'correct_answer' => 'B',
                'explanation'    => 'SMART objectives are Specific (clearly defined), Measurable (quantifiable), Achievable (realistic given resources), Relevant (aligned with organisational goals), and Time-bound (with a clear deadline).',
            ],
            [
                'question_text'  => 'Which of the following is a key element of supportive supervision?',
                'option_a'       => 'Focusing only on identifying staff mistakes and punishing poor performance',
                'option_b'       => 'Conducting supervision visits without informing staff in advance',
                'option_c'       => 'Providing constructive, specific, and timely feedback to health workers',
                'option_d'       => 'Completing supervision reports without discussing findings with staff',
                'correct_answer' => 'C',
                'explanation'    => 'Supportive supervision is a collaborative approach that includes providing constructive, specific, and timely feedback. It focuses on problem-solving and capacity building rather than fault-finding and punishment.',
            ],
            [
                'question_text'  => 'According to Maslow\'s Hierarchy of Needs, which level of need must be met FIRST before higher-level needs can be addressed?',
                'option_a'       => 'Esteem needs',
                'option_b'       => 'Social needs',
                'option_c'       => 'Safety needs',
                'option_d'       => 'Physiological needs',
                'correct_answer' => 'D',
                'explanation'    => 'Maslow\'s Hierarchy of Needs places physiological needs (food, water, shelter, adequate salary) at the base. These must be met before safety, social, esteem, and self-actualisation needs can be effectively addressed.',
            ],
            [
                'question_text'  => 'In health financing, what does "pooling" refer to?',
                'option_a'       => 'Collecting fees directly from patients at the point of care',
                'option_b'       => 'Accumulating and managing revenues to spread financial risk across the population',
                'option_c'       => 'Purchasing medicines in bulk to reduce costs',
                'option_d'       => 'Allocating funds to specific health programmes',
                'correct_answer' => 'B',
                'explanation'    => 'Pooling is one of the three key health financing functions. It involves accumulating and managing revenues so that financial risk is spread across the population, protecting individuals from catastrophic health expenditure.',
            ],
            [
                'question_text'  => 'Which of the following is a sign of staff burnout in a health facility?',
                'option_a'       => 'Increased productivity and enthusiasm for work',
                'option_b'       => 'Emotional exhaustion, cynicism, and increased absenteeism',
                'option_c'       => 'Improved quality of patient care',
                'option_d'       => 'Greater engagement in professional development activities',
                'correct_answer' => 'B',
                'explanation'    => 'Burnout is characterised by emotional exhaustion, cynicism (depersonalisation), reduced productivity, and increased absenteeism. It is common among health workers in high-stress, resource-limited settings like South Sudan.',
            ],
            [
                'question_text'  => 'What is the primary purpose of a performance appraisal in a health facility?',
                'option_a'       => 'To identify staff for dismissal',
                'option_b'       => 'To review performance against objectives, identify development needs, and plan for improvement',
                'option_c'       => 'To determine salary increases only',
                'option_d'       => 'To document staff attendance records',
                'correct_answer' => 'B',
                'explanation'    => 'Performance appraisal is a formal review of an employee\'s performance against agreed objectives. Its primary purpose is to assess achievements, identify gaps, plan for professional development, and improve future performance.',
            ],
            [
                'question_text'  => 'Which of the following best describes Universal Health Coverage (UHC)?',
                'option_a'       => 'Free healthcare for government employees only',
                'option_b'       => 'Ensuring all people have access to quality health services without financial hardship',
                'option_c'       => 'Building a hospital in every county',
                'option_d'       => 'Providing health insurance to formal sector workers',
                'correct_answer' => 'B',
                'explanation'    => 'Universal Health Coverage (UHC) means that all people and communities can use the promotive, preventive, curative, rehabilitative, and palliative health services they need, of sufficient quality, without suffering financial hardship.',
            ],
            [
                'question_text'  => 'In the strategic planning process, what is the FIRST step?',
                'option_a'       => 'Developing an implementation plan',
                'option_b'       => 'Setting SMART objectives',
                'option_c'       => 'Conducting a situational analysis (SWOT)',
                'option_d'       => 'Defining key performance indicators',
                'correct_answer' => 'C',
                'explanation'    => 'The strategic planning process begins with a situational analysis (including SWOT analysis) to understand the current state — where the organisation is now — before defining vision, setting objectives, and developing implementation plans.',
            ],
            [
                'question_text'  => 'Which financial management principle ensures that all financial transactions are documented and open to scrutiny?',
                'option_a'       => 'Efficiency',
                'option_b'       => 'Sustainability',
                'option_c'       => 'Equity',
                'option_d'       => 'Transparency',
                'correct_answer' => 'D',
                'explanation'    => 'Transparency in financial management means that all financial transactions are documented, reported, and open to scrutiny by relevant stakeholders. It is a cornerstone of good financial governance.',
            ],
            [
                'question_text'  => 'A health facility manager wants to improve staff retention. Which of the following is a NON-FINANCIAL incentive?',
                'option_a'       => 'Increasing monthly salary',
                'option_b'       => 'Providing housing allowance',
                'option_c'       => 'Offering opportunities for training and professional development',
                'option_d'       => 'Paying performance-based bonuses',
                'correct_answer' => 'C',
                'explanation'    => 'Non-financial incentives include opportunities for training and professional development, public recognition, clear career progression pathways, and a supportive work environment. Salary increases, housing allowances, and bonuses are financial incentives.',
            ],
        ];
    }

    // =========================================================================
    // COMMUNICATION COURSE QUESTIONS (12)
    // =========================================================================
    private function communicationQuestions(): array
    {
        return [
            [
                'question_text'  => 'Which of the following is a core principle of effective health communication?',
                'option_a'       => 'Using technical medical terminology to demonstrate expertise',
                'option_b'       => 'Designing messages based on the needs and preferences of the target audience',
                'option_c'       => 'Delivering the same message to all audiences regardless of their characteristics',
                'option_d'       => 'Focusing only on mass media channels for maximum reach',
                'correct_answer' => 'B',
                'explanation'    => 'Effective health communication is audience-centred — messages must be designed based on the specific needs, values, literacy levels, and preferences of the target audience. Using jargon, one-size-fits-all messages, or relying solely on mass media are common communication mistakes.',
            ],
            [
                'question_text'  => 'In the communication process, what is "noise"?',
                'option_a'       => 'The volume at which a message is delivered',
                'option_b'       => 'Barriers that interfere with the effective transmission of a message',
                'option_c'       => 'The feedback provided by the audience',
                'option_d'       => 'The medium used to deliver the message',
                'correct_answer' => 'B',
                'explanation'    => 'In communication theory, "noise" refers to any barriers or interference that disrupts the effective transmission of a message from sender to receiver. This includes language barriers, cultural differences, low literacy, physical distractions, and misinformation.',
            ],
            [
                'question_text'  => 'Which communication channel is MOST appropriate for reaching rural communities with low literacy in South Sudan?',
                'option_a'       => 'Twitter/X posts',
                'option_b'       => 'Printed pamphlets in English',
                'option_c'       => 'Community radio in local languages',
                'option_d'       => 'Email newsletters',
                'correct_answer' => 'C',
                'explanation'    => 'Community radio in local languages is the most appropriate channel for reaching rural, low-literacy communities in South Sudan. It has wide reach, does not require literacy, and can deliver messages in familiar languages and cultural contexts.',
            ],
            [
                'question_text'  => 'What does SOCO stand for in health message development?',
                'option_a'       => 'Social Communication Objective',
                'option_b'       => 'Single Overriding Communication Objective',
                'option_c'       => 'Strategic Outreach and Community Organisation',
                'option_d'       => 'Systematic Observation of Communication Outcomes',
                'correct_answer' => 'B',
                'explanation'    => 'SOCO stands for Single Overriding Communication Objective. It is a message development framework that focuses on identifying the ONE key behaviour change you want to achieve and crafting a message that directly addresses the main barrier to that behaviour.',
            ],
            [
                'question_text'  => 'Which level of community engagement involves placing final decision-making in the hands of the community?',
                'option_a'       => 'Inform',
                'option_b'       => 'Consult',
                'option_c'       => 'Collaborate',
                'option_d'       => 'Empower',
                'correct_answer' => 'D',
                'explanation'    => 'The five levels of community engagement are: Inform, Consult, Involve, Collaborate, and Empower. Empowerment is the highest level, where final decision-making authority is placed in the hands of the community.',
            ],
            [
                'question_text'  => 'A health communicator wants to reach young mothers aged 18–30 in Juba about maternal health. Which platform would be MOST effective?',
                'option_a'       => 'Printed posters in health facilities only',
                'option_b'       => 'WhatsApp groups and Facebook combined with community meetings',
                'option_c'       => 'Television advertisements only',
                'option_d'       => 'Academic journal publications',
                'correct_answer' => 'B',
                'explanation'    => 'A multi-channel approach combining WhatsApp groups and Facebook (for digital reach among smartphone users) with community meetings (for interpersonal engagement) is most effective for reaching young urban mothers. Single-channel approaches limit reach and engagement.',
            ],
            [
                'question_text'  => 'What is the primary purpose of audience segmentation in health communication?',
                'option_a'       => 'To reduce the cost of communication campaigns',
                'option_b'       => 'To divide the target population into distinct groups for tailored messaging',
                'option_c'       => 'To identify which communities should not receive health messages',
                'option_d'       => 'To determine the budget allocation for different communication channels',
                'correct_answer' => 'B',
                'explanation'    => 'Audience segmentation divides the target population into distinct groups based on demographics, geography, behaviour, and psychographics. This allows communicators to tailor messages to the specific characteristics and needs of each group, improving effectiveness.',
            ],
            [
                'question_text'  => 'Which of the following is a key role of community and religious leaders in health communication?',
                'option_a'       => 'Replacing health workers in providing clinical care',
                'option_b'       => 'Addressing rumours and misinformation and endorsing health messages',
                'option_c'       => 'Managing health facility finances',
                'option_d'       => 'Conducting disease surveillance activities',
                'correct_answer' => 'B',
                'explanation'    => 'Community and religious leaders are trusted influencers who can address rumours and misinformation, endorse health messages, mobilise community members, and increase acceptance of health interventions. They do not replace clinical health workers.',
            ],
            [
                'question_text'  => 'What type of evaluation assesses whether a health communication campaign was implemented as planned?',
                'option_a'       => 'Impact evaluation',
                'option_b'       => 'Outcome evaluation',
                'option_c'       => 'Process evaluation',
                'option_d'       => 'Economic evaluation',
                'correct_answer' => 'C',
                'explanation'    => 'Process evaluation assesses whether the campaign was implemented as planned — activities completed on time, materials distributed, target audience reached. Outcome evaluation measures changes in knowledge, attitudes, and behaviour. Impact evaluation measures long-term health improvements.',
            ],
            [
                'question_text'  => 'Which of the following is the BEST strategy to counter health misinformation on social media?',
                'option_a'       => 'Ignore misinformation and hope it disappears',
                'option_b'       => 'Proactively share accurate information and engage directly with misinformation using evidence',
                'option_c'       => 'Delete all social media accounts to avoid misinformation',
                'option_d'       => 'Only communicate through traditional media channels',
                'correct_answer' => 'B',
                'explanation'    => 'The best strategy to counter health misinformation is to proactively share accurate information before rumours spread, and to engage directly with misinformation by providing corrections backed by evidence. Ignoring misinformation allows it to spread unchallenged.',
            ],
            [
                'question_text'  => 'In the Health Belief Model, which factor refers to a person\'s belief that the benefits of taking action outweigh the barriers?',
                'option_a'       => 'Perceived susceptibility',
                'option_b'       => 'Perceived severity',
                'option_c'       => 'Perceived benefits vs. barriers',
                'option_d'       => 'Cue to action',
                'correct_answer' => 'C',
                'explanation'    => 'The Health Belief Model includes: Perceived susceptibility (belief of being at risk), Perceived severity (belief the problem is serious), Perceived benefits vs. barriers (belief that benefits of action outweigh costs), and Cue to action (trigger to act). All four factors influence health behaviour.',
            ],
            [
                'question_text'  => 'A KAP survey conducted before a health communication campaign is BEST described as:',
                'option_a'       => 'An impact evaluation tool',
                'option_b'       => 'A baseline assessment of the target audience\'s knowledge, attitudes, and practices',
                'option_c'       => 'A process evaluation method',
                'option_d'       => 'A tool for measuring campaign cost-effectiveness',
                'correct_answer' => 'B',
                'explanation'    => 'A KAP (Knowledge, Attitudes, Practices) survey conducted before a campaign serves as a baseline assessment. It measures what the target audience currently knows, believes, and does regarding the health issue, informing message design and providing a benchmark for measuring change after the campaign.',
            ],
        ];
    }
}
