<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use App\Models\SelfPaced\Course;
use App\Models\SelfPaced\CourseCategory;
use App\Models\SelfPaced\CourseTopic;
use App\Models\SelfPaced\CourseSubTopic;
use App\Models\SelfPaced\ExamQuestion;
use App\Models\SelfPaced\CourseDownload;
use App\Models\User;

/**
 * ResearchMethodsBiostatisticsCourseSeeder
 *
 * Seeds the "Professional Certificate in Research Methods and Biostatistics in Health"
 * with 7 topics, 4 subtopics each (28 total), 35 exam questions, and 2 downloads.
 * All fees in South Sudanese Pound (SSP). Fully idempotent via firstOrCreate.
 *
 * Run individually:
 *   php artisan db:seed --class=ResearchMethodsBiostatisticsCourseSeeder
 *
 * Requirements: 2.1-2.12, 3.1-3.5, 4.1-4.6, 5.1-5.9, 6.1-6.6, 7.1-7.5, 10.1-10.4
 */
class ResearchMethodsBiostatisticsCourseSeeder extends Seeder
{
    private int $createdById  = 1;
    private int $instructorId = 1;

    public function run(): void
    {
        DB::transaction(function () {
            $this->resolveUsers();
            $course = $this->makeCourse();
            $this->seedTopics($course);
            $this->seedQuestions($course);
            $this->seedDownloads($course);
        });

        $this->command->info('ResearchMethodsBiostatisticsCourseSeeder: course seeded successfully.');
    }

    private function resolveUsers(): void
    {
        $admin   = User::whereHas('roles', fn ($q) => $q->where('name', 'Super Manager'))->first();
        $trainer = User::whereHas('roles', fn ($q) => $q->where('name', 'Trainers'))->first();
        $this->createdById  = $admin?->id ?? 1;
        $this->instructorId = $trainer?->id ?? $admin?->id ?? 1;
    }

    private function makeCourse(): Course
    {
        $category = CourseCategory::where('slug', 'health')->first();

        return Course::firstOrCreate(
            ['slug' => 'professional-certificate-research-methods-biostatistics-health'],
            [
                'title'                      => 'Professional Certificate in Research Methods and Biostatistics in Health',
                'description'                => 'This Professional Certificate equips health professionals in South Sudan with the knowledge and practical skills to design, conduct, analyse, and disseminate health research. Participants will develop competencies in quantitative and qualitative research methods, biostatistics, epidemiology, data management, and scientific writing, with a focus on the South Sudan health context. The course prepares graduates to produce rigorous evidence that informs health policy and practice.',
                'objectives'                 => "By the end of this course, participants will be able to:\n- Design rigorous health research studies using appropriate methodologies\n- Apply biostatistical methods to analyse health data\n- Conduct epidemiological investigations including outbreak investigations\n- Collect and manage health research data using digital tools\n- Perform qualitative research and analyse qualitative data\n- Write scientific papers and research reports for professional audiences\n- Critically appraise published health research\n- Navigate research ethics requirements in South Sudan",
                'prerequisites'              => 'Basic understanding of public health or health service delivery. Experience working in a health facility, research organisation, or government health programme is recommended. Basic numeracy skills required. No prior statistics or research training is necessary.',
                'category_id'                => $category?->id,
                'instructor_id'              => $this->instructorId,
                'fee_amount'                 => 80000.00,
                'currency'                   => 'SSP',
                'duration_hours'             => 40,
                'passing_score'              => 70,
                'exam_attempts_allowed'      => 3,
                'exam_time_limit'            => 90,
                'exam_questions_per_attempt' => 20,
                'status'                     => 'published',
                'created_by'                 => $this->createdById,
                'updated_by'                 => $this->createdById,
            ]
        );
    }

    private function makeTopic(Course $course, string $title, string $description, int $order): CourseTopic
    {
        return CourseTopic::firstOrCreate(
            ['course_id' => $course->id, 'title' => $title],
            ['description' => $description, 'sort_order' => $order, 'is_published' => true]
        );
    }

    private function makeSub(CourseTopic $topic, string $title, string $html, int $order): void
    {
        CourseSubTopic::firstOrCreate(
            ['topic_id' => $topic->id, 'title' => $title],
            ['content' => $html, 'sort_order' => $order, 'is_published' => true]
        );
    }

    private function makeQuestion(Course $course, array $q, int $order): void
    {
        ExamQuestion::firstOrCreate(
            ['course_id' => $course->id, 'question_text' => $q['question']],
            [
                'option_a'               => $q['a'],
                'option_b'               => $q['b'],
                'option_c'               => $q['c'],
                'option_d'               => $q['d'],
                'correct_answer'         => $q['answer'],
                'explanation'            => $q['explanation'],
                'allow_multiple_answers' => false,
                'correct_answers_json'   => null,
                'sort_order'             => $order,
                'is_active'              => true,
            ]
        );
    }

    private function makeDownload(Course $course, string $title, string $fileName, string $mimeType, int $fileSize): void
    {
        $slug = $course->slug;
        CourseDownload::firstOrCreate(
            ['course_id' => $course->id, 'title' => $title],
            [
                'topic_id'  => null,
                'file_path' => "downloads/courses/{$slug}/{$fileName}",
                'file_name' => $fileName,
                'file_size' => $fileSize,
                'mime_type' => $mimeType,
            ]
        );
    }

    private function seedTopics(Course $course): void
    {
        $this->seedTopic1($course);
        $this->seedTopic2($course);
        $this->seedTopic3($course);
        $this->seedTopic4($course);
        $this->seedTopic5($course);
        $this->seedTopic6($course);
        $this->seedTopic7($course);
    }

