<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class PharmacyTestExamSeeder extends Seeder
{
    public function run(): void
    {
        DB::transaction(function () {
            $courses = [
                'Pharmacology',
                'Pharmaceutics',
                'Clinical Pharmacy',
                'Pharmaceutical Chemistry',
                'Pharmacognosy',
            ];

            foreach ($courses as $index => $course) {
                DB::table('courses')->updateOrInsert(
                    ['slug' => Str::slug($course)],
                    [
                        'name' => $course,
                        'description' => $course . ' license exam preparation questions.',
                        'is_active' => true,
                        'sort_order' => $index + 1,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]
                );
            }

            $courseIds = DB::table('courses')->pluck('id', 'name');

            $fullExamId = DB::table('exams')->insertGetId([
                'course_id' => null,
                'title' => 'Full Pharmacy License Mock Exam',
                'description' => 'Questions selected across all pharmacy courses.',
                'type' => 'full',
                'duration_minutes' => 180,
                'total_questions' => 25,
                'pass_mark' => 50,
                'is_premium' => false,
                'is_active' => true,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            foreach ($courseIds as $courseName => $courseId) {
                DB::table('exams')->insert([
                    'course_id' => $courseId,
                    'title' => $courseName . ' Test Exam',
                    'description' => 'Practice test for ' . $courseName . '.',
                    'type' => 'course',
                    'duration_minutes' => 45,
                    'total_questions' => 5,
                    'pass_mark' => 50,
                    'is_premium' => false,
                    'is_active' => true,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }

            $questions = [
                'Pharmacology' => [
                    [
                        'question' => 'Which class of drugs is commonly used as first-line therapy for uncomplicated hypertension in many adult patients?',
                        'options' => ['Antimalarials', 'Thiazide diuretics', 'Antitussives', 'Anthelmintics', 'Antacids'],
                        'answer' => 'Thiazide diuretics',
                        'explanation' => 'Thiazide diuretics reduce blood pressure by promoting sodium and water excretion and are commonly used in hypertension management.',
                    ],
                    [
                        'question' => 'Which drug is an opioid receptor antagonist used in opioid overdose?',
                        'options' => ['Naloxone', 'Atropine', 'Diazepam', 'Adrenaline', 'Furosemide'],
                        'answer' => 'Naloxone',
                        'explanation' => 'Naloxone reverses opioid toxicity by competitively blocking opioid receptors.',
                    ],
                    [
                        'question' => 'Which adverse effect is strongly associated with aminoglycosides?',
                        'options' => ['Ototoxicity', 'Hypoglycaemia', 'Constipation', 'Tooth discoloration', 'Dry cough'],
                        'answer' => 'Ototoxicity',
                        'explanation' => 'Aminoglycosides such as gentamicin can cause ototoxicity and nephrotoxicity.',
                    ],
                    [
                        'question' => 'Which drug is commonly used for acute relief of bronchospasm in asthma?',
                        'options' => ['Salbutamol', 'Amlodipine', 'Metformin', 'Omeprazole', 'Warfarin'],
                        'answer' => 'Salbutamol',
                        'explanation' => 'Salbutamol is a short-acting beta-2 agonist used for quick relief of bronchospasm.',
                    ],
                    [
                        'question' => 'Warfarin primarily acts by inhibiting the synthesis of clotting factors dependent on which vitamin?',
                        'options' => ['Vitamin A', 'Vitamin B12', 'Vitamin C', 'Vitamin D', 'Vitamin K'],
                        'answer' => 'Vitamin K',
                        'explanation' => 'Warfarin inhibits vitamin K epoxide reductase, reducing activation of vitamin K-dependent clotting factors.',
                    ],
                ],

                'Pharmaceutics' => [
                    [
                        'question' => 'Which dosage form is designed to dissolve or disintegrate in the rectum?',
                        'options' => ['Tablet', 'Capsule', 'Suppository', 'Syrup', 'Elixir'],
                        'answer' => 'Suppository',
                        'explanation' => 'Suppositories are solid dosage forms inserted into body cavities such as the rectum.',
                    ],
                    [
                        'question' => 'Which excipient is commonly used as a tablet disintegrant?',
                        'options' => ['Starch', 'Talc', 'Sucrose syrup', 'Liquid paraffin', 'Ethanol'],
                        'answer' => 'Starch',
                        'explanation' => 'Starch helps tablets break apart after administration, improving drug release.',
                    ],
                    [
                        'question' => 'What is the main purpose of enteric coating?',
                        'options' => ['Improve sweetness', 'Prevent release in the stomach', 'Increase tablet colour', 'Reduce tablet size', 'Improve odour only'],
                        'answer' => 'Prevent release in the stomach',
                        'explanation' => 'Enteric coatings resist gastric acid and allow drug release in the intestine.',
                    ],
                    [
                        'question' => 'Which process reduces particle size in pharmaceutical manufacturing?',
                        'options' => ['Milling', 'Sterilization', 'Filtration', 'Lyophilization', 'Coating'],
                        'answer' => 'Milling',
                        'explanation' => 'Milling is used to reduce particle size and improve uniformity or dissolution.',
                    ],
                    [
                        'question' => 'A suspension must be shaken before use mainly because particles may:',
                        'options' => ['Evaporate', 'Settle on standing', 'Become sterile', 'Change to gas', 'Dissolve completely'],
                        'answer' => 'Settle on standing',
                        'explanation' => 'Suspensions contain undissolved particles that may settle, so shaking redistributes them.',
                    ],
                ],

                'Clinical Pharmacy' => [
                    [
                        'question' => 'A patient taking metformin should be monitored mainly for which serious rare adverse effect?',
                        'options' => ['Lactic acidosis', 'Ototoxicity', 'Tooth staining', 'Hypertrichosis', 'Cataract'],
                        'answer' => 'Lactic acidosis',
                        'explanation' => 'Metformin rarely causes lactic acidosis, especially in renal impairment or severe illness.',
                    ],
                    [
                        'question' => 'Which parameter is most important when monitoring warfarin therapy?',
                        'options' => ['INR', 'Blood glucose', 'Serum calcium', 'Urine pH', 'Body temperature'],
                        'answer' => 'INR',
                        'explanation' => 'INR is used to monitor anticoagulation intensity and bleeding risk during warfarin therapy.',
                    ],
                    [
                        'question' => 'Which counselling point is appropriate for oral rehydration salts?',
                        'options' => ['Mix with correct volume of clean water', 'Take only with milk', 'Boil after mixing', 'Use half sachet always', 'Store mixed solution for one week'],
                        'answer' => 'Mix with correct volume of clean water',
                        'explanation' => 'ORS must be mixed with the stated volume of clean water to avoid incorrect electrolyte concentration.',
                    ],
                    [
                        'question' => 'Which drug interaction is clinically important with nitrates?',
                        'options' => ['Sildenafil', 'Paracetamol', 'Vitamin C', 'Loratadine', 'Ferrous sulphate'],
                        'answer' => 'Sildenafil',
                        'explanation' => 'Sildenafil with nitrates can cause severe hypotension.',
                    ],
                    [
                        'question' => 'Which sign may suggest hypoglycaemia in a diabetic patient?',
                        'options' => ['Sweating and tremor', 'Dry cough', 'Blue sclera', 'Constipation only', 'Hair loss'],
                        'answer' => 'Sweating and tremor',
                        'explanation' => 'Hypoglycaemia commonly presents with sweating, tremor, hunger, confusion and palpitations.',
                    ],
                ],

                'Pharmaceutical Chemistry' => [
                    [
                        'question' => 'Which functional group is present in carboxylic acids?',
                        'options' => ['-COOH', '-OH only', '-NH2 only', '-CHO', '-O-'],
                        'answer' => '-COOH',
                        'explanation' => 'Carboxylic acids contain the carboxyl functional group, written as -COOH.',
                    ],
                    [
                        'question' => 'A weak acid is mostly unionized in which environment?',
                        'options' => ['Acidic medium', 'Strongly alkaline medium', 'Neutral salt only', 'Distilled oil', 'Gas phase only'],
                        'answer' => 'Acidic medium',
                        'explanation' => 'Weak acids are more unionized in acidic environments, which can affect absorption.',
                    ],
                    [
                        'question' => 'Which technique is commonly used to separate compounds based on polarity?',
                        'options' => ['Chromatography', 'Autoclaving', 'Compression', 'Granulation', 'Coating'],
                        'answer' => 'Chromatography',
                        'explanation' => 'Chromatography separates compounds based on interactions with stationary and mobile phases.',
                    ],
                    [
                        'question' => 'Oxidation generally involves:',
                        'options' => ['Loss of electrons', 'Gain of electrons', 'No electron change', 'Only melting', 'Only filtration'],
                        'answer' => 'Loss of electrons',
                        'explanation' => 'Oxidation is the loss of electrons, while reduction is the gain of electrons.',
                    ],
                    [
                        'question' => 'Which bond is most associated with sharing of electrons?',
                        'options' => ['Covalent bond', 'Ionic bond', 'Hydrogen gas bond', 'Metallic salt only', 'Van der Waals only'],
                        'answer' => 'Covalent bond',
                        'explanation' => 'Covalent bonds involve sharing of electrons between atoms.',
                    ],
                ],

                'Pharmacognosy' => [
                    [
                        'question' => 'Pharmacognosy is primarily concerned with drugs obtained from:',
                        'options' => ['Natural sources', 'Only synthetic metals', 'Only petroleum gases', 'Only radioactive isotopes', 'Only plastic polymers'],
                        'answer' => 'Natural sources',
                        'explanation' => 'Pharmacognosy studies medicinal substances from natural sources such as plants, animals and microorganisms.',
                    ],
                    [
                        'question' => 'Which plant is commonly associated with cardiac glycosides?',
                        'options' => ['Digitalis', 'Aloe vera', 'Ginger', 'Garlic', 'Hibiscus'],
                        'answer' => 'Digitalis',
                        'explanation' => 'Digitalis species contain cardiac glycosides such as digoxin-like compounds.',
                    ],
                    [
                        'question' => 'Alkaloids are generally known to contain:',
                        'options' => ['Nitrogen', 'Chlorine only', 'Helium', 'Gold', 'Silicon only'],
                        'answer' => 'Nitrogen',
                        'explanation' => 'Alkaloids are nitrogen-containing natural compounds with significant pharmacological activity.',
                    ],
                    [
                        'question' => 'Which plant part is commonly used as a source of volatile oils?',
                        'options' => ['Leaves and flowers', 'Glass container', 'Plastic cap', 'Metal rod', 'Synthetic rubber'],
                        'answer' => 'Leaves and flowers',
                        'explanation' => 'Volatile oils are often obtained from aromatic plant parts such as leaves, flowers, peels or seeds.',
                    ],
                    [
                        'question' => 'Which method is commonly used for extracting active constituents from crude drugs?',
                        'options' => ['Maceration', 'Tablet compression', 'Autoclaving only', 'Capsule polishing', 'Film coating only'],
                        'answer' => 'Maceration',
                        'explanation' => 'Maceration involves soaking crude drugs in a solvent to extract active constituents.',
                    ],
                ],
            ];

            foreach ($questions as $courseName => $items) {
                $courseId = $courseIds[$courseName];

                foreach ($items as $item) {
                    $questionId = DB::table('questions')->insertGetId([
                        'course_id' => $courseId,
                        'question' => $item['question'],
                        'explanation' => $item['explanation'],
                        'is_active' => true,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);

                    $keys = ['A', 'B', 'C', 'D', 'E'];

                    foreach ($item['options'] as $optionIndex => $option) {
                        DB::table('question_options')->insert([
                            'question_id' => $questionId,
                            'option_key' => $keys[$optionIndex] ?? chr(65 + $optionIndex),
                            'option_text' => $option,
                            'is_correct' => $option === $item['answer'],
                            'created_at' => now(),
                            'updated_at' => now(),
                        ]);
                    }
                }
            }
        });
    }
}