<?php
/**
 * Generate 30 Researchers with Complete Profiles
 * OBGYN Research Platform
 */

require_once __DIR__ . '/../config/database.php';

try {
    $db = getDB();
    $db->beginTransaction();

    // Researcher data
    $researchers = [
        [
            'first_name' => 'Sarah',
            'last_name' => 'Johnson',
            'email' => 'sarah.johnson@research.edu',
            'specialization' => 'Maternal-Fetal Medicine',
            'institution' => 'Harvard Medical School',
            'department' => 'Obstetrics and Gynecology',
            'position' => 'Associate Professor',
            'bio' => 'Dr. Sarah Johnson is a leading researcher in maternal-fetal medicine with over 15 years of experience. Her work focuses on high-risk pregnancies and fetal development.',
            'research_interests' => 'High-risk pregnancies, Fetal development, Prenatal diagnosis',
            'publications_count' => 45,
            'citations_count' => 1250,
            'h_index' => 18,
            'orcid' => '0000-0001-2345-6789',
            'linkedin' => 'https://linkedin.com/in/sarahjohnson-md',
            'website' => 'https://sarahjohnson.research.edu'
        ],
        [
            'first_name' => 'Michael',
            'last_name' => 'Chen',
            'email' => 'michael.chen@med.university.edu',
            'specialization' => 'Gynecologic Oncology',
            'institution' => 'Stanford University School of Medicine',
            'department' => 'Gynecologic Oncology',
            'position' => 'Professor',
            'bio' => 'Dr. Michael Chen specializes in gynecologic cancers with a focus on novel therapeutic approaches and clinical trials.',
            'research_interests' => 'Gynecologic cancers, Clinical trials, Targeted therapies',
            'publications_count' => 67,
            'citations_count' => 2100,
            'h_index' => 24,
            'orcid' => '0000-0002-3456-7890',
            'linkedin' => 'https://linkedin.com/in/michaelchen-md',
            'website' => 'https://michaelchen.med.edu'
        ],
        [
            'first_name' => 'Emily',
            'last_name' => 'Rodriguez',
            'email' => 'emily.rodriguez@research.org',
            'specialization' => 'Reproductive Endocrinology',
            'institution' => 'Mayo Clinic',
            'department' => 'Reproductive Medicine',
            'position' => 'Assistant Professor',
            'bio' => 'Dr. Emily Rodriguez is an expert in reproductive endocrinology and infertility treatments.',
            'research_interests' => 'Infertility, IVF, Reproductive endocrinology',
            'publications_count' => 32,
            'citations_count' => 890,
            'h_index' => 15,
            'orcid' => '0000-0003-4567-8901',
            'linkedin' => 'https://linkedin.com/in/emilyrodriguez-md',
            'website' => 'https://emilyrodriguez.research.org'
        ],
        [
            'first_name' => 'David',
            'last_name' => 'Williams',
            'email' => 'david.williams@university.edu',
            'specialization' => 'Urogynecology',
            'institution' => 'Johns Hopkins University',
            'department' => 'Urogynecology',
            'position' => 'Professor',
            'bio' => 'Dr. David Williams specializes in pelvic floor disorders and reconstructive surgery.',
            'research_interests' => 'Pelvic floor disorders, Reconstructive surgery, Fecal incontinence',
            'publications_count' => 58,
            'citations_count' => 1650,
            'h_index' => 22,
            'orcid' => '0000-0004-5678-9012',
            'linkedin' => 'https://linkedin.com/in/davidwilliams-md',
            'website' => 'https://davidwilliams.university.edu'
        ],
        [
            'first_name' => 'Lisa',
            'last_name' => 'Thompson',
            'email' => 'lisa.thompson@medcenter.edu',
            'specialization' => 'Menopause Medicine',
            'institution' => 'Cleveland Clinic',
            'department' => 'Women\'s Health Institute',
            'position' => 'Director',
            'bio' => 'Dr. Lisa Thompson is a pioneer in menopause research and hormone therapy optimization.',
            'research_interests' => 'Menopause, Hormone therapy, Women\'s health',
            'publications_count' => 41,
            'citations_count' => 1100,
            'h_index' => 17,
            'orcid' => '0000-0005-6789-0123',
            'linkedin' => 'https://linkedin.com/in/lisathompson-md',
            'website' => 'https://lisathompson.medcenter.edu'
        ],
        [
            'first_name' => 'James',
            'last_name' => 'Anderson',
            'email' => 'james.anderson@research.edu',
            'specialization' => 'Clinical Obstetrics',
            'institution' => 'University of California, San Francisco',
            'department' => 'Obstetrics',
            'position' => 'Associate Professor',
            'bio' => 'Dr. James Anderson focuses on clinical obstetrics and labor management techniques.',
            'research_interests' => 'Labor management, Obstetric complications, Cesarean delivery',
            'publications_count' => 39,
            'citations_count' => 950,
            'h_index' => 16,
            'orcid' => '0000-0006-7890-1234',
            'linkedin' => 'https://linkedin.com/in/jamesanderson-md',
            'website' => 'https://jamesanderson.research.edu'
        ],
        [
            'first_name' => 'Maria',
            'last_name' => 'Garcia',
            'email' => 'maria.garcia@university.edu',
            'specialization' => 'Pediatric Gynecology',
            'institution' => 'Children\'s Hospital Los Angeles',
            'department' => 'Pediatric Gynecology',
            'position' => 'Chief',
            'bio' => 'Dr. Maria Garcia specializes in pediatric and adolescent gynecology.',
            'research_interests' => 'Pediatric gynecology, Adolescent health, Congenital anomalies',
            'publications_count' => 28,
            'citations_count' => 720,
            'h_index' => 13,
            'orcid' => '0000-0007-8901-2345',
            'linkedin' => 'https://linkedin.com/in/mariagarcia-md',
            'website' => 'https://mariagarcia.university.edu'
        ],
        [
            'first_name' => 'Robert',
            'last_name' => 'Miller',
            'email' => 'robert.miller@med.edu',
            'specialization' => 'Gynecologic Surgery',
            'institution' => 'Massachusetts General Hospital',
            'department' => 'Gynecologic Surgery',
            'position' => 'Professor',
            'bio' => 'Dr. Robert Miller is an expert in minimally invasive gynecologic surgery.',
            'research_interests' => 'Minimally invasive surgery, Laparoscopy, Robotic surgery',
            'publications_count' => 72,
            'citations_count' => 2400,
            'h_index' => 28,
            'orcid' => '0000-0008-9012-3456',
            'linkedin' => 'https://linkedin.com/in/robertmiller-md',
            'website' => 'https://robertmiller.med.edu'
        ],
        [
            'first_name' => 'Jennifer',
            'last_name' => 'Davis',
            'email' => 'jennifer.davis@research.org',
            'specialization' => 'Reproductive Genetics',
            'institution' => 'Genomic Medicine Institute',
            'department' => 'Reproductive Genetics',
            'position' => 'Director',
            'bio' => 'Dr. Jennifer Davis leads research in reproductive genetics and genetic counseling.',
            'research_interests' => 'Reproductive genetics, Genetic counseling, Prenatal testing',
            'publications_count' => 35,
            'citations_count' => 980,
            'h_index' => 16,
            'orcid' => '0000-0009-0123-4567',
            'linkedin' => 'https://linkedin.com/in/jenniferdavis-md',
            'website' => 'https://jenniferdavis.research.org'
        ],
        [
            'first_name' => 'Christopher',
            'last_name' => 'Brown',
            'email' => 'christopher.brown@university.edu',
            'specialization' => 'Obstetric Ultrasound',
            'institution' => 'Duke University Hospital',
            'department' => 'Maternal-Fetal Medicine',
            'position' => 'Associate Professor',
            'bio' => 'Dr. Christopher Brown specializes in obstetric ultrasound and fetal imaging.',
            'research_interests' => 'Obstetric ultrasound, Fetal imaging, 3D ultrasound',
            'publications_count' => 31,
            'citations_count' => 850,
            'h_index' => 14,
            'orcid' => '0000-0010-1234-5678',
            'linkedin' => 'https://linkedin.com/in/christopherbrown-md',
            'website' => 'https://christopherbrown.university.edu'
        ],
        [
            'first_name' => 'Amanda',
            'last_name' => 'Wilson',
            'email' => 'amanda.wilson@medcenter.edu',
            'specialization' => 'Contraceptive Research',
            'institution' => 'Planned Parenthood Research Institute',
            'department' => 'Contraceptive Development',
            'position' => 'Research Scientist',
            'bio' => 'Dr. Amanda Wilson researches novel contraceptive methods and family planning.',
            'research_interests' => 'Contraception, Family planning, Reproductive health',
            'publications_count' => 26,
            'citations_count' => 650,
            'h_index' => 12,
            'orcid' => '0000-0011-2345-6789',
            'linkedin' => 'https://linkedin.com/in/amandawilson-md',
            'website' => 'https://amandawilson.medcenter.edu'
        ],
        [
            'first_name' => 'Kevin',
            'last_name' => 'Martinez',
            'email' => 'kevin.martinez@research.edu',
            'specialization' => 'Endometriosis Research',
            'institution' => 'Endometriosis Research Center',
            'department' => 'Gynecology Research',
            'position' => 'Principal Investigator',
            'bio' => 'Dr. Kevin Martinez leads groundbreaking research on endometriosis diagnosis and treatment.',
            'research_interests' => 'Endometriosis, Chronic pelvic pain, Laparoscopic surgery',
            'publications_count' => 44,
            'citations_count' => 1300,
            'h_index' => 19,
            'orcid' => '0000-0012-3456-7890',
            'linkedin' => 'https://linkedin.com/in/kevinmartinez-md',
            'website' => 'https://kevinmartinez.research.edu'
        ],
        [
            'first_name' => 'Rachel',
            'last_name' => 'Taylor',
            'email' => 'rachel.taylor@university.edu',
            'specialization' => 'Breast Health',
            'institution' => 'University of Texas MD Anderson',
            'department' => 'Breast Gynecology',
            'position' => 'Assistant Professor',
            'bio' => 'Dr. Rachel Taylor specializes in breast health and gynecologic oncology screening.',
            'research_interests' => 'Breast cancer screening, Gynecologic oncology, Women\'s health',
            'publications_count' => 29,
            'citations_count' => 780,
            'h_index' => 13,
            'orcid' => '0000-0013-4567-8901',
            'linkedin' => 'https://linkedin.com/in/racheltaylor-md',
            'website' => 'https://racheltaylor.university.edu'
        ],
        [
            'first_name' => 'Daniel',
            'last_name' => 'Lee',
            'email' => 'daniel.lee@med.edu',
            'specialization' => 'Fetal Surgery',
            'institution' => 'Fetal Medicine Institute',
            'department' => 'Fetal Surgery',
            'position' => 'Director',
            'bio' => 'Dr. Daniel Lee pioneers fetal surgical interventions and prenatal treatments.',
            'research_interests' => 'Fetal surgery, Prenatal interventions, Congenital defects',
            'publications_count' => 53,
            'citations_count' => 1800,
            'h_index' => 23,
            'orcid' => '0000-0014-5678-9012',
            'linkedin' => 'https://linkedin.com/in/daniellee-md',
            'website' => 'https://daniellee.med.edu'
        ],
        [
            'first_name' => 'Michelle',
            'last_name' => 'Clark',
            'email' => 'michelle.clark@research.org',
            'specialization' => 'Adolescent Gynecology',
            'institution' => 'Adolescent Health Center',
            'department' => 'Adolescent Medicine',
            'position' => 'Medical Director',
            'bio' => 'Dr. Michelle Clark focuses on adolescent reproductive health and education.',
            'research_interests' => 'Adolescent health, Reproductive education, Teen pregnancy prevention',
            'publications_count' => 22,
            'citations_count' => 550,
            'h_index' => 11,
            'orcid' => '0000-0015-6789-0123',
            'linkedin' => 'https://linkedin.com/in/michelleclark-md',
            'website' => 'https://michelleclark.research.org'
        ],
        [
            'first_name' => 'Steven',
            'last_name' => 'White',
            'email' => 'steven.white@university.edu',
            'specialization' => 'Pelvic Pain Research',
            'institution' => 'Pelvic Pain Research Institute',
            'department' => 'Gynecology',
            'position' => 'Research Director',
            'bio' => 'Dr. Steven White researches chronic pelvic pain syndromes and treatment modalities.',
            'research_interests' => 'Chronic pelvic pain, Pain management, Quality of life',
            'publications_count' => 38,
            'citations_count' => 1050,
            'h_index' => 16,
            'orcid' => '0000-0016-7890-1234',
            'linkedin' => 'https://linkedin.com/in/stevenwhite-md',
            'website' => 'https://stevenwhite.university.edu'
        ],
        [
            'first_name' => 'Laura',
            'last_name' => 'Harris',
            'email' => 'laura.harris@medcenter.edu',
            'specialization' => 'Obesity and Reproduction',
            'institution' => 'Reproductive Health Center',
            'department' => 'Reproductive Endocrinology',
            'position' => 'Associate Professor',
            'bio' => 'Dr. Laura Harris studies the intersection of obesity and reproductive health.',
            'research_interests' => 'Obesity, Reproductive health, Fertility outcomes',
            'publications_count' => 33,
            'citations_count' => 920,
            'h_index' => 15,
            'orcid' => '0000-0017-8901-2345',
            'linkedin' => 'https://linkedin.com/in/lauraharris-md',
            'website' => 'https://lauraharris.medcenter.edu'
        ],
        [
            'first_name' => 'Thomas',
            'last_name' => 'Lewis',
            'email' => 'thomas.lewis@research.edu',
            'specialization' => 'Stem Cell Research',
            'institution' => 'Stem Cell Research Center',
            'department' => 'Regenerative Medicine',
            'position' => 'Principal Investigator',
            'bio' => 'Dr. Thomas Lewis researches stem cell applications in gynecologic tissue regeneration.',
            'research_interests' => 'Stem cells, Tissue regeneration, Gynecologic reconstruction',
            'publications_count' => 47,
            'citations_count' => 1400,
            'h_index' => 20,
            'orcid' => '0000-0018-9012-3456',
            'linkedin' => 'https://linkedin.com/in/thomaslewis-md',
            'website' => 'https://thomaslewis.research.edu'
        ],
        [
            'first_name' => 'Jessica',
            'last_name' => 'Walker',
            'email' => 'jessica.walker@university.edu',
            'specialization' => 'Global Health',
            'institution' => 'Global Women\'s Health Initiative',
            'department' => 'International Health',
            'position' => 'Director',
            'bio' => 'Dr. Jessica Walker works on global maternal health initiatives in developing countries.',
            'research_interests' => 'Global health, Maternal mortality, Health equity',
            'publications_count' => 25,
            'citations_count' => 680,
            'h_index' => 12,
            'orcid' => '0000-0019-0123-4567',
            'linkedin' => 'https://linkedin.com/in/jessicawalker-md',
            'website' => 'https://jessicawalker.university.edu'
        ],
        [
            'first_name' => 'Brian',
            'last_name' => 'Hall',
            'email' => 'brian.hall@med.edu',
            'specialization' => 'Immunology in Pregnancy',
            'institution' => 'Immunology Research Center',
            'department' => 'Reproductive Immunology',
            'position' => 'Professor',
            'bio' => 'Dr. Brian Hall studies immunological aspects of pregnancy and preeclampsia.',
            'research_interests' => 'Reproductive immunology, Preeclampsia, Pregnancy complications',
            'publications_count' => 51,
            'citations_count' => 1600,
            'h_index' => 21,
            'orcid' => '0000-0020-1234-5678',
            'linkedin' => 'https://linkedin.com/in/brianhall-md',
            'website' => 'https://brianhall.med.edu'
        ],
        [
            'first_name' => 'Nicole',
            'last_name' => 'Young',
            'email' => 'nicole.young@research.org',
            'specialization' => 'Mental Health in Pregnancy',
            'institution' => 'Perinatal Mental Health Center',
            'department' => 'Psychiatry',
            'position' => 'Clinical Researcher',
            'bio' => 'Dr. Nicole Young researches perinatal mental health and postpartum depression.',
            'research_interests' => 'Perinatal mental health, Postpartum depression, Maternal mental health',
            'publications_count' => 19,
            'citations_count' => 480,
            'h_index' => 10,
            'orcid' => '0000-0021-2345-6789',
            'linkedin' => 'https://linkedin.com/in/nicoleyoung-md',
            'website' => 'https://nicoleyoung.research.org'
        ],
        [
            'first_name' => 'Mark',
            'last_name' => 'King',
            'email' => 'mark.king@university.edu',
            'specialization' => 'Sports Gynecology',
            'institution' => 'Women\'s Sports Medicine Center',
            'department' => 'Sports Medicine',
            'position' => 'Director',
            'bio' => 'Dr. Mark King specializes in gynecologic issues affecting female athletes.',
            'research_interests' => 'Sports gynecology, Female athletes, Exercise physiology',
            'publications_count' => 27,
            'citations_count' => 710,
            'h_index' => 13,
            'orcid' => '0000-0022-3456-7890',
            'linkedin' => 'https://linkedin.com/in/markking-md',
            'website' => 'https://markking.university.edu'
        ],
        [
            'first_name' => 'Stephanie',
            'last_name' => 'Wright',
            'email' => 'stephanie.wright@medcenter.edu',
            'specialization' => 'HIV in Pregnancy',
            'institution' => 'Infectious Diseases Center',
            'department' => 'Maternal HIV',
            'position' => 'Research Coordinator',
            'bio' => 'Dr. Stephanie Wright studies HIV transmission prevention in pregnancy.',
            'research_interests' => 'HIV in pregnancy, Antiretroviral therapy, Vertical transmission',
            'publications_count' => 36,
            'citations_count' => 990,
            'h_index' => 15,
            'orcid' => '0000-0023-4567-8901',
            'linkedin' => 'https://linkedin.com/in/stephaniewright-md',
            'website' => 'https://stephaniewright.medcenter.edu'
        ],
        [
            'first_name' => 'Anthony',
            'last_name' => 'Lopez',
            'email' => 'anthony.lopez@research.edu',
            'specialization' => 'Artificial Intelligence in OB/GYN',
            'institution' => 'AI Health Research Lab',
            'department' => 'Digital Health',
            'position' => 'Chief Scientist',
            'bio' => 'Dr. Anthony Lopez develops AI applications for obstetric and gynecologic care.',
            'research_interests' => 'Artificial intelligence, Digital health, Predictive analytics',
            'publications_count' => 42,
            'citations_count' => 1200,
            'h_index' => 18,
            'orcid' => '0000-0024-5678-9012',
            'linkedin' => 'https://linkedin.com/in/anthonylopez-md',
            'website' => 'https://anthonylopez.research.edu'
        ],
        [
            'first_name' => 'Heather',
            'last_name' => 'Hill',
            'email' => 'heather.hill@university.edu',
            'specialization' => 'Environmental Health',
            'institution' => 'Environmental Health Institute',
            'department' => 'Reproductive Toxicology',
            'position' => 'Associate Professor',
            'bio' => 'Dr. Heather Hill studies environmental factors affecting reproductive health.',
            'research_interests' => 'Environmental health, Reproductive toxicology, Endocrine disruptors',
            'publications_count' => 30,
            'citations_count' => 820,
            'h_index' => 14,
            'orcid' => '0000-0025-6789-0123',
            'linkedin' => 'https://linkedin.com/in/heatherhill-md',
            'website' => 'https://heatherhill.university.edu'
        ],
        [
            'first_name' => 'Eric',
            'last_name' => 'Green',
            'email' => 'eric.green@med.edu',
            'specialization' => 'Robotic Surgery',
            'institution' => 'Robotic Surgery Center',
            'department' => 'Minimally Invasive Surgery',
            'position' => 'Director',
            'bio' => 'Dr. Eric Green pioneers robotic surgical techniques in gynecology.',
            'research_interests' => 'Robotic surgery, Minimally invasive techniques, Surgical outcomes',
            'publications_count' => 49,
            'citations_count' => 1500,
            'h_index' => 20,
            'orcid' => '0000-0026-7890-1234',
            'linkedin' => 'https://linkedin.com/in/ericgreen-md',
            'website' => 'https://ericgreen.med.edu'
        ],
        [
            'first_name' => 'Angela',
            'last_name' => 'Adams',
            'email' => 'angela.adams@research.org',
            'specialization' => 'Telemedicine',
            'institution' => 'Digital Health Institute',
            'department' => 'Telemedicine',
            'position' => 'Research Lead',
            'bio' => 'Dr. Angela Adams researches telemedicine applications in women\'s health.',
            'research_interests' => 'Telemedicine, Digital health, Rural healthcare',
            'publications_count' => 24,
            'citations_count' => 620,
            'h_index' => 11,
            'orcid' => '0000-0027-8901-2345',
            'linkedin' => 'https://linkedin.com/in/angelaadams-md',
            'website' => 'https://angelaadams.research.org'
        ],
        [
            'first_name' => 'Patrick',
            'last_name' => 'Baker',
            'email' => 'patrick.baker@university.edu',
            'specialization' => 'Nutrition in Pregnancy',
            'institution' => 'Nutrition Research Center',
            'department' => 'Maternal Nutrition',
            'position' => 'Professor',
            'bio' => 'Dr. Patrick Baker studies nutritional interventions during pregnancy.',
            'research_interests' => 'Maternal nutrition, Pregnancy outcomes, Dietary interventions',
            'publications_count' => 34,
            'citations_count' => 950,
            'h_index' => 16,
            'orcid' => '0000-0028-9012-3456',
            'linkedin' => 'https://linkedin.com/in/patrickbaker-md',
            'website' => 'https://patrickbaker.university.edu'
        ],
        [
            'first_name' => 'Melissa',
            'last_name' => 'Nelson',
            'email' => 'melissa.nelson@medcenter.edu',
            'specialization' => 'Health Policy',
            'institution' => 'Health Policy Research Institute',
            'department' => 'Health Policy',
            'position' => 'Policy Analyst',
            'bio' => 'Dr. Melissa Nelson researches health policy affecting women\'s reproductive care.',
            'research_interests' => 'Health policy, Reproductive rights, Healthcare access',
            'publications_count' => 21,
            'citations_count' => 540,
            'h_index' => 10,
            'orcid' => '0000-0029-0123-4567',
            'linkedin' => 'https://linkedin.com/in/melissanelson-md',
            'website' => 'https://melissanelson.medcenter.edu'
        ],
        [
            'first_name' => 'Ryan',
            'last_name' => 'Carter',
            'email' => 'ryan.carter@research.edu',
            'specialization' => 'Bioethics',
            'institution' => 'Center for Bioethics',
            'department' => 'Medical Ethics',
            'position' => 'Ethics Consultant',
            'bio' => 'Dr. Ryan Carter addresses ethical issues in reproductive medicine and research.',
            'research_interests' => 'Bioethics, Reproductive medicine, Research ethics',
            'publications_count' => 18,
            'citations_count' => 450,
            'h_index' => 9,
            'orcid' => '0000-0030-1234-5678',
            'linkedin' => 'https://linkedin.com/in/ryancarter-md',
            'website' => 'https://ryancarter.research.edu'
        ]
    ];

    $successCount = 0;
    $errorCount = 0;

    // Get researcher role ID
    $stmt = $db->prepare("SELECT id FROM roles WHERE name = 'researcher' LIMIT 1");
    $stmt->execute();
    $researcherRole = $stmt->fetch();

    if (!$researcherRole) {
        throw new Exception("Researcher role not found in database");
    }

    $roleId = $researcherRole['id'];

    // Create uploads directory if it doesn't exist
    $uploadsDir = __DIR__ . '/../assets/uploads/profile_pictures/';
    if (!is_dir($uploadsDir)) {
        mkdir($uploadsDir, 0755, true);
    }

    foreach ($researchers as $index => $researcher) {
        try {
            // Generate password hash
            $password = password_hash('Researcher2025!', PASSWORD_DEFAULT);

            // Download random profile picture
            $imageId = $index + 1;
            $imageUrl = "https://picsum.photos/300/300?random={$imageId}";
            $imagePath = $uploadsDir . "researcher_{$imageId}.jpg";

            echo "Attempting to download from: {$imageUrl}\n";
            echo "Saving to: {$imagePath}\n";

            // Download image
            $imageData = file_get_contents($imageUrl);
            if ($imageData !== false) {
                echo "Downloaded " . strlen($imageData) . " bytes of data\n";
                $bytesWritten = file_put_contents($imagePath, $imageData);
                if ($bytesWritten !== false) {
                    echo "Successfully wrote {$bytesWritten} bytes to file\n";
                    if (file_exists($imagePath)) {
                        echo "File exists on disk\n";
                        $profilePicture = "assets/uploads/profile_pictures/researcher_{$imageId}.jpg";
                    } else {
                        echo "File does not exist on disk despite successful write\n";
                        $profilePicture = null;
                    }
                } else {
                    echo "Failed to write file: " . error_get_last()['message'] . "\n";
                    $profilePicture = null;
                }
            } else {
                echo "Failed to download image\n";
                $profilePicture = null;
            }

            // Insert user
            $stmt = $db->prepare("
                INSERT INTO users (
                    email, password, first_name, last_name, role_id,
                    status, email_verified, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, 'active', 1, NOW(), NOW())
            ");
            $stmt->execute([
                $researcher['email'],
                $password,
                $researcher['first_name'],
                $researcher['last_name'],
                $roleId
            ]);

            $userId = $db->lastInsertId();

            // Get or create institution
            $stmt = $db->prepare("SELECT id FROM institutions WHERE name = ? LIMIT 1");
            $stmt->execute([$researcher['institution']]);
            $institution = $stmt->fetch();

            if (!$institution) {
                // Create institution
                $stmt = $db->prepare("
                    INSERT INTO institutions (name, type, country, city, status, created_at, updated_at)
                    VALUES (?, 'university', 'USA', 'Unknown', 'active', NOW(), NOW())
                ");
                $stmt->execute([$researcher['institution']]);
                $institutionId = $db->lastInsertId();
            } else {
                $institutionId = $institution['id'];
            }

            // Insert researcher profile
            $stmt = $db->prepare("
                INSERT INTO researcher_profiles (
                    user_id, photo, title, specialization, institution_id, department,
                    bio, research_interests, publications_count, orcid_id, linkedin,
                    created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
            ");
            $stmt->execute([
                $userId,
                $profilePicture,
                $researcher['position'],
                $researcher['specialization'],
                $institutionId,
                $researcher['department'],
                $researcher['bio'],
                $researcher['research_interests'],
                $researcher['publications_count'],
                $researcher['orcid'],
                $researcher['linkedin']
            ]);

            $successCount++;
            echo "✓ Created researcher: {$researcher['first_name']} {$researcher['last_name']}\n";

        } catch (Exception $e) {
            $errorCount++;
            echo "✗ Error creating researcher {$researcher['first_name']} {$researcher['last_name']}: " . $e->getMessage() . "\n";
        }
    }

    $db->commit();

    echo "\n=== Summary ===\n";
    echo "Researchers created: $successCount\n";
    echo "Errors: $errorCount\n";
    echo "Profile pictures downloaded: " . count(glob($uploadsDir . "*.jpg")) . "\n";

} catch (Exception $e) {
    if (isset($db)) {
        $db->rollBack();
    }
    echo "Fatal error: " . $e->getMessage() . "\n";
}
?>