    // =========================================================================
    // TOPIC 1 — Foundations of Health Research
    // =========================================================================
    private function seedTopic1(Course $course): void
    {
        $topic = $this->makeTopic($course,
            'Foundations of Health Research',
            'Core concepts, types, and principles of health research with application to the South Sudan health context.',
            1
        );

        $this->makeSub($topic, 'Introduction to Health Research',
            '<h3>What is Health Research?</h3><p>Health research is the systematic investigation of health-related questions using scientific methods to generate new knowledge that can improve health outcomes. It encompasses a wide spectrum of activities — from laboratory experiments to community surveys, from clinical trials to qualitative interviews — all united by the goal of producing reliable evidence to guide health decisions.</p><p>In South Sudan, health research is critically important because the country faces a severe burden of disease with very limited evidence to guide health policy and resource allocation. Research conducted in South Sudan by South Sudanese health professionals is particularly valuable because it reflects local realities and builds national capacity for evidence-based health system development.</p><h3>Why Health Research Matters</h3><ul><li><strong>Informs policy:</strong> Evidence from research guides national health policies, clinical guidelines, and resource allocation decisions.</li><li><strong>Improves practice:</strong> Research identifies what interventions work and what does not, enabling health workers to provide better care.</li><li><strong>Builds accountability:</strong> Research provides data to hold health systems accountable for outcomes.</li><li><strong>Advances knowledge:</strong> Research contributes to the global body of health knowledge.</li></ul>',
        1);

        $this->makeSub($topic, 'Types of Health Research',
            '<h3>Quantitative vs. Qualitative Research</h3><p>Health research is broadly divided into quantitative and qualitative approaches, each suited to different types of research questions:</p><ul><li><strong>Quantitative research</strong> uses numerical data and statistical analysis to answer questions about frequency, magnitude, associations, and causation. Examples include surveys measuring disease prevalence, clinical trials testing treatment effectiveness, and cohort studies examining risk factors.</li><li><strong>Qualitative research</strong> uses non-numerical data (words, images, observations) to explore meanings, experiences, and social processes. Examples include focus group discussions exploring barriers to health service use, in-depth interviews with health workers about their experiences, and ethnographic studies of health practices.</li></ul><h3>Primary vs. Secondary Research</h3><p>Primary research involves collecting new data directly from participants or observations. Secondary research analyses existing data collected for other purposes, such as health facility records, DHIS2 data, or previously published studies. Systematic reviews and meta-analyses are important forms of secondary research that synthesise evidence from multiple primary studies.</p><h3>Basic vs. Applied Research</h3><p>Basic research seeks to advance fundamental knowledge without immediate practical application. Applied research addresses specific practical problems. Most health research in South Sudan is applied research aimed at solving immediate health system challenges.</p>',
        2);

        $this->makeSub($topic, 'The Research Process',
            '<h3>Steps in the Research Process</h3><p>Health research follows a systematic process that ensures rigour and reproducibility. The key steps are:</p><ol><li><strong>Identify the research problem:</strong> Define the health problem or knowledge gap that the research will address. A good research problem is important, feasible, novel, ethical, and relevant (FINER criteria).</li><li><strong>Review existing literature:</strong> Conduct a systematic review of published research to understand what is already known and identify gaps.</li><li><strong>Formulate research questions and hypotheses:</strong> Develop specific, answerable research questions. For quantitative research, formulate testable hypotheses.</li><li><strong>Design the study:</strong> Select the appropriate study design, sampling strategy, data collection methods, and analysis plan.</li><li><strong>Obtain ethics approval:</strong> Submit the research protocol to an ethics committee for review and approval before data collection begins.</li><li><strong>Collect data:</strong> Implement the data collection plan, ensuring quality control throughout.</li><li><strong>Analyse data:</strong> Apply appropriate statistical or qualitative analysis methods.</li><li><strong>Interpret and disseminate findings:</strong> Draw conclusions, acknowledge limitations, and share findings through publications, presentations, and policy briefs.</li></ol>',
        3);

        $this->makeSub($topic, 'Formulating Research Questions and Hypotheses',
            '<h3>Characteristics of a Good Research Question</h3><p>A well-formulated research question is the foundation of a good study. The PICO framework is widely used in health research to structure research questions:</p><ul><li><strong>P — Population:</strong> Who is the study population? (e.g., pregnant women in Juba)</li><li><strong>I — Intervention/Exposure:</strong> What is the intervention or exposure of interest? (e.g., antenatal care attendance)</li><li><strong>C — Comparison:</strong> What is the comparison group? (e.g., women who did not attend ANC)</li><li><strong>O — Outcome:</strong> What is the outcome of interest? (e.g., maternal mortality)</li></ul><p>For qualitative research, the PEO framework (Population, Exposure/Experience, Outcome) is more appropriate.</p><h3>Research Hypotheses</h3><p>A hypothesis is a testable statement about the expected relationship between variables. The null hypothesis (H₀) states that there is no relationship or difference; the alternative hypothesis (H₁) states that there is a relationship or difference. Statistical tests evaluate the evidence against the null hypothesis. In South Sudan health research, hypotheses might address questions such as: "Is there a significant association between household water source and diarrhoeal disease incidence in children under five?"</p>',
        4);
    }

    // =========================================================================
    // TOPIC 2 — Study Design in Health Research
    // =========================================================================
    private function seedTopic2(Course $course): void
    {
        $topic = $this->makeTopic($course,
            'Study Design in Health Research',
            'Understanding and selecting appropriate study designs for health research questions in the South Sudan context.',
            2
        );

        $this->makeSub($topic, 'Observational Study Designs',
            '<h3>Cross-Sectional Studies</h3><p>A cross-sectional study measures exposure and outcome at a single point in time in a defined population. It is the most common study design in South Sudan health research because it is relatively quick and inexpensive. Cross-sectional studies are ideal for measuring disease prevalence and identifying associations, but cannot establish causation because exposure and outcome are measured simultaneously. Example: A survey measuring the prevalence of malnutrition among children under five in Jonglei State.</p><h3>Case-Control Studies</h3><p>A case-control study compares people who have a disease (cases) with people who do not (controls) to identify factors associated with the disease. Cases and controls are selected first, then their past exposures are compared. Case-control studies are efficient for studying rare diseases and can examine multiple exposures simultaneously. Example: Comparing the food consumption history of cholera cases and matched controls to identify the source of an outbreak.</p><h3>Cohort Studies</h3><p>A cohort study follows a group of people over time to observe who develops a disease or outcome. Prospective cohorts follow participants forward in time; retrospective cohorts use existing records. Cohort studies can establish temporal relationships between exposure and outcome, making them stronger evidence for causation than cross-sectional or case-control studies. Example: Following a cohort of HIV-positive pregnant women to measure mother-to-child transmission rates under different treatment protocols.</p>',
        1);

        $this->makeSub($topic, 'Experimental Study Designs',
            '<h3>Randomised Controlled Trials (RCTs)</h3><p>The RCT is considered the gold standard for evaluating the effectiveness of health interventions. Participants are randomly allocated to an intervention group (receiving the treatment being tested) or a control group (receiving standard care or placebo). Randomisation ensures that the two groups are comparable at baseline, so any difference in outcomes can be attributed to the intervention. RCTs provide the strongest evidence for causation but are expensive, time-consuming, and not always feasible or ethical.</p><h3>Quasi-Experimental Designs</h3><p>When randomisation is not possible, quasi-experimental designs can provide useful evidence about intervention effectiveness. Common quasi-experimental designs include:</p><ul><li><strong>Before-after studies:</strong> Compare outcomes before and after an intervention in the same population.</li><li><strong>Interrupted time series:</strong> Analyse trends in outcomes before and after an intervention using multiple time points.</li><li><strong>Difference-in-differences:</strong> Compare changes in outcomes between an intervention group and a comparison group over time.</li></ul><p>In South Sudan, quasi-experimental designs are often more feasible than RCTs for evaluating health system interventions such as new service delivery models or training programmes.</p>',
        2);

        $this->makeSub($topic, 'Qualitative Research Designs',
            '<h3>When to Use Qualitative Research</h3><p>Qualitative research is appropriate when the research question asks "how" or "why" rather than "how many" or "how much". It is particularly valuable for: exploring health beliefs, attitudes, and behaviours; understanding barriers and facilitators to health service use; evaluating complex health interventions; and generating hypotheses for quantitative testing. In South Sudan, qualitative research is essential for understanding the cultural and social determinants of health behaviour.</p><h3>Common Qualitative Designs</h3><ul><li><strong>Phenomenology:</strong> Explores the lived experience of a phenomenon from the perspective of those who have experienced it. Example: Understanding the experience of women who have lost a child to preventable disease.</li><li><strong>Grounded theory:</strong> Develops theory grounded in data collected from participants. Useful for understanding social processes in health settings.</li><li><strong>Ethnography:</strong> Studies a cultural group in their natural setting over an extended period. Valuable for understanding health practices in specific communities.</li><li><strong>Case study:</strong> In-depth investigation of a specific case (individual, organisation, programme). Useful for evaluating health programmes.</li></ul>',
        3);

        $this->makeSub($topic, 'Sampling Strategies',
            '<h3>Probability Sampling</h3><p>Probability sampling methods give every member of the population a known, non-zero chance of being selected. They are used in quantitative research to ensure the sample is representative of the population. Key probability sampling methods include:</p><ul><li><strong>Simple random sampling:</strong> Every member of the population has an equal chance of selection. Requires a complete sampling frame.</li><li><strong>Systematic sampling:</strong> Every nth member of the population is selected. Simpler than simple random sampling when a list is available.</li><li><strong>Stratified sampling:</strong> The population is divided into subgroups (strata) and random samples are drawn from each stratum. Ensures representation of key subgroups.</li><li><strong>Cluster sampling:</strong> Groups (clusters) rather than individuals are randomly selected. Practical when a complete sampling frame is unavailable — common in South Sudan field surveys.</li><li><strong>Multi-stage sampling:</strong> Combines multiple sampling methods. Used in large national surveys such as the South Sudan Household Health Survey.</li></ul><h3>Non-Probability Sampling</h3><p>Non-probability sampling methods are used in qualitative research and some quantitative studies where probability sampling is not feasible. Methods include purposive sampling (selecting participants based on specific characteristics), snowball sampling (participants recruit other participants), and convenience sampling. Sample size in qualitative research is determined by data saturation — the point at which no new themes emerge from additional data collection.</p>',
        4);
    }

    // =========================================================================
    // TOPIC 3 — Biostatistics Fundamentals
    // =========================================================================
    private function seedTopic3(Course $course): void
    {
        $topic = $this->makeTopic($course,
            'Biostatistics Fundamentals',
            'Core statistical concepts and methods for analysing health data, including descriptive statistics, probability, and hypothesis testing.',
            3
        );

        $this->makeSub($topic, 'Descriptive Statistics',
            '<h3>Types of Data</h3><p>Understanding data types is fundamental to selecting appropriate statistical methods. Health data can be classified as:</p><ul><li><strong>Nominal data:</strong> Categories with no inherent order (e.g., blood group, sex, disease type).</li><li><strong>Ordinal data:</strong> Categories with a meaningful order but unequal intervals (e.g., disease severity: mild, moderate, severe).</li><li><strong>Interval data:</strong> Numerical data with equal intervals but no true zero (e.g., temperature in Celsius).</li><li><strong>Ratio data:</strong> Numerical data with equal intervals and a true zero (e.g., weight, height, age, blood pressure).</li></ul><h3>Measures of Central Tendency</h3><p>Measures of central tendency describe the centre of a data distribution:</p><ul><li><strong>Mean:</strong> The arithmetic average. Sensitive to outliers. Appropriate for normally distributed ratio/interval data.</li><li><strong>Median:</strong> The middle value when data are ordered. Robust to outliers. Appropriate for skewed data or ordinal data.</li><li><strong>Mode:</strong> The most frequently occurring value. Appropriate for nominal data.</li></ul><h3>Measures of Dispersion</h3><p>Measures of dispersion describe the spread of data: range (maximum minus minimum), interquartile range (IQR, the range of the middle 50% of data), variance (average squared deviation from the mean), and standard deviation (square root of variance). The standard deviation is the most commonly used measure of dispersion for normally distributed data.</p>',
        1);

        $this->makeSub($topic, 'Probability and Distributions',
            '<h3>Basic Probability Concepts</h3><p>Probability is the likelihood that an event will occur, expressed as a number between 0 (impossible) and 1 (certain). In health research, probability underpins statistical inference — the process of drawing conclusions about a population from a sample. Key probability concepts include:</p><ul><li><strong>Independent events:</strong> The occurrence of one event does not affect the probability of another.</li><li><strong>Conditional probability:</strong> The probability of an event given that another event has occurred.</li><li><strong>Bayes\' theorem:</strong> A formula for updating probability estimates based on new evidence. Fundamental to diagnostic test interpretation.</li></ul><h3>The Normal Distribution</h3><p>The normal (Gaussian) distribution is a symmetric, bell-shaped distribution characterised by its mean and standard deviation. Many biological measurements (height, weight, blood pressure) are approximately normally distributed in large populations. The normal distribution is fundamental to many statistical tests. Key properties: approximately 68% of values fall within one standard deviation of the mean; 95% within two standard deviations; 99.7% within three standard deviations.</p><h3>Other Important Distributions</h3><p>The binomial distribution models the number of successes in a fixed number of independent trials (e.g., number of patients who respond to treatment). The Poisson distribution models the number of events occurring in a fixed time or space (e.g., number of malaria cases per week). Understanding these distributions is important for analysing count data common in epidemiology.</p>',
        2);

        $this->makeSub($topic, 'Hypothesis Testing and P-values',
            '<h3>The Logic of Hypothesis Testing</h3><p>Hypothesis testing is a formal procedure for evaluating evidence against a null hypothesis. The process involves: stating the null and alternative hypotheses; selecting a significance level (α, typically 0.05); calculating a test statistic from the data; determining the p-value; and making a decision to reject or fail to reject the null hypothesis.</p><h3>Understanding P-values</h3><p>The p-value is the probability of obtaining results at least as extreme as those observed, assuming the null hypothesis is true. A p-value less than the significance level (p < 0.05) is conventionally considered statistically significant, meaning the evidence against the null hypothesis is strong enough to reject it. Important caveats:</p><ul><li>A p-value does not measure the probability that the null hypothesis is true.</li><li>Statistical significance does not imply clinical or practical significance.</li><li>A non-significant result does not prove the null hypothesis is true.</li><li>P-values are sensitive to sample size — very large samples can produce statistically significant results for trivially small effects.</li></ul><h3>Type I and Type II Errors</h3><p>A Type I error (false positive) occurs when the null hypothesis is rejected when it is actually true. The probability of a Type I error equals the significance level α. A Type II error (false negative) occurs when the null hypothesis is not rejected when it is actually false. The probability of a Type II error is β; statistical power (1-β) is the probability of correctly detecting a true effect. Sample size calculations balance the risks of Type I and Type II errors.</p>',
        3);

        $this->makeSub($topic, 'Confidence Intervals and Effect Measures',
            '<h3>Confidence Intervals</h3><p>A confidence interval (CI) provides a range of plausible values for a population parameter based on sample data. A 95% CI means that if the study were repeated many times, 95% of the calculated intervals would contain the true population value. Confidence intervals are more informative than p-values because they convey both statistical significance (if the CI excludes the null value) and the precision and magnitude of the estimate.</p><h3>Key Effect Measures in Epidemiology</h3><p>Different study designs use different measures to quantify the association between exposure and outcome:</p><ul><li><strong>Risk (cumulative incidence):</strong> The proportion of a population that develops a disease over a defined period. Used in cohort studies and RCTs.</li><li><strong>Risk ratio (relative risk, RR):</strong> The ratio of risk in the exposed group to risk in the unexposed group. RR > 1 indicates increased risk; RR < 1 indicates protective effect.</li><li><strong>Odds ratio (OR):</strong> The ratio of the odds of exposure among cases to the odds of exposure among controls. Used in case-control studies. Approximates the RR when the disease is rare.</li><li><strong>Incidence rate ratio (IRR):</strong> The ratio of incidence rates in exposed and unexposed groups. Used when follow-up time varies between participants.</li><li><strong>Number needed to treat (NNT):</strong> The number of patients who need to receive a treatment for one additional patient to benefit. A clinically intuitive measure used in RCTs.</li></ul>',
        4);
    }

    // =========================================================================
    // TOPIC 4 — Epidemiology and Disease Measurement
    // =========================================================================
    private function seedTopic4(Course $course): void
    {
        $topic = $this->makeTopic($course,
            'Epidemiology and Disease Measurement',
            'Measuring disease frequency, understanding disease distribution, and applying epidemiological methods to health problems in South Sudan.',
            4
        );

        $this->makeSub($topic, 'Measures of Disease Frequency',
            '<h3>Prevalence and Incidence</h3><p>Two fundamental measures of disease frequency are prevalence and incidence:</p><ul><li><strong>Prevalence</strong> measures the proportion of a population that has a disease at a specific point in time (point prevalence) or during a defined period (period prevalence). Prevalence = Number of existing cases / Total population at risk. Prevalence is useful for planning health services and estimating disease burden.</li><li><strong>Incidence</strong> measures the rate at which new cases of a disease develop in a population over time. Cumulative incidence (risk) = New cases / Population at risk at start of period. Incidence rate = New cases / Person-time at risk. Incidence is more useful for understanding disease aetiology and evaluating preventive interventions.</li></ul><h3>Mortality Measures</h3><p>Key mortality measures used in South Sudan health reporting include: crude death rate (deaths per 1,000 population per year); cause-specific mortality rate (deaths from a specific cause per 100,000 population); case fatality rate (proportion of people with a disease who die from it); maternal mortality ratio (maternal deaths per 100,000 live births); and infant mortality rate (deaths in children under one year per 1,000 live births). South Sudan has some of the highest maternal and infant mortality rates in the world, making these measures particularly important for monitoring health system performance.</p>',
        1);

        $this->makeSub($topic, 'Epidemiological Transition and Disease Burden in South Sudan',
            '<h3>The Double Burden of Disease</h3><p>South Sudan faces a double burden of disease — a high burden of communicable diseases alongside a growing burden of non-communicable diseases (NCDs). Communicable diseases including malaria, tuberculosis, HIV/AIDS, cholera, and neglected tropical diseases remain the leading causes of morbidity and mortality. At the same time, NCDs such as hypertension, diabetes, and mental health disorders are increasing, particularly in urban areas.</p><h3>Measuring Disease Burden</h3><p>The Global Burden of Disease (GBD) study uses disability-adjusted life years (DALYs) to measure the total burden of disease, combining years of life lost due to premature death (YLL) and years lived with disability (YLD). One DALY represents one year of healthy life lost. DALYs enable comparison of the burden of different diseases and conditions, informing priority-setting for health interventions. Understanding the DALY concept is important for health researchers in South Sudan who need to communicate the magnitude of health problems to policymakers and donors.</p><h3>Health Inequities in South Sudan</h3><p>Disease burden in South Sudan is not evenly distributed. Rural populations, women, children, internally displaced persons, and people in conflict-affected areas bear a disproportionate burden of disease. Epidemiological research must disaggregate data by sex, age, location, and other equity dimensions to reveal these inequities and inform targeted interventions.</p>',
        2);

        $this->makeSub($topic, 'Outbreak Investigation',
            '<h3>Steps in an Outbreak Investigation</h3><p>Outbreak investigation is a core epidemiological skill for health professionals in South Sudan, where disease outbreaks — including cholera, measles, meningitis, and Ebola — occur regularly. The standard steps in an outbreak investigation are:</p><ol><li><strong>Prepare for field work:</strong> Assemble the investigation team, gather supplies, review background information.</li><li><strong>Establish the existence of an outbreak:</strong> Compare current disease rates with baseline rates to confirm an outbreak is occurring.</li><li><strong>Verify the diagnosis:</strong> Confirm cases through clinical and laboratory investigation.</li><li><strong>Define and identify cases:</strong> Develop a case definition and systematically identify all cases.</li><li><strong>Describe the outbreak:</strong> Characterise cases by person (who), place (where), and time (when) — the epidemiological triad.</li><li><strong>Develop hypotheses:</strong> Based on descriptive epidemiology, generate hypotheses about the source and mode of transmission.</li><li><strong>Test hypotheses:</strong> Conduct analytical studies (case-control or cohort) to test hypotheses.</li><li><strong>Implement control measures:</strong> Implement and evaluate control measures based on findings.</li><li><strong>Communicate findings:</strong> Write an outbreak investigation report and disseminate findings.</li></ol>',
        3);

        $this->makeSub($topic, 'Screening and Diagnostic Test Evaluation',
            '<h3>Evaluating Diagnostic Tests</h3><p>Health researchers and clinicians in South Sudan frequently need to evaluate the performance of diagnostic tests, particularly for diseases such as malaria, HIV, and tuberculosis where rapid diagnostic tests are widely used. Key measures of diagnostic test performance include:</p><ul><li><strong>Sensitivity:</strong> The proportion of people with the disease who test positive (true positive rate). A highly sensitive test misses few cases — important for screening.</li><li><strong>Specificity:</strong> The proportion of people without the disease who test negative (true negative rate). A highly specific test produces few false positives — important for confirmatory testing.</li><li><strong>Positive predictive value (PPV):</strong> The proportion of people who test positive who actually have the disease. Depends on disease prevalence — PPV is lower when disease prevalence is low.</li><li><strong>Negative predictive value (NPV):</strong> The proportion of people who test negative who actually do not have the disease.</li><li><strong>Likelihood ratios:</strong> Measures of how much a test result changes the probability of disease. More stable across different disease prevalences than PPV and NPV.</li></ul><h3>The ROC Curve</h3><p>The receiver operating characteristic (ROC) curve plots sensitivity against (1-specificity) across all possible test thresholds. The area under the ROC curve (AUC) measures overall test performance: AUC of 1.0 indicates a perfect test; AUC of 0.5 indicates a test no better than chance.</p>',
        4);
    }

    // =========================================================================
    // TOPIC 5 — Data Collection and Management
    // =========================================================================
    private function seedTopic5(Course $course): void
    {
        $topic = $this->makeTopic($course,
            'Data Collection and Management',
            'Designing data collection instruments, managing research data, and using digital tools for health research in South Sudan.',
            5
        );

        $this->makeSub($topic, 'Designing Data Collection Instruments',
            '<h3>Questionnaire Design Principles</h3><p>A well-designed questionnaire is essential for collecting valid and reliable data. Key principles of questionnaire design include:</p><ul><li><strong>Clarity:</strong> Questions should be clear, unambiguous, and written in simple language appropriate for the target population.</li><li><strong>Relevance:</strong> Every question should be necessary to answer the research question. Avoid collecting data that will not be used.</li><li><strong>Neutrality:</strong> Questions should not lead respondents toward a particular answer (avoid leading questions).</li><li><strong>Logical flow:</strong> Questions should be organised in a logical sequence, moving from general to specific and from less sensitive to more sensitive topics.</li><li><strong>Appropriate response options:</strong> Response options should be exhaustive (covering all possible answers) and mutually exclusive (no overlap between options).</li></ul><h3>Types of Questions</h3><p>Closed-ended questions provide fixed response options and are easier to analyse quantitatively. Open-ended questions allow respondents to answer in their own words and are useful for capturing nuanced information. Likert scales measure attitudes or opinions on a continuum (e.g., strongly agree to strongly disagree). Visual analogue scales are useful for measuring pain or other subjective experiences, particularly with low-literacy populations.</p><h3>Pilot Testing</h3><p>All data collection instruments should be pilot tested with a small sample from the target population before the main study. Pilot testing identifies unclear questions, translation problems, and logistical issues. In South Sudan, pilot testing is particularly important because of language diversity and varying literacy levels.</p>',
        1);

        $this->makeSub($topic, 'Digital Data Collection Tools',
            '<h3>Mobile Data Collection in South Sudan</h3><p>Digital data collection tools have transformed health research in South Sudan by enabling real-time data collection, reducing data entry errors, and facilitating data management in field settings. The most widely used platforms include:</p><ul><li><strong>KoBoToolbox:</strong> A free, open-source platform widely used by UN agencies and NGOs in humanitarian settings. Supports offline data collection, GPS coordinates, photo capture, and complex skip logic. Particularly well-suited to South Sudan field conditions.</li><li><strong>ODK (Open Data Kit):</strong> Another open-source platform with similar capabilities to KoBoToolbox. Used extensively in global health research.</li><li><strong>REDCap (Research Electronic Data Capture):</strong> A secure web-based platform designed for clinical and translational research. Provides advanced data management features including audit trails and role-based access control.</li><li><strong>CommCare:</strong> A mobile platform designed for community health worker data collection and case management.</li></ul><h3>Advantages and Limitations</h3><p>Digital data collection reduces transcription errors, enables real-time data quality checks, and facilitates faster data analysis. However, it requires reliable devices, adequate battery life, and some digital literacy among data collectors. In remote areas of South Sudan with limited electricity, paper-based backup systems may still be necessary.</p>',
        2);

        $this->makeSub($topic, 'Data Quality Assurance in Research',
            '<h3>Validity and Reliability</h3><p>Two fundamental properties of measurement in health research are validity and reliability:</p><ul><li><strong>Validity</strong> refers to whether a measurement tool actually measures what it is intended to measure. Content validity assesses whether the instrument covers all relevant aspects of the construct. Construct validity assesses whether the instrument measures the theoretical construct it is supposed to measure. Criterion validity assesses whether the instrument correlates with a gold standard measure.</li><li><strong>Reliability</strong> refers to the consistency of a measurement — whether it produces the same results under the same conditions. Test-retest reliability measures consistency over time. Inter-rater reliability measures consistency between different observers or raters.</li></ul><h3>Data Quality Control Procedures</h3><p>Practical data quality control procedures for health research in South Sudan include: training data collectors thoroughly before data collection begins; conducting regular supervision visits during data collection; implementing double data entry for paper-based data; using built-in validation rules in digital data collection platforms; conducting regular data quality checks during analysis; and maintaining a data audit trail documenting all changes to the dataset.</p>',
        3);

        $this->makeSub($topic, 'Data Management and Storage',
            '<h3>Research Data Management Principles</h3><p>Good research data management ensures that data are organised, documented, secure, and accessible throughout the research lifecycle. Key principles include:</p><ul><li><strong>Data organisation:</strong> Use consistent file naming conventions, folder structures, and version control. Maintain a master dataset and working copies.</li><li><strong>Data documentation:</strong> Create a data dictionary that defines all variables, their coding, and any transformations applied. Document all data cleaning decisions.</li><li><strong>Data security:</strong> Protect participant confidentiality by removing or encrypting identifying information. Store data on password-protected devices and secure servers. Limit access to authorised team members only.</li><li><strong>Data backup:</strong> Maintain multiple backups in different locations (e.g., local hard drive, external drive, cloud storage). In South Sudan, where power outages and device theft are risks, regular backups are essential.</li><li><strong>Data retention:</strong> Research data should typically be retained for a minimum of 5-10 years after study completion, in accordance with institutional and funder requirements.</li></ul><h3>Data Sharing and Open Science</h3><p>There is growing expectation that health research data will be shared openly to maximise the value of research investments. Data sharing must balance the benefits of open science with the obligation to protect participant confidentiality. De-identification, data use agreements, and controlled access repositories are mechanisms for enabling data sharing while protecting privacy.</p>',
        4);
    }

    // =========================================================================
    // TOPIC 6 — Statistical Analysis Methods
    // =========================================================================
    private function seedTopic6(Course $course): void
    {
        $topic = $this->makeTopic($course,
            'Statistical Analysis Methods',
            'Applying appropriate statistical tests and regression methods to analyse health research data.',
            6
        );

        $this->makeSub($topic, 'Choosing the Right Statistical Test',
            '<h3>A Framework for Test Selection</h3><p>Selecting the appropriate statistical test depends on: the type of outcome variable (continuous, binary, count, time-to-event); the number of groups being compared; whether the data are paired or independent; and whether the data meet the assumptions of parametric tests (primarily normality). A systematic approach to test selection:</p><ul><li><strong>Comparing two independent groups, continuous outcome:</strong> Independent samples t-test (if normally distributed) or Mann-Whitney U test (if not normally distributed or ordinal).</li><li><strong>Comparing two paired groups, continuous outcome:</strong> Paired t-test (if normally distributed) or Wilcoxon signed-rank test.</li><li><strong>Comparing three or more independent groups, continuous outcome:</strong> One-way ANOVA (if normally distributed) or Kruskal-Wallis test.</li><li><strong>Association between two categorical variables:</strong> Chi-squared test (if expected cell counts ≥ 5) or Fisher\'s exact test (if expected cell counts < 5).</li><li><strong>Correlation between two continuous variables:</strong> Pearson correlation (if normally distributed) or Spearman rank correlation.</li></ul>',
        1);

        $this->makeSub($topic, 'Regression Analysis',
            '<h3>Linear Regression</h3><p>Linear regression models the relationship between a continuous outcome variable and one or more predictor variables. Simple linear regression involves one predictor; multiple linear regression involves two or more predictors. The regression coefficient (β) represents the change in the outcome for a one-unit change in the predictor, holding other predictors constant. Linear regression assumes: linearity, independence of observations, homoscedasticity (constant variance of residuals), and normality of residuals.</p><h3>Logistic Regression</h3><p>Logistic regression is used when the outcome variable is binary (e.g., disease present/absent, died/survived). It models the log odds of the outcome as a linear function of the predictors. The exponentiated regression coefficient gives the odds ratio (OR) for each predictor. Logistic regression is one of the most commonly used statistical methods in health research. Multiple logistic regression allows adjustment for confounding variables — essential for observational studies where confounding is a major concern.</p><h3>Survival Analysis</h3><p>Survival analysis (time-to-event analysis) is used when the outcome is the time until an event occurs (e.g., time to death, time to disease recurrence, time to treatment failure). The Kaplan-Meier method estimates the survival function and produces survival curves. The log-rank test compares survival curves between groups. Cox proportional hazards regression models the effect of predictors on the hazard rate while adjusting for confounders.</p>',
        2);

        $this->makeSub($topic, 'Confounding and Effect Modification',
            '<h3>Confounding</h3><p>Confounding occurs when a third variable (confounder) is associated with both the exposure and the outcome, distorting the apparent relationship between them. For example, in a study of the association between alcohol consumption and lung cancer, smoking is a confounder because smokers are more likely to drink alcohol and smoking causes lung cancer. Failing to control for confounding leads to biased estimates of effect.</p><p>Methods to control confounding include: restriction (limiting the study to one level of the confounder); matching (pairing cases and controls on confounders); stratification (analysing the association separately within strata of the confounder); and multivariable regression (including confounders as covariates in the regression model).</p><h3>Effect Modification (Interaction)</h3><p>Effect modification occurs when the effect of an exposure on an outcome differs across levels of a third variable (the effect modifier). Unlike confounding, effect modification is a real biological phenomenon that should be reported, not controlled for. For example, the effect of a nutritional intervention on child growth may differ between boys and girls — sex is an effect modifier. Identifying effect modification requires stratified analysis and statistical tests for interaction.</p>',
        3);

        $this->makeSub($topic, 'Qualitative Data Analysis',
            '<h3>Approaches to Qualitative Analysis</h3><p>Qualitative data analysis involves systematic processes for identifying patterns, themes, and meanings in non-numerical data. Common approaches include:</p><ul><li><strong>Thematic analysis:</strong> Identifies, analyses, and reports themes within qualitative data. The most widely used approach in health research. Involves familiarisation with data, generating initial codes, searching for themes, reviewing themes, defining and naming themes, and writing up.</li><li><strong>Framework analysis:</strong> Uses a pre-defined analytical framework to organise and interpret data. Particularly useful for applied policy research where specific questions need to be answered.</li><li><strong>Grounded theory analysis:</strong> Develops theory inductively from data through constant comparison and theoretical sampling.</li><li><strong>Content analysis:</strong> Systematically categorises and counts the frequency of specific content in text data. Can be qualitative or quantitative.</li></ul><h3>Rigour in Qualitative Research</h3><p>Rigour in qualitative research is assessed using criteria of credibility (confidence in the truth of the findings), transferability (applicability to other contexts), dependability (consistency of findings), and confirmability (objectivity). Strategies to enhance rigour include: prolonged engagement with participants; triangulation (using multiple data sources or methods); member checking (sharing findings with participants for validation); reflexivity (researchers reflecting on their own influence on the research); and thick description (detailed contextual description enabling transferability assessment).</p>',
        4);
    }

    // =========================================================================
    // TOPIC 7 — Scientific Writing and Research Dissemination
    // =========================================================================
    private function seedTopic7(Course $course): void
    {
        $topic = $this->makeTopic($course,
            'Scientific Writing and Research Dissemination',
            'Writing scientific papers, research reports, and policy briefs, and disseminating health research findings effectively.',
            7
        );

        $this->makeSub($topic, 'Structure of a Scientific Paper',
            '<h3>The IMRaD Structure</h3><p>Most scientific papers in health research follow the IMRaD structure: Introduction, Methods, Results, and Discussion. Each section has a specific purpose:</p><ul><li><strong>Introduction:</strong> Provides background on the research problem, reviews relevant literature, identifies the knowledge gap, and states the research question and objectives. Should move from broad context to the specific research question.</li><li><strong>Methods:</strong> Describes the study design, setting, population, sampling strategy, data collection instruments, data management procedures, and statistical analysis methods in sufficient detail for the study to be replicated. Ethics approval and consent procedures should be described.</li><li><strong>Results:</strong> Presents the findings of the study objectively, without interpretation. Uses tables and figures to present data clearly. Follows a logical sequence aligned with the research objectives.</li><li><strong>Discussion:</strong> Interprets the findings in the context of existing literature, explains unexpected results, acknowledges limitations, and discusses implications for policy and practice. Ends with conclusions and recommendations.</li></ul><h3>Abstract Writing</h3><p>The abstract is often the only part of a paper that readers see. A structured abstract (Background, Methods, Results, Conclusions) of 250-300 words should accurately summarise the key elements of the paper. The abstract should be written last, after the full paper is complete.</p>',
        1);

        $this->makeSub($topic, 'Critical Appraisal of Health Research',
            '<h3>Why Critical Appraisal Matters</h3><p>Not all published research is of equal quality. Health professionals must be able to critically evaluate published research to determine whether findings are valid, important, and applicable to their practice context. Critical appraisal involves systematically assessing the methodology, results, and conclusions of a study.</p><h3>Critical Appraisal Tools</h3><p>Several tools are available to guide critical appraisal of different study types:</p><ul><li><strong>CASP (Critical Appraisal Skills Programme) checklists:</strong> Separate checklists for RCTs, cohort studies, case-control studies, systematic reviews, qualitative studies, and other designs.</li><li><strong>CONSORT statement:</strong> Reporting guidelines for RCTs, including a checklist of items that should be reported.</li><li><strong>STROBE statement:</strong> Reporting guidelines for observational studies (cohort, case-control, cross-sectional).</li><li><strong>PRISMA statement:</strong> Reporting guidelines for systematic reviews and meta-analyses.</li></ul><h3>Assessing Internal and External Validity</h3><p>Internal validity refers to whether the study findings accurately reflect the true relationship between exposure and outcome in the study population. Threats to internal validity include selection bias, information bias, and confounding. External validity (generalisability) refers to whether the findings can be applied to other populations and settings. In South Sudan, external validity of research conducted in other countries must be carefully assessed before applying findings to local practice.</p>',
        2);

        $this->makeSub($topic, 'Systematic Reviews and Meta-Analysis',
            '<h3>What is a Systematic Review?</h3><p>A systematic review is a rigorous synthesis of all available evidence on a specific research question, using explicit and reproducible methods to identify, select, and critically appraise relevant studies. Systematic reviews provide the highest level of evidence for health interventions and are the foundation of evidence-based clinical guidelines. The Cochrane Collaboration is the leading organisation producing systematic reviews in health care.</p><h3>Steps in a Systematic Review</h3><ol><li>Formulate the review question using PICO</li><li>Develop and register a review protocol (e.g., on PROSPERO)</li><li>Conduct a comprehensive literature search across multiple databases</li><li>Screen titles and abstracts for eligibility</li><li>Retrieve and assess full texts of potentially eligible studies</li><li>Extract data from included studies</li><li>Assess risk of bias in included studies</li><li>Synthesise findings (narratively or through meta-analysis)</li><li>Assess certainty of evidence using GRADE</li><li>Write and publish the review</li></ol><h3>Meta-Analysis</h3><p>Meta-analysis is a statistical technique for combining quantitative results from multiple studies to produce a pooled estimate of effect. A forest plot displays the results of individual studies and the pooled estimate. Heterogeneity (variation in results between studies) is assessed using the I² statistic. When heterogeneity is high, a random-effects model is preferred over a fixed-effects model. Funnel plots assess publication bias.</p>',
        3);

        $this->makeSub($topic, 'Research Dissemination and Knowledge Translation',
            '<h3>Dissemination Strategies</h3><p>Producing research findings is only valuable if those findings reach and influence the people who can act on them. Effective dissemination requires tailoring the message and medium to the audience:</p><ul><li><strong>Scientific publications:</strong> Peer-reviewed journal articles reach academic and research audiences. Open-access publication is important for ensuring findings are accessible in low-resource settings like South Sudan.</li><li><strong>Conference presentations:</strong> Oral and poster presentations at national and international conferences reach research and policy communities.</li><li><strong>Policy briefs:</strong> Short (2-4 page) documents summarising research findings and their policy implications for government officials and decision-makers. Should be written in plain language, avoiding technical jargon.</li><li><strong>Media engagement:</strong> Press releases, media interviews, and social media can reach broader audiences including the general public and community leaders.</li><li><strong>Community feedback:</strong> Sharing findings with the communities that participated in the research is both an ethical obligation and an important dissemination strategy.</li></ul><h3>Knowledge Translation in South Sudan</h3><p>Knowledge translation — the process of moving research evidence into policy and practice — is a major challenge in South Sudan. Barriers include: limited research capacity; weak links between researchers and policymakers; low demand for evidence in policy processes; and limited access to published research. Strategies to improve knowledge translation include: engaging policymakers as partners in research design; producing policy-relevant research outputs; building relationships with Ministry of Health officials; and participating in health sector coordination mechanisms.</p>',
        4);
    }

    // =========================================================================
    // EXAM QUESTIONS
    // =========================================================================
    private function seedQuestions(Course $course): void
    {
        $questions = [
            ['question' => 'Which study design is considered the gold standard for evaluating the effectiveness of health interventions?', 'a' => 'Cross-sectional study', 'b' => 'Case-control study', 'c' => 'Randomised controlled trial', 'd' => 'Cohort study', 'answer' => 'C', 'explanation' => 'The randomised controlled trial (RCT) is the gold standard because randomisation controls for confounding, allowing causal inference about intervention effectiveness.'],
            ['question' => 'What does the PICO framework stand for in health research?', 'a' => 'Population, Intervention, Comparison, Outcome', 'b' => 'Problem, Indicator, Context, Objective', 'c' => 'Prevalence, Incidence, Cohort, Observation', 'd' => 'Participant, Instrument, Control, Output', 'answer' => 'A', 'explanation' => 'PICO stands for Population, Intervention, Comparison, Outcome — a framework for structuring clinical and health research questions.'],
            ['question' => 'A cross-sectional study measures exposure and outcome at:', 'a' => 'Multiple time points over several years', 'b' => 'A single point in time', 'c' => 'The start and end of an intervention', 'd' => 'Regular intervals throughout follow-up', 'answer' => 'B', 'explanation' => 'Cross-sectional studies measure both exposure and outcome at a single point in time, making them unable to establish temporal relationships.'],
            ['question' => 'Which measure of central tendency is most appropriate for skewed data?', 'a' => 'Mean', 'b' => 'Mode', 'c' => 'Median', 'd' => 'Standard deviation', 'answer' => 'C', 'explanation' => 'The median is robust to outliers and skewness, making it the preferred measure of central tendency for skewed distributions.'],
            ['question' => 'A p-value of 0.03 means:', 'a' => 'There is a 3% probability that the null hypothesis is true', 'b' => 'There is a 3% probability of obtaining results this extreme if the null hypothesis is true', 'c' => 'The effect size is 3%', 'd' => 'The study has 97% power', 'answer' => 'B', 'explanation' => 'The p-value is the probability of obtaining results at least as extreme as observed, assuming the null hypothesis is true. It does not give the probability that the null hypothesis is true.'],
            ['question' => 'Sensitivity of a diagnostic test is defined as:', 'a' => 'The proportion of people without disease who test negative', 'b' => 'The proportion of people with disease who test positive', 'c' => 'The proportion of positive tests that are true positives', 'd' => 'The proportion of negative tests that are true negatives', 'answer' => 'B', 'explanation' => 'Sensitivity is the true positive rate — the proportion of people who have the disease who correctly test positive.'],
            ['question' => 'Which sampling method is most appropriate when a complete sampling frame is unavailable in a field survey?', 'a' => 'Simple random sampling', 'b' => 'Systematic sampling', 'c' => 'Cluster sampling', 'd' => 'Stratified sampling', 'answer' => 'C', 'explanation' => 'Cluster sampling selects groups (clusters) rather than individuals, making it practical when a complete list of individuals is unavailable — common in field surveys in South Sudan.'],
            ['question' => 'What is the odds ratio used to measure in a case-control study?', 'a' => 'The incidence of disease in exposed vs. unexposed groups', 'b' => 'The ratio of odds of exposure among cases vs. controls', 'c' => 'The prevalence of exposure in the population', 'd' => 'The survival probability over time', 'answer' => 'B', 'explanation' => 'In a case-control study, the odds ratio compares the odds of exposure among cases (those with disease) to the odds of exposure among controls (those without disease).'],
            ['question' => 'Which digital data collection platform is most widely used in humanitarian health settings in South Sudan?', 'a' => 'REDCap', 'b' => 'SPSS', 'c' => 'KoBoToolbox', 'd' => 'Stata', 'answer' => 'C', 'explanation' => 'KoBoToolbox is a free, open-source platform widely used by UN agencies and NGOs in humanitarian settings, including South Sudan, for offline mobile data collection.'],
            ['question' => 'A Type I error in hypothesis testing occurs when:', 'a' => 'The null hypothesis is not rejected when it is false', 'b' => 'The null hypothesis is rejected when it is true', 'c' => 'The sample size is too small', 'd' => 'The p-value exceeds the significance level', 'answer' => 'B', 'explanation' => 'A Type I error (false positive) occurs when the null hypothesis is rejected when it is actually true. Its probability equals the significance level α.'],
            ['question' => 'What does the I² statistic measure in a meta-analysis?', 'a' => 'The overall effect size', 'b' => 'The risk of publication bias', 'c' => 'The degree of heterogeneity between studies', 'd' => 'The sample size of included studies', 'answer' => 'C', 'explanation' => 'The I² statistic quantifies the proportion of total variation in study estimates due to heterogeneity (true variation between studies) rather than sampling error.'],
            ['question' => 'Which regression method is appropriate when the outcome variable is binary?', 'a' => 'Linear regression', 'b' => 'Logistic regression', 'c' => 'Poisson regression', 'd' => 'Cox regression', 'answer' => 'B', 'explanation' => 'Logistic regression is used when the outcome is binary (e.g., disease present/absent). It models the log odds of the outcome and produces odds ratios.'],
            ['question' => 'The CONSORT statement provides reporting guidelines for:', 'a' => 'Systematic reviews', 'b' => 'Observational studies', 'c' => 'Randomised controlled trials', 'd' => 'Qualitative studies', 'answer' => 'C', 'explanation' => 'CONSORT (Consolidated Standards of Reporting Trials) provides a checklist of items that should be reported in publications of randomised controlled trials.'],
            ['question' => 'Confounding in epidemiological research refers to:', 'a' => 'Random error in measurement', 'b' => 'A third variable that distorts the apparent relationship between exposure and outcome', 'c' => 'Variation in results between studies', 'd' => 'Bias introduced by selective publication', 'answer' => 'B', 'explanation' => 'A confounder is associated with both the exposure and the outcome, distorting the apparent relationship between them if not controlled for.'],
            ['question' => 'What is the primary purpose of pilot testing a data collection instrument?', 'a' => 'To collect preliminary data for publication', 'b' => 'To identify unclear questions, translation problems, and logistical issues before the main study', 'c' => 'To train data collectors in statistical analysis', 'd' => 'To obtain ethics approval', 'answer' => 'B', 'explanation' => 'Pilot testing identifies problems with the instrument before the main study, allowing corrections that improve data quality.'],
            ['question' => 'The Kaplan-Meier method is used in:', 'a' => 'Logistic regression analysis', 'b' => 'Survival analysis to estimate the survival function', 'c' => 'Meta-analysis to pool effect estimates', 'd' => 'Qualitative thematic analysis', 'answer' => 'B', 'explanation' => 'The Kaplan-Meier method estimates the survival function (probability of surviving beyond a given time) and produces survival curves for time-to-event data.'],
            ['question' => 'Which qualitative analysis approach is most widely used in health research?', 'a' => 'Grounded theory', 'b' => 'Ethnography', 'c' => 'Thematic analysis', 'd' => 'Discourse analysis', 'answer' => 'C', 'explanation' => 'Thematic analysis is the most widely used qualitative analysis approach in health research, involving systematic identification and reporting of themes within qualitative data.'],
            ['question' => 'Prevalence is defined as:', 'a' => 'The rate at which new cases develop over time', 'b' => 'The proportion of a population that has a disease at a specific point in time', 'c' => 'The number of deaths from a disease per 100,000 population', 'd' => 'The probability of developing a disease over a lifetime', 'answer' => 'B', 'explanation' => 'Prevalence measures the proportion of a population that has a disease at a specific point in time (point prevalence) or during a defined period (period prevalence).'],
            ['question' => 'What does DALY stand for in disease burden measurement?', 'a' => 'Disease-Adjusted Life Year', 'b' => 'Disability-Adjusted Life Year', 'c' => 'Death-Adjusted Longitudinal Year', 'd' => 'Diagnosis-Adjusted Lifetime Years', 'answer' => 'B', 'explanation' => 'DALY stands for Disability-Adjusted Life Year — a measure combining years of life lost due to premature death and years lived with disability.'],
            ['question' => 'Which statement about confidence intervals is correct?', 'a' => 'A 95% CI means there is a 95% probability the true value lies within the interval', 'b' => 'A wider CI indicates greater precision', 'c' => 'A 95% CI that excludes the null value indicates statistical significance at p < 0.05', 'd' => 'Confidence intervals are only used in qualitative research', 'answer' => 'C', 'explanation' => 'A 95% CI that excludes the null value (e.g., OR=1 for odds ratios, or 0 for differences) corresponds to statistical significance at the 0.05 level.'],
            ['question' => 'The IMRaD structure of a scientific paper stands for:', 'a' => 'Introduction, Methodology, Results, and Discussion', 'b' => 'Introduction, Methods, Results, and Discussion', 'c' => 'Inquiry, Measurement, Research, and Data', 'd' => 'Introduction, Materials, Review, and Dissemination', 'answer' => 'B', 'explanation' => 'IMRaD stands for Introduction, Methods, Results, and Discussion — the standard structure for scientific papers in health research.'],
            ['question' => 'Effect modification in epidemiology should be:', 'a' => 'Controlled for using multivariable regression', 'b' => 'Ignored if the p-value for interaction is > 0.05', 'c' => 'Reported as a real biological phenomenon', 'd' => 'Treated the same as confounding', 'answer' => 'C', 'explanation' => 'Effect modification is a real biological phenomenon where the effect of an exposure differs across levels of a third variable. It should be reported, not controlled for.'],
            ['question' => 'Which measure is most stable across different disease prevalences when evaluating a diagnostic test?', 'a' => 'Positive predictive value', 'b' => 'Negative predictive value', 'c' => 'Likelihood ratio', 'd' => 'Accuracy', 'answer' => 'C', 'explanation' => 'Likelihood ratios are more stable across different disease prevalences than PPV and NPV, which change substantially as prevalence changes.'],
            ['question' => 'What is the purpose of a data dictionary in research data management?', 'a' => 'To translate questionnaires into local languages', 'b' => 'To define all variables, their coding, and any transformations applied', 'c' => 'To store participant contact information', 'd' => 'To record field notes from qualitative interviews', 'answer' => 'B', 'explanation' => 'A data dictionary documents all variables in a dataset, including their names, definitions, coding schemes, and any transformations, enabling correct interpretation and reuse of the data.'],
            ['question' => 'In a cohort study, the risk ratio (relative risk) is calculated as:', 'a' => 'Odds of disease in exposed / Odds of disease in unexposed', 'b' => 'Risk of disease in exposed / Risk of disease in unexposed', 'c' => 'Incidence in cases / Incidence in controls', 'd' => 'Prevalence in exposed / Prevalence in unexposed', 'answer' => 'B', 'explanation' => 'The risk ratio (relative risk) is the ratio of the risk (cumulative incidence) of disease in the exposed group to the risk in the unexposed group.'],
            ['question' => 'Which step comes immediately before data collection in the research process?', 'a' => 'Data analysis', 'b' => 'Literature review', 'c' => 'Ethics approval', 'd' => 'Dissemination of findings', 'answer' => 'C', 'explanation' => 'Ethics approval must be obtained before data collection begins. Conducting research without ethics approval is an ethical violation.'],
            ['question' => 'The FINER criteria for a good research problem stand for:', 'a' => 'Feasible, Interesting, Novel, Ethical, Relevant', 'b' => 'Focused, Innovative, Necessary, Empirical, Rigorous', 'c' => 'Flexible, Integrated, Neutral, Exploratory, Replicable', 'd' => 'Funded, Interdisciplinary, Novel, Ethical, Reproducible', 'answer' => 'A', 'explanation' => 'FINER stands for Feasible, Interesting, Novel, Ethical, Relevant — criteria for evaluating whether a research problem is worth pursuing.'],
            ['question' => 'What is the primary advantage of a systematic review over a single study?', 'a' => 'It is faster to conduct', 'b' => 'It synthesises all available evidence, providing more reliable conclusions', 'c' => 'It requires less statistical expertise', 'd' => 'It does not require ethics approval', 'answer' => 'B', 'explanation' => 'Systematic reviews synthesise all available evidence on a question using rigorous methods, providing more reliable and comprehensive conclusions than any single study.'],
            ['question' => 'Which non-probability sampling method is most appropriate for qualitative research when participants are hard to reach?', 'a' => 'Simple random sampling', 'b' => 'Stratified sampling', 'c' => 'Snowball sampling', 'd' => 'Cluster sampling', 'answer' => 'C', 'explanation' => 'Snowball sampling, where participants recruit other participants, is useful for reaching hard-to-access populations in qualitative research.'],
            ['question' => 'A policy brief differs from a scientific paper primarily in that it:', 'a' => 'Contains more statistical detail', 'b' => 'Is written in plain language for decision-makers and is much shorter', 'c' => 'Does not require peer review', 'd' => 'Only presents negative findings', 'answer' => 'B', 'explanation' => 'A policy brief is a short (2-4 page) document written in plain language for policymakers, summarising research findings and their policy implications without technical jargon.'],
            ['question' => 'What does the area under the ROC curve (AUC) of 0.5 indicate?', 'a' => 'A perfect diagnostic test', 'b' => 'A test no better than chance', 'c' => 'A test with 50% sensitivity', 'd' => 'A test with 50% specificity', 'answer' => 'B', 'explanation' => 'An AUC of 0.5 indicates that the test performs no better than random chance. An AUC of 1.0 indicates a perfect test.'],
            ['question' => 'Which statistical test is appropriate for comparing a continuous outcome between three or more independent groups with normally distributed data?', 'a' => 'Chi-squared test', 'b' => 'Mann-Whitney U test', 'c' => 'One-way ANOVA', 'd' => 'Paired t-test', 'answer' => 'C', 'explanation' => 'One-way ANOVA (Analysis of Variance) is used to compare means of a continuous, normally distributed outcome across three or more independent groups.'],
            ['question' => 'Specificity of a diagnostic test is defined as:', 'a' => 'The proportion of people with disease who test positive', 'b' => 'The proportion of people without disease who test negative', 'c' => 'The proportion of positive tests that are correct', 'd' => 'The proportion of negative tests that are correct', 'answer' => 'B', 'explanation' => 'Specificity is the true negative rate — the proportion of people who do not have the disease who correctly test negative.'],
            ['question' => 'In qualitative research, data saturation refers to:', 'a' => 'The point at which the dataset is complete', 'b' => 'The point at which no new themes emerge from additional data collection', 'c' => 'The maximum sample size allowed by ethics guidelines', 'd' => 'The point at which quantitative and qualitative data are integrated', 'answer' => 'B', 'explanation' => 'Data saturation is the point in qualitative data collection when no new themes or insights emerge from additional participants, indicating sufficient data has been collected.'],
            ['question' => 'Which reporting guideline applies to observational studies (cohort, case-control, cross-sectional)?', 'a' => 'CONSORT', 'b' => 'PRISMA', 'c' => 'STROBE', 'd' => 'CASP', 'answer' => 'C', 'explanation' => 'STROBE (Strengthening the Reporting of Observational Studies in Epidemiology) provides reporting guidelines for cohort, case-control, and cross-sectional studies.'],
        ];

        foreach ($questions as $i => $q) {
            $this->makeQuestion($course, $q, $i + 1);
        }
    }

    // =========================================================================
    // DOWNLOADS
    // =========================================================================
    private function seedDownloads(Course $course): void
    {
        $this->makeDownload(
            $course,
            'Research Methods and Biostatistics Reference Guide',
            'research-methods-biostatistics-reference-guide.pdf',
            'application/pdf',
            2621440
        );

        $this->makeDownload(
            $course,
            'Statistical Test Selection Flowchart',
            'statistical-test-selection-flowchart.pdf',
            'application/pdf',
            524288
        );
    }
}
